Mark emails as read using IMAP

January 27th, 2010

First you need to download Mail.dll IMAP client.

The following code connects to IMAP server, downloads unique ids of all unseen emails and marks the first one as seen.

// C# version

using(Imap imap = new Imap())
{
	imap.Connect("server");

	imap.User = "user";
	imap.Password = "password";
	imap.Login();

	imap.SelectInbox();
	List<long> uids = client.SearchFlag(Flag.Unseen);
	if (uids.Count > 0)
		client.MarkMessageSeenByUID(uids[0]);
    imap.Close(true);
}
' VB.NET version

Using imap As New Imap()
	imap.Connect("server")

	imap.User = "user"
	imap.Password = "password"
	imap.Login()

	imap.SelectInbox()
	Dim uids As List(Of Long) = client.SearchFlag(Flag.Unseen)
	If uids.Count > 0 Then
		client.MarkMessageSeenByUID(uids(0))
	End If
	imap.Close(True)
End Using

Please note that it is not possible to mark messages as read using POP3 protocol.

Cross-thread operations with PostSharp

January 26th, 2010

When you try to inform User Interface (UI) about the background operation progress or completion, you can not do it from the background thread.

UI doesn’t like to be informed about anything from a different thread: you’ll get “System.InvalidOperationException: Cross-thread operation not valid: Control ‘xxx’ accessed from a thread other than the thread it was created on.” exception from WinForms control, if you try:

public void ShowStatus(ApplicationStatus status)
{
    this._lblServiceAddress.Text = "Connected to: "
        + status.WebServiceAddress;
    this._lblUserId.Text = "Working as: "
        + status.UserId;
}

The easiest sollution is to use BeginInvoke method on the control Control or Form:

public void ShowStatus(ApplicationStatus status)
{
    this.BeginInvoke((MethodInvoker)(() =>
        {
            this._lblServiceAddress.Text = "Connected to: "
                + status.WebServiceAddress;
            this._lblUserId.Text = "Working as: "
                + status.UserId;
        }));
}

Well, it’s fun to write this once, but if you have many operations done in background sooner or later you’d like to have something nicer. Like an attribute for example:

[ThreadAccessibleUI]
public void ShowStatus(ApplicationStatus status)
{
    this._lblServiceAddress.Text = "Connected to: " + status.WebServiceAddress;
    this._lblUserId.Text = "Working as: " + status.UserId;
}

Here’s the attribute implementation of such attribute using PostSharp 1.5:

/// <summary>
/// PostSharp attribute.
/// Use it to mark Control's methods that
/// are invoked from background thread.
/// </summary>
/// <remarks>
/// Be careful as BeginInvoke uses the message queue.
/// This means that the interface will be refreshed
/// when application has a chance to process its messages.
/// </remarks>
[AttributeUsage(AttributeTargets.Method)]
[Serializable] // required by PostSharp
public class ThreadAccessibleUIAttribute : OnMethodInvocationAspect
{
    public override void OnInvocation(
        MethodInvocationEventArgs eventArgs)
    {
        Control control = eventArgs.Instance as Control;
        if (control == null)
            throw new ApplicationException(
                "ThreadAccessibleUIAttribute" +
                "can be applied only to methods on Control class");

        // The form may be closed before
        // this method is called from another thread.
        if (control.Created == false)
            return;

        control.BeginInvoke((MethodInvoker)eventArgs.Proceed);
    }
};

Download email attachments in .NET

January 25th, 2010

First you’ll need an IMAP client or POP3 client to download emails from the server.

The email attachments are downloaded as a part of the message. Attachments are stored within the email as part of a mime tree. Usually Quoted-Printable or Base64 encoding are used. Mail.dll is going to parse such tree for you and expose all attachments as well known .NET collections.

ISimpleMailMessage uses 2 collections for storing attachments:

  • Attachments - contains all attached documents
  • Visuals - contains files that should be ‘displayed’ to the user (like images or music that should be played in background)

Following you’ll find samples of how you can save all attachments to disk using C# and VB.NET via POP3 and IMAP protocols.

When you use IMAP server:

// C# version
using(Imap imap = new Imap())
{
	imap.Connect("server");

	imap.User = "user";
	imap.Password = "password";
	imap.Login();

	imap.SelectInbox();
	List<long> uids = imap.SearchFlag(Flag.All);
	foreach (long uid in uids)
	{
		string eml = imap.GetMessageByUID(uid);
		ISimpleMailMessage email = new SimpleMailMessageBuilder()
			.CreateFromEml(eml);

		Console.WriteLine(email.Subject);

		// save all attachments to disk
		email.Attachments.ForEach(mime => mime.Save(mime.FileName));
		email.Visuals.ForEach(mime => mime.Save(mime.FileName));
	}
	imap.Close(true);
}

You can also save attachment to stream: void MimeData.Save(Stream stream)
Or get direct access to it: MemoryStream MimeData.GetMemoryStream()

' VB.NET version
Using imap As New Imap()
	imap.Connect("server")

	imap.User = "user"
	imap.Password = "password"
	imap.Login()

	imap.SelectInbox()
	Dim uids As List(Of Long) = imap.SearchFlag(Flag.All)
	For Each uid As Long In uids
		Dim eml As String = imap.GetMessageByUID(uid)
		Dim email As ISimpleMailMessage = New SimpleMailMessageBuilder()_
			.CreateFromEml(eml)

		Console.WriteLine(email.Subject)

		' save all attachments to disk
		email.Attachments.ForEach(Function(mime) mime.Save(mime.FileName))
		email.Visuals.ForEach(Function(mime) mime.Save(mime.FileName))
	Next
	imap.Close(True)
End Using

When you use POP3 server:

// C# version
using(Pop3 pop3 = new Pop3())
{
	pop3.Connect("server");

	pop3.User = "user";
	pop3.Password = "password";
	pop3.Login();

	pop3.GetAccountStat();
	for (int i = 1; i <= pop3.MessageCount; i++)
	{
		string eml = pop3.GetMessage(i);
		ISimpleMailMessage email = new SimpleMailMessageBuilder()
			.CreateFromEml(eml);

		Console.WriteLine(email.Subject);

		// save all attachments to disk
		email.Attachments.ForEach(mime => mime.Save(mime.FileName));
		email.Visuals.ForEach(mime => mime.Save(mime.FileName));
	}
	pop3.Close(true);
}
' VB.NET version
Using pop3 As New Pop3()
	pop3.Connect("server")

	pop3.User = "user"
	pop3.Password = "password"
	pop3.Login()

	pop3.GetAccountStat()
	For i As Integer = 1 To pop3.MessageCount
		Dim eml As String = pop3.GetMessage(i)
		Dim email As ISimpleMailMessage = New SimpleMailMessageBuilder()_
			.CreateFromEml(eml)

		Console.WriteLine(email.Subject)

		' save all attachments to disk
		email.Attachments.ForEach(Function(mime) mime.Save(mime.FileName))
		email.Visuals.ForEach(Function(mime) mime.Save(mime.FileName))
	End While
	pop3.Close(True)
End Using

FindAll, ConvertAll are your friends

January 6th, 2010

Let’s take a look at following code:

public List<string> GetDeleteWarnings_ForEach()
{
    List<string> messages = new List<string>();
    foreach (ItemReference reference in _itemReferences)
    {
        if (!reference.CanBeDeleted)
        {
            messages.Add(reference.DeleteMessage);
        }
    }
    return messages;
}

Using FindAll and ConvertAll you can do it in one, very obvious, line:

public List<string> GetDeleteWarnings_Fluently()
{
    return _itemReferences
        .FindAll(x => !x.CanBeDeleted)
        .ConvertAll(x => x.DeleteMessage);
}

Uploading emails using IMAP

January 4th, 2010

Uploading emails to the IMAP server is fairly easy with Mail.dll IMAP client

First we’ll use Mail.dll to upload an existing email in eml format to the IMAP server:

// C# code

using (Imap imap = new Imap())
{
    imap.Connect("server");

    imap.User = "user";
    imap.Password = "password";
    imap.Login();

    string eml = File.ReadAllText("email.eml");

    // The name of the folder depends on your IMAP server
    imap.UploadMessage("[Gmail]/Sent Mail", eml);

    imap.Close(true);
}
' VB.NET code

Using imap As New Imap()
	imap.Connect("server")

	imap.User = "user"
	imap.Password = "password"
	imap.Login()

	Dim eml As String = File.ReadAllText("email.eml")

	' The name of the folder depends on your IMAP server
	imap.UploadMessage("[Gmail]/Sent Mail", eml)

	imap.Close(True)
End Using

Second sample shows how to create new email message and upload it to IMAP server.

// C# code

using (Imap imap = new Imap())
{
    imap.Connect("server");

    imap.User = "user";
    imap.Password = "password";
    imap.Login();

    // Create new mail message
    SimpleMailMessageBuilder builder = new SimpleMailMessageBuilder();
    builder.Subject = "subject";
    builder.From.Add(new MailBox("alice@email.com", "Alice"));
    builder.To.Add(new MailBox("bob@email.com", "Bob"));
    builder.SetTextData("This is plain text email");

    // Upload
    // The name of the folder depends on your IMAP server
    imap.UploadMessage("[Gmail]/Sent Mail", builder.Create());

    imap.Close(true);
}
' VB.NET code

Using imap As New Imap()
	imap.Connect("server")

	imap.User = "user"
	imap.Password = "password"
	imap.Login()

	' Create new mail message
	Dim builder As New SimpleMailMessageBuilder()
	builder.Subject = "subject"
	builder.From.Add(New MailBox("alice@email.com", "Alice"))
	builder.[To].Add(New MailBox("bob@email.com", "Bob"))
	builder.SetTextData("This is plain text email")

	' Upload
	' The name of the folder depends on your IMAP server
	imap.UploadMessage("[Gmail]/Sent Mail", builder.Create())

	imap.Close(True)
End Using

Please note that only few IMAP servers are going to send the message to the actual recipients. Most servers will only upload the message without sending it.
You should use SMTP protocol for this.
You can download Mail.dll IMAP client here.