Access custom email header using POP3

Most common email headers like From, Subject, Date, To, Cc etc. are exposed by IMail interface as properties. Those properties contain parsed information and return strong typed objects like DateTime‘s, string collections, MailAddress collections.

There are times however that you need to access non-standard email header. Good example is a need to get a spam value that your POP3 server assigns to every email by inserting additional ‘x-spam’ header.

For this purpose you can always use IMail.Document.Root.Headers collection to access any non-standard and standard header.

If you only need to access email headers consider using GetHeadersByUID method which doesn’t download entire message, but only headers. It uses POP3 TOP command. The sample below downloads entire message.

// 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");

            MailBuilder builder = new MailBuilder();
            foreach (string uid in pop3.GetAll())
            {
                var eml = pop3.GetMessageByUID(uid);
                IMail email = builder.CreateFromEml(eml);
                Console.WriteLine("subject: {0}", email.Subject);

                // Get custom header:
                string header = email.Document.Root.Headers["x-spam"];
                Console.WriteLine("x-spam: {0}", header);
            }
            pop3.Close();
        }
    }
};

' VB.NET version

Imports System
Imports Limilabs.Mail
Imports Limilabs.Client.POP3

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")

            Dim builder As New MailBuilder()
            For Each uid As String In pop3.GetAll()
                Dim eml = pop3.GetMessageByUID(uid)
                Dim email As IMail = builder.CreateFromEml(eml)
                Console.WriteLine("subject: {0}", email.Subject)

                ' Get custom header:
                Dim header As String = email.Document.Root.Headers("x-spam")
                Console.WriteLine("x-spam: {0}", header)
            Next
            pop3.Close()
        End Using

    End Sub
End Module

Tags:    

Questions?

Consider using our Q&A forum for asking questions.