Over a million developers have joined DZone.

How to Access SMTP & IMAP Servers Using OAuth Inside .NET Apps

Learn how to access SMTP and IMAP servers using OAuth. It's a useful skill for .NET developers, and this tutorial will help you to get started.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

This technical tip explains how .NET developers can Access SMTP & IMAP Server using OAuth inside .NET applications. Aspose.Email for .NET can be used to access SMTP and IMAP servers. OAuth support for Google mail is implemented only for version 2.0 as OAuth 1.0 has been officially deprecated as of April 20, 2012. At this moment, Google supports OAuth only for the Google Apps Platform and public mail accounts can't be used with the OAuth mechanism. When a new Google Apps account is created, a new "Installed Application" should be registered for this account for testing in the APIs Console. Free trial accounts can be created, provided by Google Apps for Business.

The code samples for Accessing SMTP and IMAP Servers Using Aspose.Email are shown below:

//[C# Code Sample]

static void Main(string[] args)
        // The authorizationCode should be replaced with your value.
        // To get authorizationCode use the URL bellow:
        // https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F
        string authorizationCode = "4/zx4_I4ZhhUdmgLdsejpjeMkwAAMs.kk7o1Qx9U28VOl05ti8ZT3Y1uIlidQI";  // authorizationCode should be replaced with new value !!!!!!!
        string accessToken = GetAccessToken(authorizationCode);

    static void AccessSMTPServer(string accessToken)
        MailMessage message = new MailMessage(
            "NETWORKNET-33499 - " + Guid.NewGuid().ToString(),
            "Access to SMTP servers using OAuth");
        using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "user1@testaccount1913.narod2.ru", accessToken, true))
            client.Timeout = 400000;
            client.SecurityMode = SmtpSslSecurityMode.Implicit;
            client.EnableSsl = true;

    static void AccessIMAPServer(string accessToken)
        using (ImapClient client = new ImapClient("imap.gmail.com", 993, "user1@testaccount1913.narod2.ru", accessToken, true))
            client.EnableSsl = true;
            client.SecurityMode = ImapSslSecurityMode.Implicit;
            ImapMessageInfoCollection messageInfoCol = client.ListMessages();

    internal static string GetAccessToken(string authorizationCode)
        string actionUrl = "https://accounts.google.com/o/oauth2/token";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
        request.CookieContainer = new CookieContainer();
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        string encodedParameters = string.Format(
        byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
        request.ContentLength = requestData.Length;
        if (requestData.Length > 0)
            using (Stream stream = request.GetRequestStream())
                stream.Write(requestData, 0, requestData.Length);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string responseText = null;
        using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
            responseText = reader.ReadToEnd();
        string accessToken = null;
        foreach (string sPair in responseText.
            Replace("{", "").
            Replace("}", "").
            Replace("\"", "").
            Split(new string[] { ",\n" }, StringSplitOptions.None))
            string[] pair = sPair.Split(':');
            if ("access_token" == pair[0].Trim())
                accessToken = pair[1].Trim();
        return accessToken;

//[VB.NET Code Sample]

Imports Aspose.Email.Mail
Imports System.Net
Imports Aspose.Email.Imap
Imports System.Text
Imports System.IO
Imports System.Web

Module Module1

    Sub Main()
        ' The authorizationCode should be replaced with your value.
        ' To get authorizationCode use the URL bellow:
        ' https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F
        Dim authorizationCode As String = "4/zx4_I4ZhhUdmgLdsejpjeMkwAAMs.kk7o1Qx9U28VOl05ti8ZT3Y1uIlidQI"
        ' authorizationCode should be replaced with new value !!!!!!!
        Dim accessToken As String = GetAccessToken(authorizationCode)

    End Sub
    Private Sub AccessSMTPServer(ByVal accessToken As String)
        Dim message As New MailMessage("user1@testaccount1913.narod2.ru", "user1@testaccount1913.narod2.ru", "NETWORKNET-33499 - " & Guid.NewGuid().ToString(), "Access to SMTP servers using OAuth")
        Using client As New SmtpClient("smtp.gmail.com", 587, "user1@testaccount1913.narod2.ru", accessToken, True)
            client.Timeout = 400000
            client.SecurityMode = SmtpSslSecurityMode.Implicit
            client.EnableSsl = True
        End Using
    End Sub
    Private Sub AccessIMAPServer(ByVal accessToken As String)
        Using client As New ImapClient("imap.gmail.com", 993, "user1@testaccount1913.narod2.ru", accessToken, True)
            client.EnableSsl = True
            client.SecurityMode = ImapSslSecurityMode.Implicit
            Dim messageInfoCol As ImapMessageInfoCollection = client.ListMessages()
        End Using
    End Sub
    Friend Function GetAccessToken(ByVal authorizationCode As String) As String
        Dim actionUrl As String = "https://accounts.google.com/o/oauth2/token"
        Dim request As HttpWebRequest = DirectCast(WebRequest.Create(actionUrl), HttpWebRequest)
        request.CookieContainer = New CookieContainer()
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        Dim encodedParameters As String = String.Format("client_id={1}&code={0}&client_secret={2}&redirect_uri={3}&grant_type={4}", HttpUtility.UrlEncode(authorizationCode), HttpUtility.UrlEncode("929645059575.apps.googleusercontent.com"), HttpUtility.UrlEncode("USnH5eQRsC4XrjJbpGG7WVq5"), HttpUtility.UrlEncode("urn:ietf:wg:oauth:2.0:oob"), HttpUtility.UrlEncode("authorization_code"))
        Dim requestData As Byte() = Encoding.UTF8.GetBytes(encodedParameters)
        request.ContentLength = requestData.Length
        If requestData.Length > 0 Then
            Using stream As IO.Stream = request.GetRequestStream()
                stream.Write(requestData, 0, requestData.Length)
            End Using
        End If
        Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        Dim responseText As String = Nothing
        Using reader As TextReader = New StreamReader(response.GetResponseStream(), Encoding.ASCII)
            responseText = reader.ReadToEnd()
        End Using
        Dim accessToken As String = Nothing
        For Each sPair As String In responseText.Replace("{", "").Replace("}", "").Replace("""", "").Split(New String() {"," & vbLf}, StringSplitOptions.None)
            Dim pair As String() = sPair.Split(":"c)
            If "access_token" = pair(0).Trim() Then
                accessToken = pair(1).Trim()
                Exit For
            End If
        Return accessToken
    End Function
End Module

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

smtp,imap,.net,web dev

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}