Save all attachments to disk using POP3

This article describes how to save all email messages’ attachments to disk. The messages are downloaded using Mail.dll library and POP3 protocol.

The first thing you need to know is that email attachments are downloaded along with the email message. This means that invoking GetMessageByUID method is going to download entire email message including all attachments.

Mail.dll exposes all attachments as well-known .NET collections. There are 4 collections that may contain attachments:

  • IMail.Attachments – all attachments (includes Visuals, NonVisuals and Alternatives).
  • IMail.Visuals – visual elements, files that should be displayed to the user, such as images embedded in an HTML email.
  • IMail.NonVisuals – non visual elements, “real” attachments.
  • IMail.Alternatives – alternative content representations, for example ical appointment.

You should use IMail.Attachments collection to get all attachments. Every attachment is represented by MimeData object.

using Limilabs.Mail;
using Limilabs.Mail.MIME;
using Limilabs.Client.POP3;

class Program
{
    static void Main(string[] args)
    {
        Pop3 pop3 = new Pop3();
        pop3.Connect("pop3.example.com");
        pop3.Login("user", "password");

        foreach (string uid in pop3.GetAll())
        {
            var eml = pop3.GetMessageByUID(uid);
            IMail email = new MailBuilder()
                .CreateFromEml(eml);

            Console.WriteLine(email.Subject);

            foreach (MimeData mime in email.Attachments)
            {
                mime.Save(@"c:\" + mime.SafeFileName);
            }
        }

        pop3.Close();
    }
};
' VB.NET

Imports Limilabs.Mail
Imports Limilabs.Mail.MIME
Imports Limilabs.Client.POP3

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using pop3 As New Pop3()
            pop3.Connect("pop3.example.com")
            pop3.Login("user", "password")

            Dim uids As List(Of Long) = pop3.GetAll()

            For Each uid As Long In uids
                Dim eml = pop3.GetMessageByUID(uid)
                Dim email As IMail = New MailBuilder() _
                    .CreateFromEml(eml)
                Console.WriteLine(email.Subject)

                For Each mime As MimeData In email.Attachments
                    mime.Save("c:\" + mime.SafeFileName)
                Next
            Next
            pop3.Close()
        End Using

    End Sub
End Module

Accessing attachment’s data

You can also save attachment to stream: void MimeData.Save(Stream stream).
You can directly access attachment’s data as stream using MimeData.GetMemoryStream() method or as byte array using MimeData.Data property.

Process emails embedded as attachments

In many situations you’ll receive a message that has another message attached. You can use Mail.dll to extract all attachments from such inner messages no matter on how deep the embedding level is.

Save images embedded in HTML email to disk using POP3

This article shows how to save all images embedded in HTML email message to disk. The messages are downloaded using Mail.dll .NET POP3 component and POP3 protocol.

In most cases HTML body of the message references such images using special “cid:” protocol, that specifies Content-ID of the image that should be used:

This is our <strong>brand new</strong> logo: <br />
<img src="cid:logo@example.com" />

In such case actual image is embedded inside an email, as part of the mime tree, as an element related to HTML body and with content-disposition header set to inline. This means that invoking GetMessageByUID method is going to download entire email message, including all images. This makes message bigger, but images don’t need to be stored on your web server (and remember that emails tend to be archived for years).

Mail.dll exposes all attachments as well-known .NET collections. There are 4 collections that may contain attachments:

  • IMail.Attachments – all attachments (includes Visuals, NonVisuals and Alternatives).
  • IMail.Visuals – visual elements, files that should be displayed to the user, such as images embedded in an HTML email.
  • IMail.NonVisuals – non visual elements, “real” attachments.
  • IMail.Alternatives – alternative content representations, for example ical appointment.

As you can see the most interesting from this article’s point of view is IMail.Visuals collection. As with regular attachments, visual elements are represented by MimeData objects.

using Limilabs.Mail;
using Limilabs.Mail.MIME;
using Limilabs.Client.POP3;

class Program
{
    static void Main(string[] args)
    {
        Pop3 pop3 = new Pop3();
        pop3.Connect("server.company.com");
        pop3.Login("user", "password");

        // Receive all messages
        foreach (string uid in pop3.GetAll())
        {
            var eml = pop3.GetMessageByUID(uid);
            IMail email = new MailBuilder()
                .CreateFromEml(eml);

            Console.WriteLine(email.Subject);

            foreach (MimeData mime in email.Visuals)
            {
                mime.Save(@"c:\" + mime.SafeFileName);
            }
        }
        pop3.Close();
    }
};
' VB.NET

Imports Limilabs.Mail
Imports Limilabs.Mail.MIME
Imports Limilabs.Client.POP3

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using pop3 As New Pop3()
            pop3.Connect("server.example.com")
            pop3.Login("user", "password")

            Dim uids As List(Of Long) = pop3.GetAll()

            For Each uid As Long In uids
                Dim eml = pop3.GetMessageByUID(uid)
                Dim email As IMail = New MailBuilder() _
                    .CreateFromEml(eml)
                Console.WriteLine(email.Subject)

                For Each mime As MimeData In email.Visuals
                    mime.Save("c:\" + mime.SafeFileName)
                Next
            Next
            pop3.Close()
        End Using

    End Sub
End Module

You can also save attachment to stream MimeData.Save(Stream stream), get direct access to it as stream MemoryStream MimeData.GetMemoryStream()
or as byte array using byte[] MimeData.Data property.

You can also use SaveHtmlAs method to save entire message as regular HTML page with all required images and styles to a single folder:

// C#

IMail email = ...
email.SaveHtmlAs(@"c:\tmp\email.html");
' VB.NET

Dim email As IMail = ...
email.SaveHtmlAs("c:\tmp\email.html")

What is also worth mentioning is the fact that you can use Content-Id to search through IMail.Visuals collection:

// C#

IMail email = ...;
MimeData logo = email.Visuals["logo@example.com"];
// VB.NET

Dim email As IMail = ...
Dim logo As MimeData = email.Visuals("logo@example.com")

Delete emails with POP3

This article describes how to delete email messages using Mail.dll .NET POP3 component and POP3 protocol.

Internally deleted messages are only marked for deletion. Email messages are actually deleted by POP3 server after the client issues successful QUIT command – in other words: when client disconnects.

Following code will find unique ids of all messages and delete them one by one.

// C# version

using Limilabs.Client.POP3;

class Program
{
    static void Main(string[] args)
    {
        using (Pop3 pop3 = new Pop3())
        {
            pop3.Connect("pop3.company.com");    // use ConnectSSL for SSL.
            pop3.Login("user", "password");

            // Delete all messages
            foreach (string uid in pop3.GetAll())
            {
                pop3.DeleteMessageByUID(uid);
            }

            pop3.Close();
        }
    }
};
' VB.NET version

Imports Limilabs.Client.POP3

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using pop3 As New Pop3()
            pop3.Connect("pop3.company.com")  ' use ConnectSSL for SSL.
            pop3.Login("user", "password")

            ' Delete all messages
            For Each uid As String In pop3.GetAll()
                pop3.DeleteMessageByUID(uid)
            Next

            pop3.Close()
        End Using

    End Sub
End Module

Here you can find Gmail POP3 behavior regarding downloading and deleting email messages.

Get common email fields (Subject, Text) with POP3

In this article we’ll show how to download emails using Mail.dll .NET POP3 component and access some common email properties like: Subject, Date, Text, Html and Attachments.

Remember about adding a reference to Mail.dll and importing namespaces.

First you need to download email from POP3 server using Pop3 class. Then parse it using MailBuilder class. After that you’ll receive IMail interface.

This interface can be used to access all standard and non-standard headers.
Subject, From, To, Date, email data like: Text and Html versions of the email, and others can be accessed as simple properties. This sample also shows how to access Attachments collection.

// C#

using System;
using System.Collections.Generic;
using Limilabs.Client.POP3;
using Limilabs.Mail;
using Limilabs.Mail.MIME;
using Limilabs.Mail.Headers;

internal class Program
{
    private static void Main(string[] args)
    {
        using (Pop3 pop3 = new Pop3())
        {
            pop3.Connect("imap.example.com");    // use ConnectSSL for SSL
            pop3.Login("user", "password");

            // Receive all messages
            MailBuilder builder = new MailBuilder();
            foreach (string uid in pop3.GetAll())
            {
                IMail email = builder.CreateFromEml(
                    pop3.GetMessageByUID(uid)
                    );

                // Subject
                Console.WriteLine(email.Subject);

                // From
                foreach (MailBox m in email.From)
                {
                    Console.WriteLine(m.Address);
                    Console.WriteLine(m.Name);
                }

                // Date
                Console.WriteLine(email.Date);

                // Text body of the message
                Console.WriteLine(email.Text);

                // Html body of the message
                Console.WriteLine(email.Html);

                // Custom header
                Console.WriteLine(email.Document.Root.Headers["x-spam"]);

                // Save all attachments to disk
                foreach (MimeData mime in email.Attachments)
                {
                    mime.Save(@"c:\" + mime.SafeFileName);
                }
            }
            pop3.Close();
        }
    }
} ;
' VB.NET

Imports System;
Imports Limilabs.Mail;
Imports Limilabs.Mail.MIME;
Imports Limilabs.Mail.Headers;
Imports Limilabs.Client.POP3;

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using pop3 As New Pop3()
            pop3.Connect("pop3.example.com")    ' use ConnectSSL for SSL
            pop3.Login("user", "password")

            ' Receive all messages
            Dim builder As New MailBuilder()
            For Each uid As String In pop3.GetAll()
                Dim email As IMail = builder.CreateFromEml( _
                      pop3.GetMessageByUID(uid))

                ' Subject
                Console.WriteLine(email.Subject)

                ' From
                For Each m As MailBox In email.From
                    Console.WriteLine(m.Address)
                    Console.WriteLine(m.Name)
                Next

                ' Date
                Console.WriteLine(email.[Date])

                ' Text body of the message
                Console.WriteLine(email.Text)

                ' Html body of the message
                Console.WriteLine(email.Html)

                ' Custom header
                Console.WriteLine(email.Document.Root.Headers("x-spam-value"))

                ' Save all attachments to disk
                For Each mime As MimeData In email.Attachments
                    mime.Save("c:\" + mime.SafeFileName)
                Next
            Next
            pop3.Close()
        End Using

    End Sub
End Module

To, Cc and Bcc headers are a bit tricky as they can contain address groups. You can learn more about how to work with them in how to access To, Cc, Bcc fields article.

Receive emails using POP3

This article describes how to receive email messages using Mail.dll POP3 component and POP3 protocol.

As a prerequisite you need to add reference to Mail.dll to your project. Please check MSDN how to add reference article for details.

When your reference is added you need to import correct namespaces:

// C#

using Limilabs.Mail;
using Limilabs.Client.POP3;
' VB

Imports Limilabs.Mail
Imports Limilabs.Client.POP3

First thing you need to do is to connect to your POP3 server. Use Connect(string host) method to connect to the server. Typically POP3 server is working on port 110. You can use Connect(string host, int port) overload when you need to specify different port, or ConnectSSL methods to use POP3 over SSL.

// C#

using (Pop3 pop3 = new Pop3())
{
    pop3.Connect("pop3.example.com");  // or ConnectSSL for SSL
    pop3.UseBestLogin("user", "password");

' VB

Using pop3 As New Pop3()
    pop3.Connect("pop3.example.com")   ' or ConnectSSL for SSL
    pop3.UseBestLogin("user", "password")

Next step is to download all unique ids (uids) of the available messages, and iterate through them:

// C#

foreach (string uid in pop3.GetAll())
' VB

For Each uid As String In pop3.GetAll()

Finally we’ll use GetMessageByUID method to download the message from the server and MailBuilder class to parse it and extract attachments:

// C#

var eml = pop3.GetMessageByUID(uid)
IMail email = new MailBuilder().CreateFromEml(eml);

Console.WriteLine(email.Subject);
Console.WriteLine(email.Text);
' VB

Dim eml = pop3.GetMessageByUID(uid)
Dim email As IMail = builder.CreateFromEml(eml)

Console.WriteLine(email.Subject)
Console.WriteLine(email.Text)

At that point you can also access attachments.

Here are the full samples:

// C# version

using System;
using Limilabs.Mail;
using Limilabs.Client.POP3;

class Program
{
    static void Main(string[] args)
    {
        using (Pop3 pop3 = new Pop3())
        {
            pop3.Connect("pop3.example.com");  // or ConnectSSL for SSL
            pop3.UseBestLogin("user", "password");

            // Receive all messages and display the subject
            MailBuilder builder = new MailBuilder();
            foreach (string uid in pop3.GetAll())
            {
                IMail email = builder.CreateFromEml(
                  pop3.GetMessageByUID(uid));

                Console.WriteLine(email.Subject);
                Console.WriteLine(email.Text);
            }
            pop3.Close();
        }
    }
}
' VB.NET version

Imports Limilabs.Client.POP3
Imports Limilabs.Mail

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using pop3 As New Pop3()
            pop3.Connect("pop3.example.com")   ' or ConnectSSL for SSL
            pop3.UseBestLogin("user", "password")

            ' Receive all messages and display the subject
            Dim builder As New MailBuilder()
            For Each uid As String In pop3.GetAll()

                Dim email As IMail = builder.CreateFromEml( _
                    pop3.GetMessageByUID(uid))

                Console.WriteLine(email.Subject)
                Console.WriteLine(email.Text)
            Next
            pop3.Close()
        End Using

    End Sub
End Module