Save raw eml file using IMAP and POP3
There are times that you need to save raw email data in eml format.
This tutorial shows how to use Mail.dll POP3 and IMAP clients to achieve this goal.
Note that we don’t need to parse the emails, so we aren’t using MailBuilder class and IMail interface.
Samples provided use both POP3 and IMAP protocols and both C# and VB.NET.
Save email using IMAP:
The code below will search for all the emails with specified subject and write all these emails to your c: drive.
// C# code using (Imap imap = new Imap()) { imap.Connect("imap.example.com"); // use ConnectSSL for SSL connection. imap.UseBestLogin("user", "password"); imap.SelectInbox(); List<long> uids = imap.Search( Expression.Subject("email subject")); foreach (long uid in uids) { var eml = imap.GetMessageByUID(uid); string fileName = string.Format(@"c:\email_{0}.eml", uid); File.WriteAllBytes(fileName, eml); } imap.Close(); }
' VB.NET code Using imap As New Imap() imap.Connect("imap.example.com") ' use ConnectSSL for SSL connection. imap.UseBestLogin("user", "password") imap.SelectInbox() Dim uids As List(Of Long) = imap.Search( _ Expression.Subject("email subject")) For Each uid As Long In uids Dim eml = imap.GetMessageByUID(uid) Dim fileName As String = String.Format(@"c:\email_{0}.eml", uid) File.WriteAllBytes(fileName, eml) Next imap.Close() End Using
Save email using POP3:
As POP3 protocol does not allow searching, the code below will write all emails to your c: drive. You can easily limit this to the specified uid.
// C# code using (Pop3 pop3 = new Pop3()) { pop3.Connect("pop3.example.com"); // use ConnectSSL for SSL connection. pop3.UseBestLogin("user", "password"); foreach (string uid in pop3.GetAll()) { var eml = pop3.GetMessageByUID(uid)); string fileName = string.Format(@"c:\email_{0}.eml", uid); File.WriteAllBytes(fileName, eml); } pop3.Close(); }
' VB.NET code Using pop3 As New Pop3() pop3.Connect("pop3.example.com") 'use ConnectSSL for SSL connection. pop3.UseBestLogin("user", "password") For Each uid As String In pop3.GetAll() Dim eml = pop3.GetMessageByUID(uid) Dim fileName As String = String.Format("c:\email_{0}.eml", uid) File.WriteAllBytes(fileName, eml) Next pop3.Close() End Using
You can download Mail.dll at: Mail.dll .NET email component
May 4th, 2014 at 12:20
Save raw eml file using IMAP :
Could you please let me know where in your code folder/drive path should be specified to save the eaw emails.
Thanks.
May 4th, 2014 at 16:51
You can add drive/folder information to the fileName variable.
April 23rd, 2015 at 18:12
can you save an email in outlook style? like msg ? or as an htm ?
thanks.
April 24th, 2015 at 10:40
@Stelios
Proprietary msg files are not supported.
You can use IMail.Html property to access HTML version of the email and IMail.SaveHtmlAs method to save HTML version of the message as regular HTML file. This method also saves all visual elements as files to the same folder.