Save raw eml file using IMAP and POP3
There are times that you need to save raw eml format of the email (for example when you want to report a bug).
This tutorial shows how to use Mail.dll POP3 and IMAP clients to achieve this goal.
Notice that we are not parsing the emails so we don’t need to use MailBuilder and IMail classes.
Samples provided use both POP3 and IMAP protocols using C# and VB.NET
IMAP version:
The code below will write all emails with specified subject to your c: drive:
// C# code
using (Imap imap = new Imap())
{
imap.Connect("server");
// imap.ConnectSSL("server"); // if you need SSL connection.
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.Search(
Expression.Subject("email subject"));
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
string fileName = string.Format("c:\email_{0}.eml", uid);
File.WriteAllText(fileName, eml, Encoding.UTF8);
}
imap.Close();
}
' VB.NET code
Using imap As New Imap()
imap.Connect("server")
' imap.ConnectSSL("server") ' if you need SSL connection.
imap.Login("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 As String = imap.GetMessageByUID(uid)
Dim fileName As String = String.Format("c:\email_{0}.eml", uid)
File.WriteAllText(fileName, eml, Encoding.UTF8)
Next
imap.Close()
End Using
POP3 version:
As POP3 does not allow searching, the code below will write all emails to your c: drive:
// C# code
using (Pop3 pop3 = new Pop3())
{
pop3.Connect("server");
// pop3.ConnectSSL("server"); // if you need SSL connection.
pop3.Login("user", "password");
foreach (string uid in pop3.GetAll())
{
string eml = pop3.GetMessageByUID(uid));
string fileName = string.Format("c:\email_{0}.eml", uid);
File.WriteAllText(fileName, eml, Encoding.UTF8);
}
pop3.Close();
}
' VB.NET code
Using pop3 As New Pop3()
pop3.Connect("server")
' pop3.ConnectSSL("server"); ' if you need SSL connection.
pop3.Login("user", "password")
For Each uid As String In pop3.GetAll()
Dim eml As String = pop3.GetMessageByUID(uid)
Dim fileName As String = String.Format("c:\email_{0}.eml", uid)
File.WriteAllText(fileName, eml, Encoding.UTF8)
Next
pop3.Close()
End Using
You can download Mail.dll at: Mail.dll .NET email component

May 4th, 2010 at 14: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, 2010 at 18:51
You can add drive/folder information to the fileName variable.
April 23rd, 2011 at 20:12
can you save an email in outlook style? like msg ? or as an htm ?
thanks.
April 24th, 2011 at 12:40
@Stelios
Proprietary msg files are not supported.
You can use IMail.HtmlDataString to access HTML version of the email and IMail.SaveHtmlAs to save HTML version of the message as regular HTML file. This method also saves all visual elements as files to the same folder.