This tutorial introduces how to retrieve email and parse email in C# using POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates retrieving email over SSL/TLS connection, verifying email digital signature, decrypting encrypted email (S/MIME), parsing email attachment, parsing non-delivery report (NDR) and managing mail folder.
Sections:
To better demonstrate how to retrieve email and parse email, let’s create a C# console project named “receiveemail” at first, and then add the reference of EAGetMail in your project.
EAGetMail is a POP3 and IMAP4 component which supports all operations of POP3/IMAP4/MIME/Exchange Web Service/WebDAV/SSL/S/MIME protocol. Before you can use the following example codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.
Install from NuGet
You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:
Install-Package EAGetMail
Note
If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.
To use EAGetMail POP3 & IMAP Component in your project, the first step is “Add reference
of EAGetMail to your project”. Please create or open your project with Visual Studio,
then go to menu
-> Project
-> Add Reference
-> .NET
-> Browse...
, and
select Installation Path\Lib\net[version]\EAGetMail{version}.dll
from installation path, click Open
-> OK
, the reference
will be added to the project, you can start to use it to
retrieve email and parse email 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 2.0, 4.0, 4.5, 4.6.1, 4.7.2, 4.8.1, .NET 6.0, NET 7.0, .NET 8.0, .NET Standard 2.0 and .Net Compact Framework 2.0, 3.5.
File | .NET Framework Version |
Lib\[net20|40|45|461|472|481]\EAGetMail.dll |
Built with .NET Framework 2.0, 4.0, 4.5, 4.6.1, 4.7.2, 4.8.1
It requires .NET Framework 2.0, 3.5 or later version. |
Lib\[net5.0|6.0|7.0|8.0]\EAGetMail.dll |
Built with .NET 5.0, .NET 6.0, .NET 7.0, .NET 8.0
It requires .NET 5.0 or later version. |
Lib\netstandard2.0\EAGetMail.dll |
Built with .NET Standard 2.0
It requires .NET Standard 2.0 or later version. |
Lib\[net20-cf|net35-cf]\EAGetMail.dll |
Built with .NET Compact Framework 2.0, 3.5
It requires .NET Compact Framework 2.0, 3.5 or later version. |
Now add the following codes to the project. The following codes demonstrate how
to retrieve email from a POP3 mail account. It downloads emails from POP3
server and deletes the email after the email is retrieved. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Pop3);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 995;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 110;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from POP3 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
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.
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.
When you retrieve email in above simple project, if it returned an error, please have a look at the following tips:
This error means DNS server cannot resolve POP3 server, you should check if you input correct server address. If your server address is correct, you should check if your DNS server setting is correct.
This error means there is a problem with networking connection to POP3 server. You can use Windows built-in Telnet command to detect the networking connection.
Note
Notice: in Windows 2008/Windows 8 or later version, Telnet Client is not installed by default, you should enable this command in Control Panel
-> Programs and Features
-> Turn Windows feature on or off
-> have Telnet Client
checked.
Under DOS command prompt, input telnet [serveraddress] [port]
telnet mail.emailarchitect.net 110
If the networking connection to your POP3 server is good, it should return a message like +OK ...
.
If it returns Could not open connection to ...
, that means the networking connection to POP3 server is bad,
or outbound 110 port is blocked by anti-virus software, firewall or ISP.
Please have a look at the following screenshot:
If you use telnet to test 995/993 port, it doesn’t return the +OK...
, because it requires SSL hand shake.
If the connection is ok, telnet returns a flash cursor.
Now SSL is commonly used, many email servers require SSL connection such as Gmail, Outlook, Office 365 and Yahoo.
In this case you should set MailServer.SSLConnection
to true
and change MailServer.Port
to 995 (POP3) or 993 (IMAP4).
This error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.
If POP3 server returns an error, it usually returns description about this error. You can use the following codes to generate a log file to learn all POP3 session between client and server.
[C# - Using log file to detect POP3 server response - Example]
oClient.LogFileName = "d:\\pop3.txt";
TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
In this section, I introduced retrieving email in C# with POP3 protocol. At next section I will introduce how to retrieve email from IMAP4 server.
In previous section, I introduced retrieving email from POP3 server in C#. In this section, I will introduce the IMAP4 server.
Sections:
IMAP4 protocol is different with POP3 protocol. First of all, IMAP4 supports retrieving email from different mail folder and folder management. Secondly, IMAP4 supports mail flags management. Therefore, we can do more things with IMAP4 server. To better understand the IMAP4 protocol, please see the following examples.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to download email from
IMAP4 server default mailbox.
In order to run it correctly, please change email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("imap.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 143;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Because IMAP4 protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.
The following example codes demonstrate how to retrieve emails
from “Deleted Items” in an IMAP4 account.
In order to run it correctly, please change email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// if you want to search sub folder, use parentfolder\subfolder as folderPath
// for example: inbox\mysubfolder
static Imap4Folder FindFolder(string folderPath, Imap4Folder[] folders)
{
int count = folders.Length;
for (int i = 0; i < count; i++)
{
Imap4Folder folder = folders[i];
if (string.Compare(folder.LocalPath, folderPath, true) == 0)
{
return folder;
}
folder = FindFolder(folderPath, folder.SubFolders);
if (folder != null)
{
return folder;
}
}
// No folder found
return null;
}
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("imap.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 143;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// find folder
Imap4Folder folder = FindFolder("Deleted Items", oClient.GetFolders());
if (folder == null)
{
throw new Exception("Folder not found!");
}
// select dest folder
oClient.SelectFolder(folder);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
At next section I will introduce how to retrieve email from Exchange Server with Web Service protocol.
In previous section, I introduced how to retrieve email from IMAP4 server. In this section, I will introduce the Exchange Web Service (EWS) protocol (Exchange 2007/2010/2013/2016/2019/Office365).
Sections:
Exchange Web Service (EWS) protocol is similar with IMAP4 protocol. First of all, it supports retrieving email from different mail folder and folder management. Secondly, Exchange Web Service supports mail read flag management. Therefore, we can do more things with Exchange server. To better understand the Exchange Web Service protocol, please see the following examples.
Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 or later version, POP3/IMAP4 service is disabled by default. If you don’t want to use POP3/IMAP4 to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007/2010/2013/2016 or later version) or WebDAV (Exchange 2000/2003) protocol.
Office 365 also supports EWS protocol.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to download email from
Exchange 2007/2010/2013/2016 server default mailbox using EWS protocol. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Please use domain\user or full email address as the user name
MailServer oServer = new MailServer("exch.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.ExchangeEWS);
// By default, Exchange Web Service (EWS) requires SSL connection
// Please ignore Port property for EWS and WebDAV protocol
oServer.SSLConnection = true;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 Exchange server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from Exchange server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from Exchange server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Because Exchange Web Service protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.
The following example codes demonstrate how to retrieve emails
from “Deleted Items” in an Exchange account. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// if you want to find sub folder, use parentfolder\subfolder as folderPath
// for example: inbox\mysubfolder
static Imap4Folder FindFolder(string folderPath, Imap4Folder[] folders)
{
int count = folders.Length;
for (int i = 0; i < count; i++)
{
Imap4Folder folder = folders[i];
if (string.Compare(folder.LocalPath, folderPath, true) == 0)
{
return folder;
}
folder = FindFolder(folderPath, folder.SubFolders);
if (folder != null)
{
return folder;
}
}
// No folder found
return null;
}
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Please use domain\user or full email address as the user name
MailServer oServer = new MailServer("exch.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.ExchangeEWS);
// By default, Exchange Web Service (EWS) requires SSL connection
// Please ignore Port property for EWS and WebDAV protocol
oServer.SSLConnection = true;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// find folder
Imap4Folder folder = FindFolder("Deleted Items", oClient.GetFolders());
if (folder == null)
{
throw new Exception("Folder not found!");
}
// select dest folder
oClient.SelectFolder(folder);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 Exchange server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from Exchange server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from Exchange server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to retrieve email from Exchange Server with WebDAV protocol.
In previous section, I introduced how to retrieve email from Exchange Server with Web Service (EWS) protocol in C#. In this section, I will introduce the WebDAV protocol (Exchange 2000/2003).
Sections:
Exchange WebDAV protocol is similar with IMAP4 protocol. First of all, it supports retrieving email from different mail folder and folder management. Secondly, Exchange WebDAV supports mail read flag management. Therefore, we can do more things with Exchange server. To better understand the WebDAV protocol, please see the following examples.
Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 or later version, POP3/IMAP4 service is disabled by default. If you don’t want to use POP3/IMAP4 to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007/2010 or later version) or WebDAV (Exchange 2000/2003) protocol.
For Exchange Server 2007 or later version, WebDAV service is also disabled by default, so please use Exchange Web Service (EWS) instead of WebDAV protocol.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to download email from
Exchange server default mailbox using WebDAV protocol. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Please use domain\user or full email address as the user name
MailServer oServer = new MailServer("exch.emailarchitect.net",
"emailarchitect.net\\test",
"testpassword",
ServerProtocol.ExchangeWebDAV);
// If your Exchange WebDAV server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 Exchange server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from Exchange server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from Exchange server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Because Exchange WebDAV protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.
The following example codes demonstrate how to retrieve emails
from “Deleted Items” in an Exchange account. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// if you want to find sub folder, use parentfolder\subfolder as folderPath
// for example: inbox\mysubfolder
static Imap4Folder FindFolder(string folderPath, Imap4Folder[] folders)
{
int count = folders.Length;
for (int i = 0; i < count; i++)
{
Imap4Folder folder = folders[i];
if (string.Compare(folder.LocalPath, folderPath, true) == 0)
{
return folder;
}
folder = FindFolder(folderPath, folder.SubFolders);
if (folder != null)
{
return folder;
}
}
// No folder found
return null;
}
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Please use domain\user or full email address as the user name
MailServer oServer = new MailServer("exch.emailarchitect.net",
"emailarchitect.net\\test",
"testpassword",
ServerProtocol.ExchangeWebDAV);
// If your Exchange WebDAV server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// find folder
Imap4Folder folder = FindFolder("Deleted Items", oClient.GetFolders());
if (folder == null)
{
throw new Exception("Folder not found!");
}
// select dest folder
oClient.SelectFolder(folder);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 Exchange server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from Exchange server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from Exchange server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to retrieve email over SSL connection.
In previous section, I introduced how to retrieve email from Exchange Server with WebDAV protocol. In this section, I will introduce how to retrieve email over SSL connection in C#.
Sections:
SSL connection encrypts data between the email component and POP3 server or IMAP4 server to protect user, password and email content in TCP/IP level. Now this technology is commonly used and many email servers are deployed with SSL such as Gmail, Yahoo and Hotmail.
There are two ways to deploy SSL on email server:
Implicit SSL
Deploying SSL on another port (POP3: 995 port or IMAP4: 993 port) directly. This is most common way.
Explicit SSL (TLS)
Using STARTTLS or STLS command to switch SSL channel on normal port (POP3: 110 port or IMAP4: 143 port);
TLS is the successor of SSL, EAGetMail supports SSL 3.0/TLS1.0 - 1.2 very well. In EAGetMail, ConnectTLS doesn’t mean TLS encryption, it means TLS command in POP3/IMAP protocol.
You don’t have to set any property to enable TLS 1.2 encryption. If your server requires TLS 1.2 encryption, TLS 1.2 encryption is used automatically with ConnectTLS, ConnectSSL or ConnectSSLAuto.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
EAGetMail POP3 component supports both Implicit SSL
and Explicit SSL
.
For Exchange Web Service/WebDAV protocol, the SSL is based on HTTPS connection, so you just need to set SSLConnection property and simply ignore Port property. Notice: Exchange Web Service requires SSL connection by default.
// Retrieve email by normal TCP/IP without SSL connection
// POP3
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", false,
ServerAuthType.AuthLogin, ServerProtocol.Pop3);
// IMAP4
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", false,
ServerAuthType.AuthLogin, ServerProtocol.Imap4);
// Retrieve email over SSL connection with direct SSL.
// POP3 SSL
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", true,
ServerAuthType.AuthLogin, ServerProtocol.Pop3);
oServer.Port = 995;
// IMAP4 SSL
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", true,
ServerAuthType.AuthLogin, ServerProtocol.Imap4);
oServer.Port = 993;
// Retrieve email by SSL connection with STARTTLS or TLS command switching
// POP3 TLS
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", true,
ServerAuthType.AuthLogin, ServerProtocol.Pop3);
oServer.Port = 110;
oServer.SSLType = SSLConnectType.ConnectTLS;
// IMAP4 STARTTLS
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", true,
ServerAuthType.AuthLogin, ServerProtocol.Imap4);
oServer.Port = 143;
oServer.SSLType = SSLConnectType.ConnectTLS;
// Exchange WebDAV
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", false,
ServerAuthType.AuthLogin, ServerProtocol.ExchangeWebDAV);
// Exchange Web Service SSL
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", true,
ServerAuthType.AuthLogin, ServerProtocol.ExchangeEWS);
// Exchange WebDAV SSL
MailServer oServer = new MailServer("myserveraddress",
"myuser", "mypassword", true,
ServerAuthType.AuthLogin, ServerProtocol.ExchangeWebDAV);
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to retrieve emails
from POP3 server over SSL connection on 995 port. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Pop3);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 995 SSL port
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from POP3 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
The following example codes demonstrate how to retrieve emails
from IMAP4 server over SSL connection on 993 port. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("imap.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to download emails from Gmail account.
In previous section, I introduced how to retrieve email over SSL connection. In this section, I will introduce how to download email from your Gmail account in C#.
Sections:
Gmail POP3 server address is pop.gmail.com
. It requires SSL connection on 995
port, and you should use your Gmail email address as the user name for user authentication.
Gmail IMAP4 server address is imap.gmail.com
. It requires SSL connection on 993
port, and you should use your Gmail email address as the user name for user authentication.
For example: your email is gmailid@gmail.com
, and then the user name should be
gmailid@gmail.com
.
To retrieve email from Gmail account, you need to enable POP3 or IMAP4 access in your gmail account settings.
Because Gmail POP3 server doesn’t work like normal POP3 server, it hides old emails automatically even the email was not deleted, so we suggest that you use IMAP4 protocol.
Server | Port | SSL | Protocol |
pop.gmail.com | 995 | SSL required | Pop3 |
imap.gmail.com | 993 | SSL required | Imap4 (recommended) |
To help keep your account secure, starting May 30, 2022, Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
Therefore, you should sign in using App Passwords.
An App Password
is a 16-digit passcode that gives a less secure app or device permission
to access your Google Account. App Passwords
can only be used with accounts that have 2-Step Verification turned on.
You need to use App Password
instead of the user password for user authentication.
Another solution is Gmail OAUH, please see Gmail IMAP OAUTH section.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to download email from Gmail account using IMAP4 protocol.
Because Gmail POP3 server doesn’t work like normal POP3 server, it hides old emails automatically even the email was not deleted, so we suggest that you use IMAP4 protocol.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Create app password in Google account
// https://support.google.com/accounts/answer/185833?hl=en
// Gmail IMAP4 server is "imap.gmail.com"
MailServer oServer = new MailServer("imap.gmail.com",
"gmailid@gmail.com",
"your app password",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
By default, you can generate an App Passwords, and use this app password instead of the user password for IMAP4 authentication.
However, Google will disable traditional user authentication in the future, switching to Google OAuth is strongly recommended now.
Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from Gmail like this
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Create app password in Google account
// https://support.google.com/accounts/answer/185833?hl=en
// Gmail IMAP4 server is "imap.gmail.com"
MailServer oServer = new MailServer("imap.gmail.com",
"gmailid@gmail.com",
"your app password",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// retrieve unread/new email only
oClient.GetMailInfosParam.Reset();
oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// mark unread email as read, next time this email won't be retrieved again
if(!info.Read)
{
oClient.MarkAsRead(info, true);
}
// if you don't want to leave a copy on server, please use
// oClient.Delete(info);
// instead of MarkAsRead
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
At next section I will introduce how to download emails from Yahoo account.
In previous section, I introduced how to download emails from Gmail account. In this section, I will introduce how to download emails from your Yahoo account in C#.
Sections:
Yahoo POP3 server address is pop.mail.yahoo.com
.
It requires SSL connection on 995 port;
Yahoo IMAP4 server address is imap.mail.yahoo.com
. It requires SSL connection on 993 port.
You should use your Yahoo email address as the user name for user authentication.
For example: your email is myid@yahoo.com
, and then the user name should be myid@yahoo.com
.
Server | Port | SSL | Protocol |
pop.mail.yahoo.com | 995 | SSL required | Pop3 |
imap.mail.yahoo.com | 993 | SSL required | Imap4 |
If you got authentication error, you need to enable Allowing less secure apps in your Yahoo account. Or you can generate an App Passwords and use this app password instead of the user password.
Although Yahoo supports OAUTH, but it doesn’t provide mail permission, so OAUTH is not a solution for Yahoo mail.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to download
emails from Yahoo account. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Yahoo POP3 server is "pop.mail.yahoo.com"
MailServer oServer = new MailServer("pop.mail.yahoo.com",
"myid@yahoo.com",
"yourpassword",
ServerProtocol.Pop3);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 995 SSL port
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from POP3 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
The following example codes demonstrate how to download emails from Yahoo account using IMAP4 protocol.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Yahoo IMAP server is "imap.mail.yahoo.com"
MailServer oServer = new MailServer("imap.mail.yahoo.com",
"myid@yahoo.com",
"yourpassword",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from Yahoo like this
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Yahoo IMAP server is "imap.mail.yahoo.com"
MailServer oServer = new MailServer("imap.mail.yahoo.com",
"myid@yahoo.com",
"yourpassword",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// retrieve unread/new email only
oClient.GetMailInfosParam.Reset();
oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// mark unread email as read, next time this email won't be retrieved again
if(!info.Read)
{
oClient.MarkAsRead(info, true);
}
// if you don't want to leave a copy on server, please use
// oClient.Delete(info);
// instead of MarkAsRead
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
At next section I will introduce how to download emails from Hotmail/MSN Live/Office 365 account.
In previous section, I introduced how to download email from Yahoo account. In this section, I will introduce how to download email from Hotmail/MSN Live/Outlook.com/Office 365 account in C#.
Sections:
Hotmail/Outlook POP3 server address is outlook.office365.com
. It requires SSL connection
on 995 port; Hotmail/Outlook IMAP4 server address is outlook.office365.com
. It requires SSL connection
on 993 port;
You should use your Hotmail/Outlook email address as the user name
for user authentication. For example: your email is liveid@hotmail.com
, and then
the user name should be liveid@hotmail.com
.
Server | Port | SSL | Protocol |
outlook.office365.com | 995 | SSL required | Pop3 |
outlook.office365.com | 993 | SSL required | Imap4 |
If your account enabled two-factor authentication, you cannot login your account by normal user authentication,
you should create an App Passwords and
use this App Password
instead of the user password.
Another solution is using OAUH, please see Hotmail IMAP OAUTH section.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to download
email from Hotmail/MSN Live/Outlook account using POP3 protocol. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Hotmail/MSN POP3 server is "outlook.office365.com"
// If you got authentication error, try to create an app password instead of your user password.
// https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
MailServer oServer = new MailServer("outlook.office365.com",
"liveid@hotmail.com",
"your password or app password",
ServerProtocol.Pop3);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 995 SSL port
oServer.Port = 995;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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);
// download email from Hotmail/MSN server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from POP3 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
The following example codes demonstrate how to download email from Hotmail/MSN Live/Outlook account using IMAP4 protocol.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Hotmail/MSN IMAP4 server is "outlook.office365.com"
// If you got authentication error, try to create an app password instead of your user password.
// https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
MailServer oServer = new MailServer("outlook.office365.com",
"liveid@hotmail.com",
"your password or app password",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Microsoft Live SMTP servers (Hotmail, Oultook personal account) have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application.
Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.
First of all, you should go to Office 365 Outlook
-> Options
-> See All Options
-> Account
-> My Account
-> Settings for POP, IMAP, and SMTP access
.
You will get your Office 365 POP3/IMAP4 server address and port. The default POP3 server is outlook.office365.com
on SSL 995 port;
IMAP4 server is outlook.office365.com
on SSL 993 port.
Important
Office 365 has started to disable user login in POP/IMAP protocol, you should use Office365 POP/IMAP/EWS OAUTH instead of traditional user/password login.
Server | Port | SSL | Protocol |
outlook.office365.com | 995 | SSL required | Pop3 |
outlook.office365.com | 993 | SSL required | Imap4 |
If your account enabled two-factor authentication, you cannot login your account by normal user authentication,
you should create an App Passwords and
use this App Password
instead of the user password.
Office 365 has started to disable user login in POP/IMAP protocol, if basic authentication
has been disabled in your tenant,
you have to use Office365 POP/IMAP/EWS OAUTH.
The following example codes demonstrate how to download email from Offic 365 account using IMAP4 protocol.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Hotmail/MSN IMAP4 server is "outlook.office365.com"
// If you got authentication error, try to create an app password instead of your user password.
// https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
MailServer oServer = new MailServer("outlook.office365.com",
"yourid@domain",
"your password or app password",
ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 Office 365 IMAP4 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from Hotmail/Outlook/Office 365 like this
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Hotmail/MSN/Office365 IMAP4 server is "outlook.office365.com"
// If you got authentication error, try to create an app password instead of your user password.
// https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
MailServer oServer = new MailServer("outlook.office365.com",
"yourid@domain", "your password or app password", ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// retrieve unread/new email only
oClient.GetMailInfosParam.Reset();
oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// mark unread email as read, next time this email won't be retrieved again
if(!info.Read)
{
oClient.MarkAsRead(info, true);
}
// if you don't want to leave a copy on server, please use
// oClient.Delete(info);
// instead of MarkAsRead
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Microsoft Office365 servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application.
Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.
TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.
If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2
,
and you got connection error with SSL/TLS connection,
you need to enable TLS 1.2 protocol in your operating system like this:
Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012
Next Section
At next section I will introduce how to retrieve email with event handler.
In previous section, I introduced how to retrieve email from Hotmail/MSN Live account. In this section, I will introduce how to retrieve email with event handler in C#.
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.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to use EAGetMail POP3 component to retrieve
email with event handler. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
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");
}
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Pop3);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 995;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 110;
MailClient oClient = new MailClient("TryIt");
// 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 don't have 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);
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// Mark email as deleted from POP3 server.
oClient.Delete(info);
}
// Quit and expunge emails marked as deleted from POP3 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to use UIDL function to mark the email has been downloaded.
In previous section, I introduced how to use event handler. In this section, I will introduce how to use UIDL function to mark the email has been downloaded in C#.
Sections:
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.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
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. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("imap.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 143;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
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}.eml", info.UIDL);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
if(File.Exists(fullPath))
{
// This email has been downloaded before, 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(fullPath, true);
// Do not delete email from IMAP4 server.
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
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.
UIDL is also unique in Exchange Web Service/WebDAV, but the UIDL is string but not integer. UIDL in Exchange server may contain invalid characters for file name, so we cannot use UIDL as the file name either.
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 POP3/IMAP4/Exchange Web Service/WebDAV protocols.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
bool isUidlLoaded = false;
bool isLeaveCopy = true; // leave a copy of message on server.
// UIDL is the identifier of every email on POP3/IMAP4/Exchange 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.
// UIDLManager wraps the function to write/read uidl record from a text file.
UIDLManager oUIDLManager = new UIDLManager();
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
string uidlFile = string.Format("{0}\\uidl.txt", localInbox);
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Load existed uidl records to UIDLManager
oUIDLManager.Load(uidlFile);
isUidlLoaded = true;
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Pop3);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 995;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 110;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
// Remove the local uidl that is not existed on the server,
oUIDLManager.SyncUIDL(oServer, infos);
oUIDLManager.Update();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null)
{
// This email has been downloaded before
continue;
}
Console.WriteLine("Retrieving {0}/{1}...", i + 1, infos.Length);
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
if (isLeaveCopy)
{
// Add uidl to uidl file to avoid we retrieve it next time.
oUIDLManager.AddUIDL(oServer, info.UIDL, fileName);
}
else
{
Console.WriteLine("Deleting ...");
oClient.Delete(info);
// Remove UIDL from local uidl file.
oUIDLManager.RemoveUIDL(oServer, info.UIDL);
}
}
// Quit and expunge emails marked as deleted from POP3 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
// Update the uidl list to local uidl file and then we can load it next time.
if (isUidlLoaded)
{
oUIDLManager.Update();
}
}
}
}
With EAGetMail 4.0, it provides a new class named “UIDLManager”. This object provides an easy way to maintain UIDL between your server and your local client. How does it work? It stores UIDL collection to a local disk file and you can use this object to add, remove and search UIDL with this local file. Then you don’t have to handle UIDL in your code. Please click here to learn more detail.
With IMAP4/Exchange Web Service/WebDAV protocol, you can also mark the email as read on the server, but POP3 doesn’t support this feature. Please refer to MarkAsRead method to learn more detail.
Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from IMAP4/EWS/WebDAV like this
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("imap.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 143;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// retrieve unread/new email only
oClient.GetMailInfosParam.Reset();
oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
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 unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// mark unread email as read, next time this email won't be retrieved again
if(!info.Read)
{
oClient.MarkAsRead(info, true);
}
// if you don't want to leave a copy on server, please use
// oClient.Delete(info);
// instead of MarkAsRead
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to download email in background.
In previous section, I introduced how to use UIDL function to mark the email has been downloaded. In this section, I will introduce how to download email with background service in C#.
Sections:
In an ASP/ASP.NET email application, if email download takes longer than the timeout value (in seconds) that the current asp page is allowed to run, user will get an error “ASP Timeout”. This often happens when user has a large quantity of emails to download or user downloads emails via a slow connection. By default the timeout is set to 90 seconds, it is easy to exceed this limit.
Obviously, a solution to ASP timeout is to set ASPScriptTimeout a larger value. You may click here for details. Technically the timeout problem can be solved in this way; however, some users may get frustrated and press the stop button on the browser toolbar as he waits too long.
EAGetMail POP3 Component introduces a more intelligent method to retrieve emails in background. You should download the EAGetMail Service installer and install it on your machine at first. Then you can use MailClient.GetMailsByQueue method to send the request to EAGetMail Service, the method returns to the user immediately and the EAGetMail Service performs task in background.
Important
To run the following example, you need to download EAGetMail and EAGetMail Service at first, and then install both on your machine.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to retrieve
email with background service. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Globalization;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Pop3);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 995;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 110;
MailClient oClient = new MailClient("TryIt");
// Leave a copy of message on server.
bool leaveCopy = true;
// Download emails to this local folder
string downloadFolder = localInbox;
// Send request to EAGetMail Service, then EAGetMail Service retrieves email
// in background and this method returns immediately.
oClient.GetMailsByQueue(oServer, downloadFolder, leaveCopy);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
EAGetMail Service provides another advanced feature which allow you set a POP3/IMAP4 account in the EAGetMail Service Manager. EAGetMail Service can download emails from this account in specified time interval. If you need to process the email in the mailbox on a regular basis, you just need to create your mail process application, you don’t need to write your email download task part.
Finally you just need to set your mail account in EAGetMail Service Manager and specify your application or COMMAND, EAGetMail service will download the emails and invoke your application automatically. Please refer to Mail Pull for more detail.
I also suggest that you have a look at Parse Non-Delivery Report (NDR) using EAGetMail Service. It demonstrates how to set a schedule to check a mailbox and insert non-delivery report to SQL database.
Next Section
At next section I will introduce how to parse email in C#.
In previous section, I introduced how to download email with background service. In this section, I will introduce how to parse email in C#.
Sections:
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.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to use EAGetMail POP3 component to parse
email sender, to, cc, subject, body text and attachments. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
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)
{
try
{
ParseEmail("c:\\my folder\\test.eml");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
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.
Next Section
At next section I will introduce how to verify digital signature and decrypt email.
In previous section, I introduced how to parse email. In this section, I will introduce how to verify digital signature and decrypt email in C#.
How to sign email?
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.
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.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to use EAGetMail POP3 component to verify
digital signature and decrypt email. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
using System.Security.Cryptography.X509Certificates;
namespace receiveemail
{
class Program
{
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
/* X509Certificate2 decryptCert = new X509Certificate2("D:\\mycert\\test.pfx",
"nosecret",
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
oMail.DecryptMessage(decryptCert);
*/
oMail.DecryptMessage(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
if (oMail.IsSigned)
{
try
{
// This email is digital signed.
X509Certificate2 signerCert = oMail.VerifyMessageSignature();
Console.WriteLine("This email contains a valid digital signature.");
// You can add the certificate to your certificate storage like this
/*
X509Store store = new X509Store("My", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(signerCert);
store.Close();
*/
// 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)
{
try
{
ParseEmail("c:\\my folder\\test.eml");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to parse MAPI winmail.dat (TNEF/MAPI) attachment.
In previous section, I introduced how to verify digital signature and decrypt email. In this section, I will introduce how to parse winmail.dat (TNEF stream) in C#.
Sections:
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 stream) file, we should use ParseTNEF method.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to parse MAPI winmail.dat.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
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];
Console.WriteLine("Attachment: {0}", att.Name);
// This attachment is in OUTLOOK RTF format(TNEF stream), decode it here.
if (string.Compare(att.Name, "winmail.dat", true) == 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);
}
}
}
}
static void Main(string[] args)
{
try
{
ParseEmail("c:\\my folder\\test.eml");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
In EAGetMail 4.5, a new method named DecodeTNEF is introduced. It is easier to parse TNEF attachment. Please have a look at the following example codes:
using System;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
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);
}
}
// Decode winmail.dat (TNEF) and RTF body automatically
oMail.DecodeTNEF();
// 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)
{
try
{
ParseEmail("c:\\my folder\\test.eml");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
Next Section
At next section I will introduce how to convert email to HTML page and display it in Web browser.
In previous section, I introduced how to parse winmail.dat. In this section, I will introduce how to parse email body and attachment, then convert email to a HTML page and display it using Web browser in C#.
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 and Embedded images.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to use EAGetMail POP3 component to convert email to HTML page.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static string _formatHtmlTag(string src)
{
src = src.Replace(">", ">");
src = src.Replace("<", "<");
return src;
}
static string _formatAddresses(MailAddress[] addresses, string prefix)
{
if (addresses.Length == 0)
{
return "";
}
StringBuilder buffer = new StringBuilder();
buffer.Append(string.Format("<b>{0}:</b> ", prefix));
for (int i = 0; i < addresses.Length; i++)
{
buffer.Append(_formatHtmlTag(addresses[i].ToString()));
if (i < addresses.Length - 1)
{
buffer.Append("; ");
}
}
buffer.Append("<br>");
return buffer.ToString();
}
// 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.
static void _generateHtmlForEmail(string emlFile, string htmlFile,
string attachmentFolder)
{
// For evaluation usage, please use "TryIt" as the license code, otherwise the
//"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
//"trial version expired" exception will be thrown.
Mail mail = new Mail("TryIt");
mail.Load(emlFile, false);
if (mail.IsEncrypted)
{
try
{
// this email is encrypted, we decrypt it by user default certificate.
// you can also use specified certificate like this
// oCert = new Certificate();
// oCert.Load("c:\\test.pfx", "pfxpassword", Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
// oMail = oMail.Decrypt( oCert );
mail = mail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
if (mail.IsSigned)
{
try
{
// This email is digital signed.
Certificate signerCertificate = mail.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);
}
}
// Decode winmail.dat (Outlook TNEF stream) automatically.
// also convert RTF body to HTML body automatically.MO
mail.DecodeTNEF();
string html = mail.HtmlBody;
StringBuilder header = new StringBuilder();
header.Append("<font face=\"Courier New,Arial\" size=2>");
header.Append("<b>From:</b> " + _formatHtmlTag(mail.From.ToString()) + "<br>");
header.Append(_formatAddresses(mail.To, "To"));
header.Append(_formatAddresses(mail.Cc, "Cc"));
header.Append(string.Format("<b>Subject:</b>{0}<br>\r\n", _formatHtmlTag(mail.Subject)));
Attachment[] attachments = mail.Attachments;
if (attachments.Length > 0)
{
if (!Directory.Exists(attachmentFolder))
Directory.CreateDirectory(attachmentFolder);
header.Append("<b>Attachments:</b> ");
for (int i = 0; i < attachments.Length; i++)
{
Attachment attachment = attachments[i];
string attachmentName = string.Format("{0}\\{1}", attachmentFolder, attachment.Name);
attachment.SaveAs(attachmentName, true);
header.Append(string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a> ",
attachmentName, attachment.Name));
if (attachment.ContentID.Length > 0)
{ // Show embedded image.
html = html.Replace("cid:" + attachment.ContentID, attachmentName);
}
}
}
// Change original meta header encoding to utf-8
Regex reg = new Regex("(<meta[^>]*charset[ \t]*=[ \t\"]*)([^<> \r\n\"]*)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = reg.Replace(html, "$1utf-8");
if (!reg.IsMatch(html))
{
header.Insert(0, "<meta HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=utf-8\">");
}
html = header.ToString() + "<hr>" + html;
using (FileStream stream = new FileStream(htmlFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] buffer = Encoding.UTF8.GetBytes(html);
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
}
static void ConvertMailToHtml(string emlFile)
{
try
{
int pos = emlFile.LastIndexOf(".");
string attachmentFolder = emlFile.Substring(0, pos);
string htmlFile = attachmentFolder + ".htm";
if (!File.Exists(htmlFile))
{
// We haven't generate the html for this email, generate it now.
_generateHtmlForEmail(emlFile, htmlFile,attachmentFolder);
}
Console.WriteLine("Please open {0} to browse your email",
htmlFile);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
static void Main(string[] args)
{
ConvertMailToHtml("c:\\my folder\\test.eml");
}
}
}
In EAGetMail installer, there are many samples demonstrate how to use Web browser control to display the email, I suggest that you download it and have a try
Next Section
At next section I will introduce how to parse Non-delivery report.
In previous section, I introduced how to convert email to HTML page. In this section, I will introduce how to parse Non-delivery report (NDR) in C#.
Sections:
Some e-mail applications, such as Microsoft Office Outlook, employ a read-receipt tracking mechanism. A sender selects the receipt request option prior to sending the message. Upon opening the email, each recipient has the option of notifying the sender that the message was opened and read.
However, there is no guarantee that you will get a read-receipt. Some possible reason are that very few e-mail applications or services support read receipts, or simply because users disable the functionality. Those do support read-receipt aren’t necessarily compatible with or capable of recognizing requests from a different e-mail service or application
It is also called a DSN (delivery service notification), which is a request to the recipient’s email server to send you a notification about the delivery of an email you’ve just sent. The notification takes the form of an email, and will tell you if your delivery succeeded (Delivery Receipt), failed, got delayed (Failure Report).
For many email campaign applications, the very important task is detecting if the email is received by recipient or not. Parsing the delivery report is the common way to get the email status. EAGetMail .NET class provides a built-in function (GetReport) to parse the report. The following sample demonstrates how to parse the delivery-report.
If ReporType is DeliveryReceipt
or ReadReceipt
, the report probably
has only OriginalSender, OriginalRecipient and OriginalMessageID information in
the report, it depends on the mail server that generated the report.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to parse delivery report.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void ParseReport(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);
if (!oMail.IsReport)
{
Console.WriteLine("This is not a delivery report.");
return;
}
MailReport oReport = oMail.GetReport();
switch (oReport.ReportType)
{
case DeliveryReportType.DeliveryReceipt:
Console.WriteLine("This is a delivery receipt!");
break;
case DeliveryReportType.ReadReceipt:
Console.WriteLine("This is a read receipt!");
break;
case DeliveryReportType.Deleted:
Console.WriteLine("This is a unread receipt, this email was deleted without read!");
break;
case DeliveryReportType.DelayedReport:
Console.WriteLine("This is a delayed report, server will retry to deliver it automatically!");
break;
default:
Console.WriteLine("This is a failure report!");
break;
}
Console.WriteLine("OriginalSender: {0}", oReport.OriginalSender);
Console.WriteLine("OriginalRecipient: {0}", oReport.OriginalRecipient);
Console.WriteLine("OriginalMessageID: {0}", oReport.OriginalMessageID);
if (oReport.ReportType == DeliveryReportType.FailureReport || oReport.ReportType == DeliveryReportType.DelayedReport)
{
Console.WriteLine("ErrCode: {0}", oReport.ErrCode);
Console.WriteLine("ErrDescription: {0}", oReport.ErrDescription);
Console.WriteLine("OriginalSubject: {0}", oReport.OriginalSubject);
Console.WriteLine("ReportMTA: {0}", oReport.ReportMTA);
Console.WriteLine(oReport.OriginalHeaders.ToString());
}
}
static void Main(string[] args)
{
try
{
ParseReport("c:\\my folder\\test.eml");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
To retrieve and parse Failure Report (NDR), you should monitor your sender mailbox. Here I will introduce how to use EAGetMail Service to monitor a mailbox and retrieve non-delivery report and insert it to SQL server on a regular basis.
To use EAGetMail Service, you need to download EAGetMail Service and install it on your machine at first.
Then create a table in your SQL database like this:
CREATE TABLE [dbo].[Failure_Report](
[reportid] [int] IDENTITY(1,1) NOT NULL,
[address] [nvarchar](255) NOT NULL,
[error_code] [nchar](10) NOT NULL,
[error_desc] [nchar](255) NOT NULL,
[error_datetime] [datetime] NOT NULL
) ON [PRIMARY]
GO
Create a C# console application named “parse_reports”, then
Input the following codes:
using System;
using System.Text;
using EAGetMail;
using System.IO;
using System.Data.SqlClient;
namespace parse_reports
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Parse_Reports.exe [email folder path]\r\n");
Console.WriteLine("eg: Parse_Reports.exe \"c:\\my folder\"\r\n");
return;
}
try
{
// change it to your sql server address, database, user and password
// The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
// e.g.: Server=serveraddress\\instancename;
// open database connection
SqlConnection oConn = new SqlConnection("Server=localhost;Database=myDB;User Id=myUser;Password=myPassword;");
oConn.Open();
string[] files = Directory.GetFiles(args[0], "*.eml");
Console.WriteLine("Total {0} email(s)", files.Length);
int count = files.Length;
for (int i = 0; i < count; i++)
{
string fileName = files[i];
if (ParseEmail(fileName, oConn))
{
// Delete the local report file.
File.Delete(fileName);
}
}
oConn.Close();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
Console.WriteLine(ep.StackTrace);
}
}
static bool ParseEmail(string fileName, SqlConnection oConn)
{
Mail oMail = new Mail("TryIt");
oMail.Load(fileName, true);
// detect if this is a report or receipt
if (!oMail.IsReport)
{
Console.WriteLine("Not a report or receipt!");
return false;
}
MailReport oReport = oMail.GetReport();
// we only process failure report
if (oReport.ReportType != DeliveryReportType.FailureReport)
{
Console.WriteLine("Not a failure report!");
return false;
}
Console.WriteLine("OriginalRecipient: {0}", oReport.OriginalRecipient);
Console.WriteLine("ErrorCode: {0}", oReport.ErrCode);
Console.WriteLine("ErrorDesc: {0}", oReport.ErrDescription);
string errorDesc = oReport.ErrDescription;
if (errorDesc.Length > 250)
errorDesc = errorDesc.Substring(0, 250);
// INSERT the result to database.
string sql = "INSERT INTO [dbo].[Failure_Report] " +
" ([address] " +
" ,[error_code] " +
" ,[error_desc] " +
" ,[error_datetime]) " +
" VALUES ( @address, @error_code, @error_desc, GETDATE())";
SqlCommand command = new SqlCommand(sql, oConn);
command.Parameters.AddWithValue("@address", oReport.OriginalRecipient);
command.Parameters.AddWithValue("@error_code", oReport.ErrCode);
command.Parameters.AddWithValue("@error_desc", errorDesc);
command.ExecuteNonQuery();
command.Dispose();
return true;
}
}
}
Finally, open EAGetMail Service Manager -> Mail Pull Configuration -> New:
Input your sender mailbox account information
Create a folder named “inbox” on your machine, this folder is used to store .EML file.
Input the folder full path to “Save email file(s) to specified local folder:”;
Input application full path [SPACE] folder full path to: “Run specified application after download is finished”.
For example:
If your application full path is d:\parse_reports.exe
and your folder is d:\inbox
, then input:
"d:\parse_reports.exe" "d:\inbox"
With above setting, EAGetMail Service checks mailbox every 15 minutes and once there is non-delivery report, it will invoke parse_reports.exe to process non-delivery report and insert it to database like this:
Important
If you have “Leave a copy of message on mail server” unchecked, EAGetMail Service will delete all emails in your mailbox after the emails were retrieved to local folder. If your mailbox is only used to retrieve non-delivery report, then I recommend you have “Leave a copy of message on mail server” unchecked to get better performance.
You can run your application directly under DOS prompt without EAGetMail Service. If there is any error, you can debug and fix it.
"d:\parse_reports.exe" "d:\inbox"
EAGetMail Service is a common solution to process email on a regular basis, you can use above solution to download and process normal emails as well. You just need to change/extend the codes in parse_reports.exe
Common SQL Driver Download
If SQL Server is installed on a remote server, and you don’t have SQL driver installed on local machine, then you need to download and install corresponding driver on local machine.
Next Section
At next section I will introduce how to manage folders with IMAP4/Exchange Web Service (EWS)/WebDAV protocol.
In previous section, I introduced how to parse non-delivery report (NDR) in C#. In this section, I will introduce how to create folders and manage folders with IMAP4/Exchange Web Service (EWS)/WebDAV protocol in C#.
Sections:
Because IMAP4/Exchange Web Service (EWS)/WebDAV protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”, I have introduced it in other sections. In this section, I will introduce how to use EAGetMail to create folder and delete folder with IMAP4/Exchange Web Service/WebDAV protocol. Notice: POP3 protocol doesn’t support this feature.
The following example codes demonstrate how to create folder and delete
folder. In order to run it correctly, please change
email server
, user
, password
, folder
, file name
values.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
try
{
// To create folder with Exchange Web Service, please change
// ServerProtocol.Imap4 to ServerProtocol.ExchangeEWS to MailServer constructor
// and also set oServer.SSLConnection to true
// To create folder with Exchange WebDAV, please change
// ServerProtocol.Imap4 to ServerProtocol.ExchangeWebDAV to MailServer constructor
// Exchange Server supports IMAP4 protocol as well, but in Exchange 2007
// or later version, IMAP4 service is disabled by default. If you don't want to use IMAP4
// to manage folder from Exchange Server, you can use Exchange Web Service (Exchange 2007-2019 or
// later version) or WebDAV (Exchange 2000/2003) protocol.
MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net",
"testpassword",
ServerProtocol.Imap4);
// Enable SSL/TLS connection, most modern email server require SSL/TLS by default
oServer.SSLConnection = true;
oServer.Port = 993;
// if your server doesn't support SSL/TLS, please use the following codes
// oServer.SSLConnection = false;
// oServer.Port = 143;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// create folder
Imap4Folder folder = oClient.CreateFolder(null, "TestFolder");
// get existed folders.
Imap4Folder[] folders = oClient.GetFolders();
for (int i = 0; i < folders.Length; i++)
{
Imap4Folder fd = folders[i];
Console.WriteLine("folder: {0}", fd.FullPath);
}
// delete folder
oClient.DeleteFolder(folder);
oClient.Logout();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
To retrieve emails from a specified folder, please use SelectFolder method; To move email from a folder to another folder, please use Move method; To copy email from a folder to another folder, please use Copy method; To upload an email file from local disk to server folder, please use Append method.
Note
Please refer to ImapFull project for more detail.
Since Exchange 2007 or later version (2010/203), IMAP4 protocol does not expose public folders to mail client. If you want to access public folders on MS Exchange 2007/2010/2013/2016/2019 or later version, please use MailClient.QueryEWSPublicFolders method.
Next Section
Total sample projects in EAGetMail Mail Component installation package.
After you downloaded the EAGetMail POP3 Component Installer and install it on your machine, there are many samples in the installation path.
All the samples locate at EAGetMail Installation Folder
. Most of sample projects demonstrate SSL/TLS Connection, UIDLManager,
S/MIME, Tnef (winmail.dat) Parsing, Retrieve/Parse Email and Gmail/Office365/Hotmail OAUTH/XOAUTH2.
C#\Simple | Retrieve email and parse email from ASP.NET Form with POP3/IMAP4/Exchange Web Service/WebDAV/Graph API/Gmail Rest API protocol. |
C#\QueueService | Download email from EAGetMail Background Service with POP3/IMAP4/Exchange Web Service/WebDAV protocol. |
C#, VB\Simple | Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV/Graph API/Gmail Rest API protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV/Graph API/Gmail Rest API) and Gmail/Office365/Hotmail OAUTH. |
C#, VB\SimpleWebView2 | Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to display email in WebView2. |
C#, VB\ParseReport | Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV/Graph API/Gmail Rest API protocol. |
C#, VB\ImapFull | Full functionality of IMAP4/EWS/WebDAV/Graph API/Gmail Rest API including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption. |
C#, VB\ImapFullWebView2 | Full functionality of IMAP4/EWS/WebDAV/Graph API/Gmail Rest API including folder management, email moving and mail flags. This sample also demonstrates how to display email in WebView2. |
C#, VB\pocketpc.mobile | Retrieve email and parse email from .NET Compact Framework with POP3/IMAP4/EWS/WebDAV protocol. |
VBScript\Simple | Retrieve email and parse email from ASP Form with POP3/IMAP4/Exchange Web Service/WebDAV protocol. |
VBScript\QueueService | Download email from EAGetMail Background Service with POP3/IMAP4/Exchange Web Service/WebDAV protocol. |
Simple | Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV) and Gmail/Office365/Hotmail OAUTH. |
ParseReport | Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV protocol. |
ImapFull | Full functionality of IMAP4/EWS/WebDAV including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption. |
VBScript, JScript\ParseEmail | Parse email file by JScript/VBScript. |
VBScript, JScript\PreviewEmail | Download email header with POP3/IMAP4/EWS/WebDAV server by JScript/VBScript. |
Simple | Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV) and Gmail/Office365/Hotmail OAUTH. |
ParseReport | Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV protocol. |
ImapFull | Full functionality of IMAP4/EWS/WebDAV including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption. |
Simple | Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV) and Gmail/Office365/Hotmail OAUTH. |
ParseReport | Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV protocol. |
ImapFull | Full functionality of IMAP4/EWS/WebDAV including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption. |
Free Email Support
Not enough? Please contact our technical support team.
Remarks
We usually reply emails within 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 Gmail, Hotmail/Offic 365 email account is recommended.
Appendix
Comments
If you have any comments or questions about above example codes, please click here to add your comments.