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);
}
imap.Close(true);
}
' 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)
Next
imap.Close(True)
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);
}
pop3.Close(true);
}
' 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)
Next
pop3.Close(True)
End Using
You can download Mail.dll at: Mail.dll .NET email component