Posts Tagged ‘IMAP’

Archive email in Gmail

Friday, January 6th, 2012

First remember to enable IMAP in Gmail.

You need to use DeleteMessageByUID method. Messages will be still available in All Mail folder.

// C#

using(Imap imap = new Imap())
{
	imap.ConnectSSL("imap.gmail.com");
	imap.Login("user", "password");

	// Find all emails we want to delete
	imap.SelectInbox();
	List<long> uids = imap.Search(
		Expression.Subject("email to archive"));

	imap.DeleteMessageByUID(uids);

	imap.Close();
}
' VB.NET

Using imap As New Imap()
	imap.ConnectSSL("imap.gmail.com")
	imap.Login("user@gmail.com", "password")

	' Find all emails we want to delete
	imap.SelectInbox()
	Dim uids As List(Of Long) = imap.Search(_
		Expression.Subject("email to archive"))

	imap.DeleteMessageByUID(uids)

	imap.Close()
End Using

Enable IMAP in Gmail

Friday, January 6th, 2012

To enable IMAP in Gmail:

  1. Sign in to Gmail.
  2. Click the gear icon in the upper-right and select Mail settings .
  3. Click Forwarding and POP/IMAP.
  4. Select Enable IMAP.
  5. Now you are able to connect to your Gmail account with Mail.dll IMAP library.

Remember that Gmail only allows secure SSL connections so we need to use ConnectSSL method.

OAuth with Gmail

Friday, October 21st, 2011

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

In this post I’ll show how to access Gmail account using 3-legged OAuth authentication method. The key advantage of this method is that it allows an application to access user email without knowing user’s password.

You can read more on OAuth authentication with Google accounts here:
http://code.google.com/apis/accounts/docs/OAuth_ref.html

Gmail IMAP and SMTP using OAuth:
http://code.google.com/apis/gmail/oauth/protocol.html

If your application/website is not registered, you should use following key and secret:
consumer key: “anonymous”
consumer secret: “anonymous”

Remember to add reference to Maill.dll and appropriate namespaces.

// C#

using Lesnikowski.Client.IMAP;
using Lesnikowski.Client.Authentication;
using Lesnikowski.Client.Authentication.Google;

const string userEmailAccount = "pat@gmail.com";
const string consumerKey = "anonymous";
const string consumerSecret = "anonymous";

GmailOAuth oauth = new GmailOAuth(
    consumerKey, consumerSecret);

string url = oauth.GetAuthorizationUrl("http://localhost:64119/");

Process.Start(url);
// You can use Response.Redirect(url) in ASP.NET

string oauthVerifier = HttpUtility.UrlDecode(Console.ReadLine());
// You can use Request["oauth_verifier"].ToString() in ASP.NET

oauth.GetAccessToken(oauthVerifier);

using (Imap client = new Imap())
{
    client.ConnectSSL("imap.gmail.com");
    string oauthImapKey = oauth.GetXOAuthKeyForImap();
    client.LoginOAUTH(oauthImapKey);

    // Now you can access user's emails
    //...

    client.Close();
    oauth.RevokeToken(oauthImapKey);
}

1.
GmailOAuth.GetAuthorizationUrl method returns url you should redirect your user to so he can authorize access.
As you can see Mail.dll is asking for access to user’s email information and Gmail access:

2.
If you don’t specify callback parameter, user will have to manually copy&paste the token to your application:

In case of a web project, you can specify a web address on your website. oauth_verifier will be included as the redirection url parameter.

After the redirection, your website/application needs to read oauth_verifier query parameter:

3.
GmailOAuth.GetAccessToken method authorizes the token.

4.
GmailOAuth.GetXOAuthKeyForImap method uses Google API to get the email address of the user, and generates XOAuth key for IMAP protocol (you can use GetXOAuthKeyForSmtp for SMTP).

5.
GmailOAuth.RevokeToken method revokes XOAuth key, so no further access can be made with it.

…and finally VB.NET version of the code:

' VB.NET

Imports Lesnikowski.Client.IMAP
Imports Lesnikowski.Client.Authentication
Imports Lesnikowski.Client.Authentication.Google

Const userEmailAccount As String = "pat@gmail.com"
Const consumerKey As String = "anonymous"
Const consumerSecret As String = "anonymous"

Dim oauth As New GmailOAuth(consumerKey, consumerSecret)

Dim url As String = oauth.GetAuthorizationUrl("http://localhost:64119/")

Process.Start(url)
' You can use Response.Redirect(url) in ASP.NET

Dim oauthVerifier As String = HttpUtility.UrlDecode(Console.ReadLine())
' You can use Request["oauth_verifier"].ToString() in ASP.NET

oauth.GetAccessToken(oauthVerifier)

Using client As New Imap()
	client.ConnectSSL("imap.gmail.com")
	Dim oauthImapKey As String = oauth.GetXOAuthKeyForImap()
	client.LoginOAUTH(oauthImapKey)

	' Now you can access user's emails
	'...

	client.Close()
	oauth.RevokeToken(oauthImapKey)
End Using

2-legged OAuth with Gmail

Friday, October 21st, 2011

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

In this post I’ll show how to access Gmail account using 2-legged OAuth authentication method. The basic idea is that domain administrator can use this method to access user email without knowing user’s password.

You can read more on OAuth authentication with Google accounts here:
http://code.google.com/apis/accounts/docs/OAuth_ref.html

Gmail IMAP and SMTP using OAuth:
http://code.google.com/apis/gmail/oauth/protocol.html

Remember to add reference to Maill.dll and appropriate namespaces.

// C#

using Lesnikowski.Client.IMAP;
using Lesnikowski.Client.Authentication;
using Lesnikowski.Client.Authentication.Google;

const string consumerKey = "example.com";
const string consumerSecret = "secret";
const string email = "pat@example.com";

Gmail2LeggedOAuth oauth = new Gmail2LeggedOAuth(
    consumerKey, consumerSecret);

using (Imap client = new Imap())
{
    client.ConnectSSL(TestConstants.GmailImapServer);

    string oauthImapKey = oauth.GetXOAuthKeyForImap(email);

    client.LoginOAUTH(oauthImapKey);

    //...

    client.Close();
}
' VB.NET

Imports Lesnikowski.Client.IMAP
Imports Lesnikowski.Client.Authentication
Imports Lesnikowski.Client.Authentication.Google

Const  consumerKey As String = "example.com"
Const  consumerSecret As String = "secret"
Const  email As String = "pat@example.com"

Dim oauth As New Gmail2LeggedOAuth(consumerKey, consumerSecret)

Using client As New Imap()
	client.ConnectSSL(TestConstants.GmailImapServer)

	Dim oauthImapKey As String = oauth.GetXOAuthKeyForImap(email)

	client.LoginOAUTH(oauthImapKey)

	'...

	client.Close()
End Using

Here are the google apps configuration screens:

Get supported authentication methods (IMAP, POP3, SMTP)

Thursday, October 6th, 2011

You can use SupportedAuthenticationMethodsto retrieve all authentication methods supported by the server:

// C#

using (Imap client = new Imap())
{
    client.ConnectSSL("imap.example.org");
    client.UseBestLogin("user", "password");

    Console.WriteLine("Supported methods:");

    foreach (var method in client.SupportedAuthenticationMethods())
    {
        Console.WriteLine(method.Name);
    }

    Console.WriteLine("Supports CramMD5:");

    bool supportsCramMD5 = client.SupportedAuthenticationMethods()
        .Contains(ImapAuthenticationMethod.CramMD5);

    Console.WriteLine(supportsCramMD5);

    client.Close();
}
' VB.NET

Using client As New Imap()
    client.ConnectSSL("imap.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported methods:")

    For Each method As ImapAuthenticationMethod In client.SupportedAuthenticationMethods()
	    Console.WriteLine(method.Name)
    Next

    Console.WriteLine("Supports CramMD5:")

    Dim supportsCramMD5 As Boolean = client.SupportedAuthenticationMethods() _
        .Contains(ImapAuthenticationMethod.CramMD5)

    Console.WriteLine(supportsCramMD5)

    client.Close()
End Using

For example Gmail produces following output:

Supported method s:
IMAP4rev1
UNSELECT
IDLE
NAMESPACE
QUOTA
ID
XLIST
CHILDREN
X-GM-EXT-1
UIDPLUS
COMPRESS

Supports CramMD5:
False

We take great care for the API to look similar for all protocols (IMAP, POP3, SMTP).

Here’s the sample for POP3:

// C#

using (Pop3 client = new Pop3())
{
    client.ConnectSSL("pop3.example.org");
    client.UseBestLogin("user", "password");

    Console.WriteLine("Supported methods:");

    foreach (var method in client.SupportedAuthenticationMethods())
    {
        Console.WriteLine(method.Name);
    }

    Console.WriteLine("Supports CramMD5:");

    bool supportsCramMD5 = client.SupportedAuthenticationMethods()
        .Contains(Pop3AuthenticationMethod.CramMD5);

    Console.WriteLine(supportsCramMD5);

    client.Close();
}
' VB.NET

Using client As New Pop3()
    client.ConnectSSL("pop3.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported methods:")

    For Each method As Pop3AuthenticationMethod In client.SupportedAuthenticationMethods()
	    Console.WriteLine(method.Name)
    Next

    Console.WriteLine("Supports CramMD5:")

    Dim supportsCramMD5 As Boolean = client.SupportedAuthenticationMethods() _
        .Contains(Pop3AuthenticationMethod.CramMD5)

    Console.WriteLine(supportsCramMD5)

    client.Close()
End Using

Here’s the sample for SMTP:

// C#

using (Smtpclient = new Smtp())
{
    client.Connect("smtp.example.org");
    client.UseBestLogin("smtp", "password");

    Console.WriteLine("Supported methods:");

    foreach (var method in client.SupportedAuthenticationMethods())
    {
        Console.WriteLine(method.Name);
    }

    Console.WriteLine("Supports CramMD5:");

    bool supportsCramMD5 = client.SupportedAuthenticationMethods()
        .Contains(SmtpAuthenticationMethod.CramMD5);

    Console.WriteLine(supportsCramMD5);

    client.Close();
}
' VB.NET

Using client As New Smtp()
    client.Connect("smtp.example.org")
    client.UseBestLogin("user", "password")

    Console.WriteLine("Supported methods:")

    For Each method As SmtpAuthenticationMethod In client.SupportedAuthenticationMethods()
	    Console.WriteLine(method.Name)
    Next

    Console.WriteLine("Supports CramMD5:")

    Dim supportsCramMD5 As Boolean = client.SupportedAuthenticationMethods() _
        .Contains(SmtpAuthenticationMethod.CramMD5)

    Console.WriteLine(supportsCramMD5)

    client.Close()
End Using