EAGetMail Developers Center > Using EAGetMail in Visual C#.NET to retrieve email from POP3/IMAP4 server
This page has moved. Click Here! to redirect to our new page.
Introduction
EAGetMail is a POP3 & IMAP4 component which supports all operations of POP3/IMAP4/MIME protocol. This tutorial covers everything of receiving email and parsing email with EAGetMail in C#.
Installation
You should download the EAGetMail Installer and install it on your machine at first.
A simple C# project
First of all, let's create a C# console project named "receiveemail" at first, then add the reference of EAGetMail in your project (Please refer to next section).
Add Reference of EAGetMail to Visual Stuido.NET Project
To use EAGetMail POP3 & IMAP Component in your project, the first step is "Add reference of EAGetMail to your project". Please create/open your project with Visual Studio.NET, then choose menu->"Project"->"Add Reference"->".NET"->"Browse...", and choose the EAGetMail{version}.dll from your disk, click "Open"->"OK", the reference of EAGetMail will be added to your project, and you can start to use EAGetMail POP3 & IMAP Component in your project.
Because EAGetMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.
Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0 and .Net Compact Framework 2.0, 3.5.
| File | .NET Framework Version |
| EAGetMail.dll |
Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version. |
| EAGetMail20.dll |
Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version. |
| EAGetMail35.dll |
Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version. |
| EAGetMail40.dll |
Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version. |
| EAGetMailCF20.dll |
Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version. |
| EAGetMailCF35.dll |
Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version. |
Retrieve email from POP3 server
The following code demonstrates how to receive email from a POP3 mail account. This sample downloads emails from POP3 server and delete the email after the email is retrieved.
Add the following code like this:
/*[C# Example - Receive email from POP3 server]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");
//if your POP3 server requires SSL connection,
//please add the following codes:
//oServer.SSLConnection = true;
//oServer.Port = 995;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//receive email from POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
//save email to local disk
oMail.SaveAs(fileName, true);
//mark email as deleted from POP3 server.
oClient.Delete(info);
}
//quit and pure emails marked as deleted from POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
If you set everything right, you can get emails in the mail folder. If the codes threw exception, then please have a look at the following section.
Where can I get my POP3 server address, user and password?
Because each email account provider has different server address, so you should query your POP3 server address from your email account provider. User name is your email address or your email address without domain part. It depends on your email provider setting.
When you execute above example code, if you get error about "Networking connection" or "No such host", it is likely that your POP3 server address is not correct. If you get an error like "Invalid user or password", it is likely that you did not set the correct user or password.
Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your POP3 server address, user in your email client. For example, you can choose menu -> "Tools" - > - "Accounts" - > "Your email account" - > "Properties" - > "Servers" in Outlook express or Windows Mail to get your POP3 server, user. Using EAGetMail to receive email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.
Retrieve email from IMAP4 server in C#
If your server supports IMAP4 protocol, you can also receive email by IMAP4 protocol. Please have a look at the following code.
/*[C# Example - Receive email from IMAP4 server]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");
//Set IMAP4 server port
oServer.Port = 143;
//if your IMAP4 server requires SSL connection,
//please add the following codes:
//oServer.SSLConnection = true;
//oServer.Port = 993;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
//save email to local disk
oMail.SaveAs(fileName, true);
//mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
//quit and pure emails marked as deleted from IMAP4 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Retrieve email over SSL connection
SSL connection encrypts data between the POP3 component and POP3 server to protects user, password and email content in TCP/IP level. Now this technology is commonly used and many SMTP servers are deployed with SSL such as Gmail.
The following samples demonstrate how to receive email over SSL connection from Gmail, Yahoo and Hotmail account.
Retrieve email from Gmail account with SSL connection
/*[C# Example - Receive email from Gmail]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//Gmail POP3 server is "pop.gmail.com"
//Gmail user authentication should use your
//Gmail email address as the user name.
//For example: your email is "gmailid@gmail.com",
//then the user should be "gmailid@gmail.com"
MailServer oServer = new MailServer("pop.gmail.com",
"gmailid@gmail.com", "yourpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");
//Set SSL connection,
oServer.SSLConnection = true;
oServer.Port = 995;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//Receive email from GMail POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
//save email to local disk
oMail.SaveAs(fileName, true);
//mark email as deleted in GMail account.
oClient.Delete(info);
}
//quit and pure emails marked as deleted from Gmail POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Retrieve email from Yahoo account with SSL connection
/*[C# Example - Receive email from Yahoo]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//Yahoo POP3 server is "pop.mail.yahoo.com"
//Yahoo user authentication should use your
//Yahoo email address as the user name.
//For example: your email is "yahooid@yahoo.com",
//then the user should be "yahooid@yahoo.com"
MailServer oServer = new MailServer("pop.mail.yahoo.com",
"yahooid@yahoo.com", "yourpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");
//Set SSL connection,
oServer.SSLConnection = true;
oServer.Port = 995;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//Receive email from Yahoo POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
//save email to local disk
oMail.SaveAs(fileName, true);
//mark email as deleted in Yahoo account.
oClient.Delete(info);
}
//quit and pure emails marked as deleted from Yahoo POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Retrieve email from Hotmail account with SSL connection
/*[C# Example - Receive email from Hotmail]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//Hotmail POP3 server is "pop3.live.com"
//Hotmail user authentication should use your
//Hotmail email address as the user name.
//For example: your email is "hotmailid@hotmail.com",
//then the user should be "hotmailid@hotmail.com"
MailServer oServer = new MailServer("pop3.live.com",
"hotmailid@hotmail.com", "yourpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");
//Set SSL connection,
oServer.SSLConnection = true;
oServer.Port = 995;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//Receive email from Hotmail POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
//save email to local disk
oMail.SaveAs(fileName, true);
//mark email as deleted in Hotmail account.
oClient.Delete(info);
}
//quit and pure emails marked as deleted from Hotmail POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Retrieve email with event handler
After Connect method, GetMail method or other methods are invoked, if you want to know the progress of the email receiving, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email receiving.
/*[C# Example - Receive email from with event handler]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
private static void OnConnected(object sender, ref bool cancel)
{
Console.WriteLine("Connected");
}
private static void OnQuit(object sender, ref bool cancel)
{
Console.WriteLine( "Quit");
}
private static void OnReceivingDataStream(object sender,
MailInfo info, int received, int total, ref bool cancel)
{
Console.WriteLine(String.Format("Receiving {0}, {1}/{2}...", info.Index,
received, total));
}
private static void OnIdle(object sender, ref bool cancel)
{
}
private static void OnAuthorized(object sender, ref bool cancel)
{
Console.WriteLine("Authorized");
}
private static void OnSecuring(object sender, ref bool cancel)
{
Console.WriteLine("Securing");
}
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");
//if your POP3 server requires SSL connection,
//please add the following codes:
//oServer.SSLConnection = true;
//oServer.Port = 995;
//Catching the following events is not necessary,
//just make the application more user friendly.
//If you use the object in asp.net/windows service or non-gui application,
//You need not to catch the following events.
oClient.OnAuthorized += new MailClient.OnAuthorizedEventHandler( OnAuthorized );
oClient.OnConnected += new MailClient.OnConnectedEventHandler( OnConnected );
oClient.OnIdle += new MailClient.OnIdleEventHandler( OnIdle );
oClient.OnSecuring += new MailClient.OnSecuringEventHandler( OnSecuring );
oClient.OnReceivingDataStream +=
new MailClient.OnReceivingDataStreamEventHandler( OnReceivingDataStream );
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//receive email from POP3 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
//save email to local disk
oMail.SaveAs(fileName, true);
//mark email as deleted from POP3 server.
oClient.Delete(info);
}
//quit and pure emails marked as deleted from POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Using UIDL function to mark the email has been downloaded
If you want to leave a copy of email on the server, you should not call Delete method. However, there is a problem, how can you know if the email has already been downloaded? If there is a way to identify the downloaded email, you can avoid downloading the duplicated email from your POP3/IMAP4 server.
IMAP4 Solution
Every email has a unique identifier (UIDL) on IMAP4 server. It is a 32bit integer and it is always unique in your email account life time. So we can use the integer as file name to identify if the email has been downloaded.
Please see the following example code:
/*[C# Example - Receive email from IMAP4 server - Leave a copy of message on server]*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
//create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");
//Set IMAP4 server port
oServer.Port = 143;
//if your IMAP4 server requires SSL connection,
//please add the following codes:
//oServer.SSLConnection = true;
//oServer.Port = 993;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
//using IMAP UIDL as the file name.
string fileName = String.Format("{0}\\{1}.eml",
mailbox, info.UIDL );
if( File.Exists( fileName ))
{//This email has been downloaded, do not download it again.
continue;
}
//receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
//save email to local disk
oMail.SaveAs(fileName, true);
//do not delete email from IMAP4 server.
}
//quit
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
POP3/IMAP4 Solution
There is a little bit different in POP3 server. The UIDL is only unique in the email life time. That means if the email was deleted from the server, other email can use the old unique identifier. Another problem is: UIDL in POP3 server can be any number or characters, so we cannot use UIDL as the file name, because UIDL may contain invalid characters for file name.
To solve this problem, we have to store the UIDL to a txt file and synchronize it with server every time.
Please have a look at the following example code. It works with both POP3/IMAP4 servers.
/*[C# Example - Using UIDL to mark email as read]*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class MyMailClient
{
private string m_uidlfile = "uidl.txt";
private string m_curpath = "";
private ArrayList m_arUidl = new ArrayList();
#region UIDL Functions
// uidl is the identifier of every email on POP3/IMAP4 server, to
// avoid retrieve the same email from server more than once, we
// record the email uidl retrieved every time if you delete the
// email from server every time and not to leave a copy of email
on
// the server, then please remove all the function about uidl.
private bool _FindUIDL(MailInfo[] infos, string uidl)
{
int count = infos.Length;
for (int i = 0; i < count; i++)
{
if (String.Compare(infos[i].UIDL, uidl, false) == 0)
return true;
}
return false;
}
//remove the local uidl which is not existed on the server.
private void _SyncUIDL(MailServer oServer, MailInfo[] infos)
{
string s = String.Format("{0}#{1} ", oServer.Server, oServer.User);
bool bcontinue = false;
int n = 0;
do
{
bcontinue = false;
int count = m_arUidl.Count;
for (int i = n; i < count; i++)
{
string x = m_arUidl[i] as string;
if (String.Compare(s, 0, x, 0, s.Length, true) == 0)
{
int pos = x.LastIndexOf(' ');
if (pos != -1)
{
string uidl = x.Substring(pos + 1);
if (!_FindUIDL(infos, uidl))
{
//this uidl doesn't exist on server,
//remove it from local uidl list to save the storage.
bcontinue = true;
n = i;
m_arUidl.RemoveAt(i);
break;
}
}
}
}
} while (bcontinue);
}
private bool _FindExistedUIDL(MailServer oServer, string uidl)
{
string s = String.Format("{0}#{1} {2}", oServer.Server.ToLower(),
oServer.User.ToLower(), uidl);
int count = m_arUidl.Count;
for (int i = 0; i < count; i++)
{
string x = m_arUidl[i] as string;
if (String.Compare(s, x, false) == 0)
return true;
}
return false;
}
private void _AddUIDL(MailServer oServer, string uidl)
{
string s = String.Format("{0}#{1} {2}", oServer.Server.ToLower(),
oServer.User.ToLower(), uidl);
m_arUidl.Add(s);
}
private void _UpdateUIDL()
{
StringBuilder s = new StringBuilder();
int count = m_arUidl.Count;
for (int i = 0; i < count; i++)
{
s.Append(m_arUidl[i] as string);
s.Append("\r\n");
}
string file = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
FileStream fs = null;
try
{
fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
byte[] data = System.Text.Encoding.Default.GetBytes(s.ToString());
fs.Write(data, 0, data.Length);
fs.Close();
}
catch (Exception ep)
{
if (fs != null)
fs.Close();
throw ep;
}
}
private void _LoadUIDL()
{
m_arUidl.Clear();
string file = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
StreamReader read = null;
try
{
read = File.OpenText(file);
while (true)
{
string line = read.ReadLine().Trim("\r\n \t".ToCharArray());
m_arUidl.Add(line);
}
}
catch (Exception ep)
{ }
if (read != null)
read.Close();
}
#endregion
public void ReceiveEmail(MailServer oServer, bool bLeaveCopy )
{
MailClient oClient = new MailClient("TryIt");
m_curpath = Directory.GetCurrentDirectory();
try
{
// uidl is the identifier of every email on POP3/IMAP4 server, to
// avoid retrieve the same email from server more than once,
// we record the email uidl retrieved every time if you delete the
// email from server every time and not to leave a copy of email
on
// the server, then please remove all the function about uidl.
_LoadUIDL();
string mailFolder = String.Format("{0}\\inbox", m_curpath);
if (!Directory.Exists(mailFolder))
Directory.CreateDirectory(mailFolder);
Console.WriteLine("Connecting server ... ");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine( "Total {0} email(s)", infos.Length);
_SyncUIDL(oServer, infos);
int count = infos.Length;
for (int i = 0; i < count; i++)
{
MailInfo info = infos[i];
if (_FindExistedUIDL(oServer, info.UIDL))
{
//this email has existed on local disk.
continue;
}
Console.WriteLine("Retrieving {0}/{1}...", info.Index, count);
Mail oMail = oClient.GetMail(info);
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur =
new System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailFolder, sdate, d.Millisecond.ToString("d3"), i);
oMail.SaveAs(fileName, true);
if (bLeaveCopy)
{
//add the email uidl to uidl file to avoid we retrieve it next time.
_AddUIDL(oServer, info.UIDL);
}
}
if (!bLeaveCopy)
{
Console.WriteLine( "Deleting ..." );
for (int i = 0; i < count; i++)
oClient.Delete(infos[i]);
}
Console.WriteLine("Completed");
// Delete method just mark the email as deleted,
// Quit method pure the emails from server exactly.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
//update the uidl list to a text file and then we can load it next
time.
_UpdateUIDL();
}
}
class Program
{
static void Main(string[] args)
{
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MyMailClient oMyClient = new MyMailClient();
//Leave a copy of email on server
oMyClient.ReceiveEmail(oServer, true);
}
}
}
Parse email
After you received the emails to the local folder, we can use the following code to parse the email now. The following code demonstrates how to parse from, to, cc, subject, body text, attachments of all emails file received by previous sample.
/*[C# Example - Parse Email]*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
private static void ParseEmail(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);
//Parse Mail From/Sender
Console.WriteLine("From: {0}", oMail.From.ToString());
//Parse Mail To/Recipient
MailAddress[] addrs = oMail.To;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}
//Parse Mail CC
addrs = oMail.Cc;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}
//Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject);
//Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody);
//Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody );
//Parse Attachments
Attachment[] atts = oMail.Attachments;
for (int i = 0; i < atts.Length; i++)
{
Console.WriteLine("Attachment: {0}", atts[i].Name);
}
}
static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseEmail(files[i]);
}
}
}
}
TextBody and HtmlBody
Not every email has both text/plain body text and html body text. However, Mail object provides both TextBody and HtmlBody properties smartly. If the email has only text/plain body, then Mail object converts the text/plain body to html body automatically; if the email has only html body, then Mail object converts the html body to text/plain body automatically.
Verify digital signature and decrypt email in C#
Digital signature prevents email content is faked or changed in transport level. Encrypting email protects email content from exposure to inappropriate recipients. Both digital signature and email encrypting depend on digital certificate.
How to sign email content?
Digital signature is always signed by sender certificate. The certificate used to sign email content MUST have the public/private key pair. First of all, the user MUST get a digital certificate for personal email protection from third-party certificate authorities such as www.verisign.com. After the certificate is installed on the machine, it can be viewed by "Control Panel"->"Internet Options"->"Content"->"Certificates"->"Personal". When you view the certificate, please note there is a line "You have a private key that corresponds to this certificate" in the certificate view, that means you are able to use this certificate to sign email content. If this line doesn't appear, that means you are unable to sign the email content by this certificate. To sign email content, please refer to EASendMail SMTP Component.
How to encrypt email?
Encrypting email doesn't require sender certificate but the certificate with public key for every recipient. For example, from@adminsystem.com sends an email to rcpt@adminsystem.com with digital signature. The digital signature contains the public key certificate for from@adminsystem.com, then rcpt@adminsystem.com can send an encrypted email with this certificate back to from@adminsystem.com. Only from@adminsystem can read this email, because this email MUST be decrypted by private key of from@adminsystem.com. Therefore, you MUST receive an digital signed email from other people (Most email clients such as outlook, outlook express will add the certificate to the Other People Storage automatically once an digital signed email is received) before you can send encrypted email to this people. To encrypt email, please refer to EASendMail SMTP Component.
Verify signed email and decrypt the encrypted email.
EAGetMail Mail class provides an easy way to verify the email digital signature and get the signer certificate. The signer certificate only contains the public key, that means you can add this certificate to your user certificate storage so that you can use this certificate to encrypt email and send the encrypted email back to the sender, only the sender can decrypt the email.
Please have a look at the following sample codes:
/*[C# Example - Verify digital signature and decrypt email]*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
private static void ParseEmail(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);
if (oMail.IsEncrypted)
{
try
{
//this email is encrypted, we decrypt it by user default certificate.
// you can also use specified certificate like this
// Certificate oCert = new Certificate();
// oCert.Load("c:\test.pfx", "pfxpassword",
// Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
// oMail = oMail.Decrypt( oCert );
oMail = oMail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
if (oMail.IsSigned)
{
try
{
//this email is digital signed.
EAGetMail.Certificate cert = oMail.VerifySignature();
Console.WriteLine("This email contains a valid digital signature.");
//you can add the certificate to your certificate storage like this
//cert.AddToStore(
// Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
// "addressbook" );
// then you can use send the encrypted email back to this sender.
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
//Parse Mail From/Sender
Console.WriteLine("From: {0}", oMail.From.ToString());
//Parse Mail To/Recipient
MailAddress[] addrs = oMail.To;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}
//Parse Mail CC
addrs = oMail.Cc;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}
//Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject);
//Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody);
//Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody );
//Parse Attachments
Attachment[] atts = oMail.Attachments;
for (int i = 0; i < atts.Length; i++)
{
Console.WriteLine("Attachment: {0}", atts[i].Name);
}
}
static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseEmail(files[i]);
}
}
}
}
Parse winmail.dat (TNEF) in C#
When an Outlook user composes and sends a message using either Rich Text Format or HTML Format, Outlook automagically generates a file, winmail.dat, and attaches it to the end of the email. The winmail.dat contains the rich text body and original attachments. To parse winmail.dat (TNEF) file, we should use ParseTNEF method.
/*[C# Example - Parse winmail.dat (TNEF Parser)]*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
private static void ParseEmail(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);
if (oMail.IsEncrypted)
{
try
{
//this email is encrypted, we decrypt it by user default certificate.
// you can also use specified certificate like this
// Certificate oCert = new Certificate();
// oCert.Load("c:\test.pfx", "pfxpassword",
// Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
// oMail = oMail.Decrypt( oCert );
oMail = oMail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
if (oMail.IsSigned)
{
try
{
//this email is digital signed.
EAGetMail.Certificate cert = oMail.VerifySignature();
Console.WriteLine("This email contains a valid digital signature.");
//you can add the certificate to your certificate storage like this
//cert.AddToStore(
// Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
// "addressbook" );
// then you can use send the encrypted email back to this sender.
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
//Parse Mail From/Sender
Console.WriteLine("From: {0}", oMail.From.ToString());
//Parse Mail To/Recipient
MailAddress[] addrs = oMail.To;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}
//Parse Mail CC
addrs = oMail.Cc;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}
//Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject);
//Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody);
//Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody );
//Parse Attachments
Attachment[] atts = oMail.Attachments;
for (int i = 0; i < atts.Length; i++)
{
Attachment att = atts[i];
//this attachment is in OUTLOOK RTF format(TNEF), decode it here.
if (String.Compare(att.Name, "winmail.dat") == 0)
{
Attachment[] tatts = null;
try
{
tatts = Mail.ParseTNEF(att.Content, true);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
continue;
}
int y = tatts.Length;
for (int x = 0; x < y; x++)
{
Attachment tatt = tatts[x];
Console.WriteLine("winmail.dat: {0}", tatt.Name);
}
continue;
}
Console.WriteLine("Attachment: {0}", att.Name);
}
}
static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseEmail(files[i]);
}
}
}
}
Parse email to HTML page and display it in Web browser
Finally, I want to introduce a simple way to convert email file to HTML page. After the email was converted to HTML page, you can browse it with web browser. You can get everything in the HTML page such as From, To, Cc, Subject, Date, Attachments.
/*[C# Example - Convert Email To HTML]*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
private static void ConvertMailToHtml(string fileName)
{
try
{
int pos = fileName.LastIndexOf(".");
string mainName = fileName.Substring(0, pos);
string htmlName = mainName + ".htm";
string tempFolder = mainName;
if (!File.Exists(htmlName))
{ //we haven't generate the html for this email, generate it
now.
_GenerateHtmlForEmail(htmlName, fileName, tempFolder);
}
Console.WriteLine("Please open {0} to browse your email",
htmlName);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
private static string _FormatHtmlTag(string src)
{
src = src.Replace(">", ">");
src = src.Replace("<", "<");
return src;
}
//we generate a html + attachment folder for every email, once the
html is create,
// next time we don't need to parse the email again.
private static void _GenerateHtmlForEmail(string htmlName, string emlFile,
string tempFolder)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);
if (oMail.IsEncrypted)
{
try
{
//this email is encrypted, we decrypt it by user default certificate.
oMail = oMail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
oMail.Load(emlFile, false);
}
}
if (oMail.IsSigned)
{
try
{
//this email is digital signed.
EAGetMail.Certificate cert = oMail.VerifySignature();
Console.WriteLine("This email contains a valid digital signature.");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
//Parse html body
string html = oMail.HtmlBody;
StringBuilder hdr = new StringBuilder();
//Parse sender
hdr.Append("<font face=\"Courier New,Arial\" size=2>");
hdr.Append("<b>From:</b> " + _FormatHtmlTag(oMail.From.ToString()) + "<br>");
//Parse to
MailAddress[] addrs = oMail.To;
int count = addrs.Length;
if (count > 0)
{
hdr.Append("<b>To:</b> ");
for (int i = 0; i < count; i++)
{
hdr.Append(_FormatHtmlTag(addrs[i].ToString()));
if (i < count - 1)
{
hdr.Append(";");
}
}
hdr.Append("<br>");
}
//Parse cc
addrs = oMail.Cc;
count = addrs.Length;
if (count > 0)
{
hdr.Append("<b>Cc:</b> ");
for (int i = 0; i < count; i++)
{
hdr.Append(_FormatHtmlTag(addrs[i].ToString()));
if (i < count - 1)
{
hdr.Append(";");
}
}
hdr.Append("<br>");
}
hdr.Append(String.Format("<b>Subject:</b>{0}<br>\r\n",
_FormatHtmlTag(oMail.Subject)));
//Parse attachments and save to local folder
Attachment[] atts = oMail.Attachments;
count = atts.Length;
if (count > 0)
{
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);
hdr.Append("<b>Attachments:</b>");
for (int i = 0; i < count; i++)
{
Attachment att = atts[i];
//this attachment is in OUTLOOK RTF format, decode it here.
if (String.Compare(att.Name, "winmail.dat") == 0)
{
Attachment[] tatts = null;
try
{
tatts = Mail.ParseTNEF(att.Content, true);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
continue;
}
int y = tatts.Length;
for (int x = 0; x < y; x++)
{
Attachment tatt = tatts[x];
string tattname = String.Format("{0}\\{1}", tempFolder, tatt.Name);
tatt.SaveAs(tattname, true);
hdr.Append(
String.Format("<a href=\"{0}\" target=\"_blank\">{1}</a> ",
tattname, tatt.Name));
}
continue;
}
string attname = String.Format("{0}\\{1}", tempFolder, att.Name);
att.SaveAs(attname, true);
hdr.Append(String.Format("<a href=\"{0}\" target=\"_blank\">{1}</a> ",
attname, att.Name));
if (att.ContentID.Length > 0)
{ //show embedded images.
html = html.Replace("cid:" + att.ContentID, attname);
}
else if (String.Compare(att.ContentType, 0, "image/", 0,
"image/".Length, true) == 0)
{
//show attached images.
html = html + String.Format("<hr><img src=\"{0}\">", attname);
}
}
}
Regex reg = new Regex("(<meta[^>]*charset[ \t]*=[ \t\"]*)([^<> \r\n\"]*)",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = reg.Replace(html, "$1utf-8");
if (!reg.IsMatch(html))
{
hdr.Insert(0,
"<meta HTTP-EQUIV=\"Content-Type\" Content=\"text-html; charset=utf-8\">");
}
//write html to file
html = hdr.ToString() + "<hr>" + html;
FileStream fs = new FileStream(htmlName, FileMode.Create,
FileAccess.Write, FileShare.None);
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(html);
fs.Write(data, 0, data.Length);
fs.Close();
oMail.Clear();
}
static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
//if the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
//convert all emails received to html page
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ConvertMailToHtml(files[i]);
}
}
}
}
Total Sample Projects
After you downloaded the EAGetMail POP3 Component Installer and install it on your machine, there are many samples in the installation path.
| pop3_imap4_simple.vb6 | Receives and parses email from POP3 & IMAP4 with Visual Basic 6.0. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (VB6, ActiveX/COM) |
| pop3_imap4_simple.vb | Receives and parses email from POP3 & IMAP4 with Visual Basic.NET. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption.(VB.NET, .NET) |
| pop3_imap4_simple.csharp | Receives and parses email from POP3 & IMAP4 with CSharp.NET. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (C#, .NET) |
| pop3_imap4_simple.vc | Receives and parses email from POP3 & IMAP4 with Managed C++. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption.(Managed C++, .NET) |
| pop3_imap4_simple.vcNative | Receives and parses email from POP3 & IMAP4 with Native Visual C++. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (Visual C++, ActiveX/COM) |
| imap4_full.vb6 | Full functionality of IMAP4 including folder management, mail flags. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (VB6, ActiveX/COM) |
| imap4_full.vb | Full functionality of IMAP4 including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (V.NET, .NET) |
| imap4_full.csharp | Full functionality of IMAP4 including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (C#, .NET) |
| pocketpc.mobile.cs | Receives and parses email from POP3 & IMAP4 with CSharp.NET on Windows Mobile Platform.(C#, .NET) |
| pocketpc.mobile.vb | Receives and parses email from POP3 & IMAP4 with VB.NET on Windows Mobile Platform.(VB, .NET) |
| ParseEmail.js/ParseEmail.vbs | Parses email file by JScript/VBScript.(Jscript, VBScript, ActiveX/COM) |
| PreviewEmail.js/PreviewEmail.vbs | Download email header from POP3/IMAP4 server by JScript/VBScript.(Jscript, VBScript, ActiveX/COM) |
| asp | Receives and parses email from POP3 & IMAP4 with ASP.(ASP, VBScript, ActiveX/COM) |
| asp_queue | Receives email from POP3 & IMAP4 with EAGetMail Service.(ASP, VBScript, ActiveX/COM) |
| asp_net | Receives and parses email from POP3 & IMAP4 with ASP.NET.(ASP.NET, C#, .NET) |
| asp_net_queue | Receives email from POP3 & IMAP4 with EAGetMail Service.(ASP.NET, C#, .NET) |
Free Email Support
Not enough? Please contact our technical support team.
Support@EmailArchitect.NET
VIP@EmailArchitect.NET(Registered User)
Remarks
We usually reply emails in 24hours. The reason for getting no response is likely
that your smtp server bounced our reply. In this case, please try to use another
email address to contact us. Your Hotmail or Yahoo email account is recommended.
|