+1 vote

I need to get all email message headers part of the message for storing it together with standard mail message fields for user display / examination.

Some information contained in the message headers is in custom headers. Also some standard headers (like comment and keywords) are usually ignored and dumped out for mail clients.

Following is a piece of code for receiving a message:

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

private static string GetEmailMessageHeader(IMail email)
{
    // Here you should extract the message all message 
    // headers as they were contained in original message data
    throw new NotImplementedException();
}

static void Main(string[] args)
{
    using (Pop3 pop3 = new Pop3())
    {
        pop3.Connect("pop3.example.com");
        pop3.Login("user", "password");
        MailBuilder builder = new MailBuilder();
        foreach (string uid in pop3.GetAll())
        {
            byte[] messageData = pop3.GetMessageByUID(uid);
            IMail email = builder.CreateFromEml(messageData);
        }
        pop3.Close();
    }
}

What is the recommended implementation for function GetEmailMessageHeader?

Regards,

Manolis

by (1.2k points)

1 Answer

+1 vote

Use IMail.Headers collection:

IMail email = ...
foreach (string key in email.Headers.AllKeys)
{
    List<string> values = joined.Headers.GetValues(key);
}

Also some standard headers (like comment and keywords) are usually
ignored and dumped out for mail clients.

I don't think I understand that.

by (301k points)
Following a full tested implementation of the suggested function:

// Get Message Header Text
private static string GetEmailMessageHeader(IMail iMail)
{
    string ret = null;
    if (iMail != null)
    {
        HeaderCollection headerCollection = iMail.Headers;
        if (headerCollection != null)
        {
            List<string> headerAllKeys = headerCollection.AllKeys;
            if (headerAllKeys != null & headerAllKeys.Count > 0)
            {
                ret = "";
                foreach (string headerKey in headerAllKeys)
                {
                    string keyValue = headerCollection[headerKey];
                    ret += headerKey + ": " + keyValue + "\n";
                }
            }
        }
    }
    return ret;
}
...