Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Options
Go to last post Go to first unread
ivan  
#1 Posted : Tuesday, July 23, 2013 5:31:50 PM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email and Parse Email in C# - Tutorial

EAGetMail is an email component which supports all operations of POP3/IMAP4/MIME/Exchange Web Service/WebDAV/S/MIME/SSL protocol. This tutorial introduces how to read email in C# using POP3/IMAP4/EWS/WebDAV protocol and parse email body, attachment. It also demonstrates how to decrypt email and verify email digital signature (S/MIME) in C#.

read original tutorial

Tutorial Index:
Read email in a simple C# project using POP3
Read email from IMAP4 server
Read email over SSL connection
Read email from Gmail account
Read email from Yahoo account
Read email from Hotmail/MSN Live account
Read email with event handler
Using UIDL function to mark the email has been downloaded
Read email with background service
Parse email
Verify digital signature and decrypt email - S/MIME
Parse winmail.dat (TNEF)
Convert email to HTML page and display it using Web browser
Parse Non-delivery report (NDS)
Sample projects

Installation
Before you can use the following sample codes, you should download the EAGetMail Installer and install it on your machine at first.

Read email in a simple C# project
To better demonstrate how to read and parsing email, let's create a C# console project named "receiveemail" at first, and then add the reference of EAGetMail in your project.

read email in a simple c# project

Add Reference of EAGetMail to Visual Stuido C#.NET Project
To use EAGetMail in your project, the first step is "Add reference of EAGetMail to your project". Please create/open your project with Visual Studio.NET, then choose menu->"Project"->"Add Reference"->".NET"->"Browse...", and choose the EAGetMail{version}.dll from your disk, click "Open"->"OK", the reference of EAGetMail will be added to your project, and you can start to use EAGetMail POP3 & IMAP Component in your project.

Add EAGetMail reference in C#


Because EAGetMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.

Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0 and .Net Compact Framework 2.0, 3.5.

EAGetMail.dll
Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version.

EAGetMail20.dll
Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version.

EAGetMail35.dll
Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version.

EAGetMail40.dll
Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version.

EAGetMailCF20.dll
Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version.

EAGetMailCF35.dll
Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version.


[C# - Read email from POP3 server]
Now add the following codes to the project. The following code demonstrates how to read email from a POP3 mail account. This sample downloads emails from POP3 server and deletes the email after the email is retrieved.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");

// If your POP3 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 995;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Read email from POP3 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted from POP3 server.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}


If you set everything right, you can get emails in the mail folder. If the codes threw exception, then please have a look at the following section:

Where can I get my POP3 server address, user and password?

Because each email account provider has different server address, so you should query your POP3 server address from your email account provider. User name is your email address or your email address without domain part. It depends on your email provider setting.

When you execute above example code, if you get error about "Networking connection" or "No such host", it is likely that your POP3 server address is not correct. If you get an error like "Invalid user or password", it is likely that you did not set the correct user or password.

Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your POP3 server address, user in your email client. For example, you can choose menu -> "Tools" - > - "Accounts" - > "Your email account" - > "Properties" - > "Servers" in Outlook express or Windows Mail to get your POP3 server, user. Using EAGetMail to receive email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.

POP3 email setting

Edited by user Wednesday, July 24, 2013 1:54:27 AM(UTC)  | Reason: Not specified

ivan  
#2 Posted : Wednesday, July 24, 2013 12:52:55 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email from IMAP4 server in C#

In this section, I will introduce how to read email from IMAP4 server.

IMAP4 protocol is different with POP3 protocol. First of all, IMAP4 supports reading 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.


[C# - Read email from IMAP4 inbox]
The following example codes demonstrate how to read email from IMAP4 server default mailbox.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to store the email file retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");

// Set IMAP4 server port
oServer.Port = 143;

// If your IMAP4 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 993;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from IMAP4 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}


Because IMAP4 protocol supports folder access, so we can read email from other mailbox rather than default "INBOX". POP3 protocol doesn't support this feature.

[C# - Read email from "Deleted Items"]
The following example codes demonstrate how to read emails from "Deleted Items" in an IMAP4 account.


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static Imap4Folder SearchFolder(Imap4Folder[] folders, string name)
{
int count = folders.Length;
for (int i = 0; i < count; i++)
{
Imap4Folder folder = folders[i];
Console.WriteLine(folder.FullPath);
// Folder was found.
if (String.Compare(folder.Name, name) == 0)
return folder;

folder = SearchFolder(folder.SubFolders, name);
if (folder != null)
return folder;
}
// No folder found
return null;
}

static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to store the email file retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");

// Set IMAP4 server port
oServer.Port = 143;

// If your IMAP4 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 993;

try
{
oClient.Connect(oServer);

// Lookup folder based name.
Imap4Folder folder = SearchFolder(oClient.Imap4Folders, "Deleted Items");
if (folder == null)
{
throw new Exception("Folder was not found");
}

// Select this folder
oClient.SelectFolder(folder);

// Retrieve emails from selected folder instead of default folder.
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted from IMAP4 server.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from IMAP4 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#3 Posted : Wednesday, July 24, 2013 12:56:50 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email from Exchange Server using Web Service (EWS) in C#

In this section, I will introduce how to read email using Exchange Web Service (EWS) protocol (Exchange 2007/2010 or later version).

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 read email from Exchange Server, you can use Exchange Web Service (Exchange 2007/2010 or later version) or WebDAV (Exchange 2000/2003) protocol.

[C# - Read email from Exchange INBOX - EWS]
The following example codes demonstrate how to download email from Exchange 2007/2010/2013 server default mailbox.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to store the email file retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Please use domain\user as the user name
MailServer oServer = new MailServer("exch.emailarchitect.net",
"emailarchitect.net\\tester", "testpassword", ServerProtocol.ExchangeEWS );
MailClient oClient = new MailClient("TryIt");

// By default, Exchange Web Service (EWS) requires SSL connection
// Please ignore Port property for EWS and WebDAV protocol
oServer.SSLConnection = true;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from Exchange server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Delete email from IMAP4 server.
oClient.Delete(info);
}

// Quit from Exchange server.
oClient.Quit();
}
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.

[C# - Read email from "Deleted Items" - EWS]
The following example codes demonstrate how to read emails from "Deleted Items" in an Exchange account.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static Imap4Folder SearchFolder(Imap4Folder[] folders, string name)
{
int count = folders.Length;
for (int i = 0; i < count; i++)
{
Imap4Folder folder = folders[i];
Console.WriteLine(folder.FullPath);
// Folder was found.
if (String.Compare(folder.Name, name) == 0)
return folder;

folder = SearchFolder(folder.SubFolders, name);
if (folder != null)
return folder;
}
// No folder found
return null;
}

static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to store the email file retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Please use domain\user as the user name
MailServer oServer = new MailServer("exch.emailarchitect.net",
"emailarchitect.net\\tester", "testpassword", ServerProtocol.ExchangeEWS );
MailClient oClient = new MailClient("TryIt");

// By default, Exchange Web Service (EWS) requires SSL connection
// Please ignore Port property for EWS and WebDAV protocol
oServer.SSLConnection = true;

try
{
oClient.Connect(oServer);

// Lookup folder based name.
Imap4Folder folder = SearchFolder(oClient.Imap4Folders, "Deleted Items");
if (folder == null)
{
throw new Exception("Folder was not found");
}

// Select this folder
oClient.SelectFolder(folder);

// Retrieve emails from selected folder instead of default folder.
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from Exchange server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Delete email from Exchange server.
oClient.Delete(info);
}

// Quit from Exchange server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#4 Posted : Wednesday, July 24, 2013 1:03:38 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email from Exchange Server using WebDAV protocol in C#

In this section, I will introduce how to read email using WebDAV protocol (Exchange 2000/2003).

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.

[C# - Read email from Exchange Inbox - WebDAV]
The following example codes demonstrate how to read email from Exchange server default mailbox.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to store the email file retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Please use domain\user as the user name.
MailServer oServer = new MailServer("exch.emailarchitect.net",
"emailarchitect.net\\test", "testpassword", ServerProtocol.ExchangeWebDAV );
MailClient oClient = new MailClient("TryIt");


// If your Exchange WebDAV server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;


try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from Exchange server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Delete email from Exchange server.
oClient.Delete(info);
}

// Quit from Exchange server.
oClient.Quit();
}
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.

[C# - Read email from "Deleted Items" - WebDAV]
The following example codes demonstrate how to read emails from "Deleted Items" in an Exchange account.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static Imap4Folder SearchFolder(Imap4Folder[] folders, string name)
{
int count = folders.Length;
for (int i = 0; i < count; i++)
{
Imap4Folder folder = folders[i];
Console.WriteLine(folder.FullPath);
// Folder was found.
if (String.Compare(folder.Name, name) == 0)
return folder;

folder = SearchFolder(folder.SubFolders, name);
if (folder != null)
return folder;
}
// No folder found
return null;
}

static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to store the email file retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Please use domain\user as the user name.
MailServer oServer = new MailServer("exch.emailarchitect.net",
"emailarchitect.net\\test", "testpassword", ServerProtocol.ExchangeWebDAV );
MailClient oClient = new MailClient("TryIt");

// If your Exchange WebDAV server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;

try
{
oClient.Connect(oServer);

// Lookup folder based name.
Imap4Folder folder = SearchFolder(oClient.Imap4Folders, "Deleted Items");
if (folder == null)
{
throw new Exception("Folder was not found");
}

// Select this folder
oClient.SelectFolder(folder);

// Retrieve emails from selected folder instead of default folder.
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from Exchange server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Delete email from Exchange server.
oClient.Delete(info);
}

// Quit from Exchange server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#5 Posted : Wednesday, July 24, 2013 1:06:45 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email over SSL connection in C#

In this section, I will introduce how to retrieve email over SSL connection in C#.

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:

1. Using STARTTLS or TLS command to switch SSL channel on normal port (POP3: 110 or IMAP4: 143);
2. Deploying SSL on another port (POP3: 995 or IMAP4: 993 you may query it from your server administrator) directly.


EAGetMail POP3 component supports both ways. Please see the following example code.

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.

[C# - SSL/TLS Setting - POP3/IMAP4/EWS/WebDAV]

// 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);



[C# - Read email from POP3 server over SSL on 995 port]
The following example codes demonstrate how to read emails from POP3 server over SSL connection on 995 port.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");

// Enable SSL connection.
oServer.SSLConnection = true;

// Set 995 SSL port
oServer.Port = 995;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from POP3 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted from POP3 server.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#6 Posted : Wednesday, July 24, 2013 1:08:58 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email from Gmail account in C#

In this section, I will introduce how to read email from your Gmail account in C#.

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. For example: your email is "gmailid@gmail.com", and then the user name should be "gmailid@gmail.com".

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 read 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.

[C# - Read email from Gmail account using IMAP4 protocol]
The following example codes demonstrate how to read email from Gmail account.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Gmail IMAP4 server is "imap.gmail.com"
MailServer oServer = new MailServer("imap.gmail.com",
"gmailid@gmail.com", "yourpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");

// Set SSL connection,
oServer.SSLConnection = true;

// Set 993 IMAP4 port
oServer.Port = 993;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Download email from GMail IMAP4 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted in GMail account.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from Gmail IMAP4 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#7 Posted : Wednesday, July 24, 2013 1:10:45 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email from Yahoo account in C#

In this section, I will introduce how to read emails from your Yahoo account in C#.

Yahoo POP3 server address is "pop.mail.yahoo.com" or "plus.pop.mail.yahoo.com". It requires SSL connection on 995 port, and 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".


[C# - Read emails from Yahoo account]
The following example codes demonstrate how to read emails from Yahoo account.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Yahoo POP3 server is "pop.mail.yahoo.com"
MailServer oServer = new MailServer("pop.mail.yahoo.com",
"myid@yahoo.com", "yourpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");

// Set SSL connection
oServer.SSLConnection = true;

// Set 995 SSL port
oServer.Port = 995;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Download email from Yahoo POP3 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted in Yahoo account.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from Yahoo POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#8 Posted : Wednesday, July 24, 2013 1:12:53 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email from Hotmail/Live account in C#

I will introduce how to read email from Hotmail/Live account in C#.

Hotmail/MSN Live POP3 server address is "pop3.live.com". It requires SSL connection on 995 port, and you should use your Hotmail/MSN 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".

[C# - Read emails from Hotmail/Live account]
The following example codes demonstrate how to read email from Hotmail/Live account.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Hotmail/MSN POP3 server is "pop3.live.com"
MailServer oServer = new MailServer("pop3.live.com",
"liveid@hotmail.com", "yourpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");

// Set SSL connection
oServer.SSLConnection = true;

// Set 995 SSL port
oServer.Port = 995;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Download email from Hotmail/MSN POP3 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted in Hotmail/MSN Live account.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from Hotmail/MSN Live server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#9 Posted : Wednesday, July 24, 2013 1:14:48 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email with Event Handler in C#

In this section, I will introduce how to read 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.


[C# - Read email with event handler]
The following example codes demonstrate how to read email with event handler.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
private static void OnConnected(object sender, ref bool cancel)
{
Console.WriteLine("Connected");
}

private static void OnQuit(object sender, ref bool cancel)
{
Console.WriteLine( "Quit");
}

private static void OnReceivingDataStream(object sender,
MailInfo info, int received, int total, ref bool cancel)
{
Console.WriteLine(String.Format("Receiving {0}, {1}/{2}...", info.Index,
received, total));
}

private static void OnIdle(object sender, ref bool cancel)
{

}

private static void OnAuthorized(object sender, ref bool cancel)
{
Console.WriteLine("Authorized");

}

private static void OnSecuring(object sender, ref bool cancel)
{
Console.WriteLine("Securing");
}

static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");

// If your POP3 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 995;

// Catching the following events is not necessary,
// just make the application more user friendly.
// If you use the object in asp.net/windows service or non-gui application,
// You need not to catch the following events.
oClient.OnAuthorized += new MailClient.OnAuthorizedEventHandler( OnAuthorized );
oClient.OnConnected += new MailClient.OnConnectedEventHandler( OnConnected );
oClient.OnIdle += new MailClient.OnIdleEventHandler( OnIdle );
oClient.OnSecuring += new MailClient.OnSecuringEventHandler( OnSecuring );
oClient.OnReceivingDataStream +=
new MailClient.OnReceivingDataStreamEventHandler( OnReceivingDataStream );

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Receive email from POP3 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Mark email as deleted from POP3 server.
oClient.Delete(info);
}

// Quit and pure emails marked as deleted from POP3 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}
ivan  
#10 Posted : Wednesday, July 24, 2013 1:18:42 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Mark the Email has been downloaded/read in C#

n this section, I will introduce how to use UIDL function to mark the email has been downloaded in C#.

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.


[C# - IMAP4 Solution]
Every email has a unique identifier (UIDL) on IMAP4 server. It is a 32bit integer and it is always unique in your email account life time. So we can use the integer as file name to identify if the email has been downloaded.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");

// Set IMAP4 server port
oServer.Port = 143;

// If your IMAP4 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 993;

try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);

// Using IMAP UIDL as the file name.
string fileName = String.Format("{0}\\{1}.eml",
mailbox, info.UIDL );

if( File.Exists( fileName ))
{

// This email has been downloaded, do not download it again.
continue;
}

// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);

Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

// Save email to local disk
oMail.SaveAs(fileName, true);

// Do not delete email from IMAP4 server.
}

// Quit
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}


POP3/IMAP4/Exchange Web Service/WebDAV Solution

There is a little bit different in POP3 server. The UIDL is only unique in the email life time. That means if the email was deleted from the server, other email can use the old unique identifier. Another problem is: UIDL in POP3 server can be any number or characters, so we cannot use UIDL as the file name, because UIDL may contain invalid characters for file name.

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 both POP3/IMAP4/Exchange Web Service/WebDAV protocol.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class MyMailClient
{
private string m_uidlfile = "uidl.txt";
private string m_curpath = "";
private ArrayList m_arUidl = new ArrayList();

#region UIDL Functions
// uidl is the identifier of every email on POP3/IMAP4 server, to
// avoid retrieve the same email from server more than once, we
// record the email uidl retrieved every time if you delete the
// email from server every time and not to leave a copy of email on
// the server, then please remove all the function about uidl.
private bool _FindUIDL(MailInfo[] infos, string uidl)
{
int count = infos.Length;
for (int i = 0; i < count; i++)
{
if (String.Compare(infos[i].UIDL, uidl, false) == 0)
return true;
}
return false;
}

// Remove the local uidl which is not existed on the server.
private void _SyncUIDL(MailServer oServer, MailInfo[] infos)
{
string s = String.Format("{0}#{1} ", oServer.Server, oServer.User);

bool bcontinue = false;
int n = 0;
do
{
bcontinue = false;
int count = m_arUidl.Count;
for (int i = n; i < count; i++)
{
string x = m_arUidl[i] as string;
if (String.Compare(s, 0, x, 0, s.Length, true) == 0)
{
int pos = x.LastIndexOf(' ');
if (pos != -1)
{
string uidl = x.Substring(pos + 1);
if (!_FindUIDL(infos, uidl))
{
// This uidl doesn't exist on server,
// remove it from local uidl list to save the storage.
bcontinue = true;
n = i;
m_arUidl.RemoveAt(i);
break;
}
}
}
}
} while (bcontinue);

}

private bool _FindExistedUIDL(MailServer oServer, string uidl)
{
string s = String.Format("{0}#{1} {2}", oServer.Server.ToLower(),
oServer.User.ToLower(), uidl);
int count = m_arUidl.Count;
for (int i = 0; i < count; i++)
{
string x = m_arUidl[i] as string;
if (String.Compare(s, x, false) == 0)
return true;
}
return false;
}

private void _AddUIDL(MailServer oServer, string uidl)
{
string s = String.Format("{0}#{1} {2}", oServer.Server.ToLower(),
oServer.User.ToLower(), uidl);
m_arUidl.Add(s);
}

private void _UpdateUIDL()
{
StringBuilder s = new StringBuilder();
int count = m_arUidl.Count;
for (int i = 0; i < count; i++)
{
s.Append(m_arUidl[i] as string);
s.Append("\r\n");
}

string file = String.Format("{0}\\{1}", m_curpath, m_uidlfile);

FileStream fs = null;
try
{
fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
byte[] data = System.Text.Encoding.Default.GetBytes(s.ToString());
fs.Write(data, 0, data.Length);
fs.Close();
}
catch (Exception ep)
{
if (fs != null)
fs.Close();

throw ep;
}

}

private void _LoadUIDL()
{
m_arUidl.Clear();
string file = String.Format("{0}\\{1}", m_curpath, m_uidlfile);
StreamReader read = null;
try
{
read = File.OpenText(file);
while (true)
{
string line = read.ReadLine().Trim("\r\n \t".ToCharArray());
m_arUidl.Add(line);
}
}
catch (Exception ep)
{ }

if (read != null)
read.Close();
}
#endregion

public void ReceiveEmail(MailServer oServer, bool bLeaveCopy )
{
MailClient oClient = new MailClient("TryIt");
m_curpath = Directory.GetCurrentDirectory();
try
{

// Uidl is the identifier of every email on POP3/IMAP4 server, to
// avoid retrieve the same email from server more than once,
// we record the email uidl retrieved every time if you delete the
// email from server every time and not to leave a copy of email on
// the server, then please remove all the function about uidl.
_LoadUIDL();

string mailFolder = String.Format("{0}\\inbox", m_curpath);
if (!Directory.Exists(mailFolder))
Directory.CreateDirectory(mailFolder);

Console.WriteLine("Connecting server ... ");
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine( "Total {0} email(s)", infos.Length);

_SyncUIDL(oServer, infos);
int count = infos.Length;

for (int i = 0; i < count; i++)
{
MailInfo info = infos[i];
if (_FindExistedUIDL(oServer, info.UIDL))
{

// This email has existed on local disk.
continue;
}

Console.WriteLine("Retrieving {0}/{1}...", info.Index, count);

Mail oMail = oClient.GetMail(info);
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur =
new System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailFolder, sdate, d.Millisecond.ToString("d3"), i);
oMail.SaveAs(fileName, true);

if (bLeaveCopy)
{

// Add the email uidl to uidl file to avoid we retrieve it next time.
_AddUIDL(oServer, info.UIDL);
}
}

if (!bLeaveCopy)
{
Console.WriteLine( "Deleting ..." );
for (int i = 0; i < count; i++)
oClient.Delete(infos[i]);
}

Console.WriteLine("Completed");
// Delete method just mark the email as deleted,
// Quit method pure the emails from server exactly.
oClient.Quit();

}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

// Update the uidl list to a text file and then we can load it next time.
_UpdateUIDL();
}
}
class Program
{
static void Main(string[] args)
{
MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );


MyMailClient oMyClient = new MyMailClient();
// Leave a copy of email on server
oMyClient.ReceiveEmail(oServer, true);
}
}
}


UIDLManager Object
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.

Mark Email as Read on IMAP4/Exchange Server
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.
ivan  
#11 Posted : Wednesday, July 24, 2013 1:21:18 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read Email with Background Service in C#

In this section, I will introduce how to read email with background service in C#.

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.

To run the following example, you also need to download EAGetMail Service and install it on your machine.


[C# - Read email with background service]
The following example codes demonstrate how to read email with background service.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

MailServer oServer = new MailServer("pop3.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );
MailClient oClient = new MailClient("TryIt");

// If your POP3 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 995;

try
{
// Leave a copy of message on server.
bool leaveCopy = true;

// Download emails to this local folder
string downloadFolder = mailbox;

// 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);
}

}
}
}


Retrieve emails in schedule
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 in schedule, 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.
ivan  
#12 Posted : Wednesday, July 24, 2013 1:23:25 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Parse Email (Recipients, Body, Attachments) in C#

In this section, I will introduce how to parse email in C#.

After you received the emails to the local folder, we can use the following code to parse the email now. The following code demonstrates how to parse from, to, cc, subject, body text, attachments of all emails file received by previous sample.


[C# - Parse email]
The following example codes demonstrate how to parse email sender, to, cc, subject, body text and attachments.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
private static void ParseEmail(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);

// Parse Mail From, Sender
Console.WriteLine("From: {0}", oMail.From.ToString());

// Parse Mail To, Recipient
MailAddress[] addrs = oMail.To;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}

// Parse Mail CC
addrs = oMail.Cc;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}

// Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject);

// Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody);

// Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody );

// Parse Attachments
Attachment[] atts = oMail.Attachments;
for (int i = 0; i < atts.Length; i++)
{
Console.WriteLine("Attachment: {0}", atts[i].Name);
}
}

static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseEmail(files[i]);
}
}
}
}

TextBody and HtmlBody

Not every email has both text/plain body text and html body text. However, Mail object provides both TextBody and HtmlBody properties smartly. If the email has only text/plain body, then Mail object converts the text/plain body to html body automatically; if the email has only html body, then Mail object converts the html body to text/plain body automatically.
ivan  
#13 Posted : Wednesday, July 24, 2013 1:25:37 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Verify Digital Signature and Decrypt Email in C# - S/MIME

In this section, I will introduce how to verify digital signature and decrypt email in C#.

Digital signature prevents email content is faked or changed in transport level. Encrypting email protects email content from exposure to inappropriate recipients. Both digital signature and email encrypting depend on digital certificate.

How to sign email content?

Digital signature is always signed by sender certificate. The certificate used to sign email content MUST have the public/private key pair. First of all, the user MUST get a digital certificate for personal email protection from third-party certificate authorities such as www.verisign.com. After the certificate is installed on the machine, it can be viewed by "Control Panel"->"Internet Options"->"Content"->"Certificates"->"Personal". When you view the certificate, please note there is a line "You have a private key that corresponds to this certificate" in the certificate view, that means you are able to use this certificate to sign email content. If this line doesn't appear, that means you are unable to sign the email content by this certificate. To sign email content, please refer to EASendMail SMTP Component.

How to encrypt email?

Encrypting email doesn't require sender certificate but the certificate with public key for every recipient. For example, from@adminsystem.com sends an email to rcpt@adminsystem.com with digital signature. The digital signature contains the public key certificate for from@adminsystem.com, then rcpt@adminsystem.com can send an encrypted email with this certificate back to from@adminsystem.com. Only from@adminsystem can read this email, because this email MUST be decrypted by private key of from@adminsystem.com. Therefore, you MUST receive an digital signed email from other people (Most email clients such as outlook, outlook express will add the certificate to the Other People Storage automatically once an digital signed email is received) before you can send encrypted email to this people. To encrypt email, please refer to EASendMail SMTP Component.

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.


[C# - Verify digital signature and decrypt email]
The following example codes demonstrate how to verify digital signature and decrypt email in C#.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
private static void ParseEmail(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);

if (oMail.IsEncrypted)
{
try
{
// This email is encrypted, we decrypt it by user default certificate.
// You can also use specified certificate like this
// Certificate oCert = new Certificate();
// oCert.Load("c:\test.pfx", "pfxpassword",
// Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET);
// oMail = oMail.Decrypt( oCert );
oMail = oMail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}

if (oMail.IsSigned)
{
try
{
// This email is digital signed.
EAGetMail.Certificate cert = oMail.VerifySignature();
Console.WriteLine("This email contains a valid digital signature.");

// You can add the certificate to your certificate storage like this
// cert.AddToStore(
// Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
// "addressbook" );
// Then you can use send the encrypted email back to this sender.
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}

// Parse Sender
Console.WriteLine("From: {0}", oMail.From.ToString());

// Parse To/Recipient
MailAddress[] addrs = oMail.To;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}

// Parse CC
addrs = oMail.Cc;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}

// Parse subject
Console.WriteLine("Subject: {0}", oMail.Subject);

// Parse Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody);

// Parse HTML body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody );

// Parse attachments
Attachment[] atts = oMail.Attachments;
for (int i = 0; i < atts.Length; i++)
{
Console.WriteLine("Attachment: {0}", atts[i].Name);
}
}

static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseEmail(files[i]);
}
}
}
}
ivan  
#14 Posted : Wednesday, July 24, 2013 1:26:58 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Read/Parse winmail.dat (TNEF/MAPI) in C#

In this section, I will introduce how to parse winmail.dat (TNEF stream) in C#.

When an Outlook user composes and sends a message using either Rich Text Format or HTML Format, Outlook automagically generates a file, winmail.dat, and attaches it to the end of the email. The winmail.dat contains the rich text body and original attachments. To parse winmail.dat (TNEF stream) file, we should use ParseTNEF method.


[C# - Parse winmail.dat (TNEF stream)]
The following example codes demonstrate how to parse MAPI winmail.dat.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
private static void ParseEmail(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);

if (oMail.IsEncrypted)
{
try
{
// This email is encrypted, we decrypt it by user default certificate.
// you can also use specified certificate like this
// Certificate oCert = new Certificate();
// oCert.Load("c:\test.pfx", "pfxpassword",
// Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET);
// oMail = oMail.Decrypt( oCert );
oMail = oMail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}

if (oMail.IsSigned)
{
try
{
// This email is digital signed.
EAGetMail.Certificate cert = oMail.VerifySignature();
Console.WriteLine("This email contains a valid digital signature.");

// You can add the certificate to your certificate storage like this
// cert.AddToStore(
// Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
// "addressbook" );
// then you can use send the encrypted email back to this sender.
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}

// Parse sender
Console.WriteLine("From: {0}", oMail.From.ToString());

// Parse to recipient
MailAddress[] addrs = oMail.To;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}

// Parse cc
addrs = oMail.Cc;
for (int i = 0; i < addrs.Length; i++)
{
Console.WriteLine("To: {0}", addrs[i].ToString());
}

// Parse subject
Console.WriteLine("Subject: {0}", oMail.Subject);

// Parse Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody);

// Parse Html body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody );

// Parse attachments
Attachment[] atts = oMail.Attachments;
for (int i = 0; i < atts.Length; i++)
{
Attachment att = atts[i];

// This attachment is in OUTLOOK RTF format(TNEF stream), decode it here.
if (String.Compare(att.Name, "winmail.dat") == 0)
{
Attachment[] tatts = null;
try
{
tatts = Mail.ParseTNEF(att.Content, true);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
continue;
}
int y = tatts.Length;
for (int x = 0; x < y; x++)
{
Attachment tatt = tatts[x];
Console.WriteLine("winmail.dat: {0}", tatt.Name);
}
continue;
}
Console.WriteLine("Attachment: {0}", att.Name);
}
}

static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseEmail(files[i]);
}
}
}
}
ivan  
#15 Posted : Wednesday, July 24, 2013 1:29:29 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Convert Email to HTML page and Display it using Web Browser in C#
In this section, I will introduce how to 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.

[C# - Convert email to HTML]
The following example codes demonstrate how to convert email to HTML page.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
class Program
{
private static void ConvertMailToHtml(string fileName)
{
try
{
int pos = fileName.LastIndexOf(".");
string mainName = fileName.Substring(0, pos);
string htmlName = mainName + ".htm";

string tempFolder = mainName;
if (!File.Exists(htmlName))
{
// We haven't generate the html for this email, generate it now.
_GenerateHtmlForEmail(htmlName, fileName, tempFolder);
}

Console.WriteLine("Please open {0} to browse your email",
htmlName);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}

private static string _FormatHtmlTag(string src)
{
src = src.Replace(">", "&gt;");
src = src.Replace("<", "&lt;");
return src;
}

// We generate a html + attachment folder for every email, once the html is create,
// next time we don't need to parse the email again.
private static void _GenerateHtmlForEmail(string htmlName, string emlFile,
string tempFolder)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);

if (oMail.IsEncrypted)
{
try
{
// This email is encrypted, we decrypt it by user default certificate.
oMail = oMail.Decrypt(null);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
oMail.Load(emlFile, false);
}
}

if (oMail.IsSigned)
{
try
{
// This email is digital signed.
EAGetMail.Certificate cert = oMail.VerifySignature();
Console.WriteLine("This email contains a valid digital signature.");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}

// Parse html body
string html = oMail.HtmlBody;
StringBuilder hdr = new StringBuilder();

// Parse sender
hdr.Append("<font face=\"Courier New,Arial\" size=2>");
hdr.Append("<b>From:</b> " + _FormatHtmlTag(oMail.From.ToString()) + "<br>");

// Parse to
MailAddress[] addrs = oMail.To;
int count = addrs.Length;
if (count > 0)
{
hdr.Append("<b>To:</b> ");
for (int i = 0; i < count; i++)
{
hdr.Append(_FormatHtmlTag(addrs[i].ToString()));
if (i < count - 1)
{
hdr.Append(";");
}
}
hdr.Append("<br>");
}

// Parse cc
addrs = oMail.Cc;

count = addrs.Length;
if (count > 0)
{
hdr.Append("<b>Cc:</b> ");
for (int i = 0; i < count; i++)
{
hdr.Append(_FormatHtmlTag(addrs[i].ToString()));
if (i < count - 1)
{
hdr.Append(";");
}
}
hdr.Append("<br>");
}

hdr.Append(String.Format("<b>Subject:</b>{0}<br>\r\n",
_FormatHtmlTag(oMail.Subject)));

// Parse attachments and save to local folder
Attachment[] atts = oMail.Attachments;
count = atts.Length;
if (count > 0)
{
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);

hdr.Append("<b>Attachments:</b>");
for (int i = 0; i < count; i++)
{
Attachment att = atts[i];

// this attachment is in OUTLOOK RTF format, decode it here.
if (String.Compare(att.Name, "winmail.dat") == 0)
{
Attachment[] tatts = null;
try
{
tatts = Mail.ParseTNEF(att.Content, true);
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
continue;
}

int y = tatts.Length;
for (int x = 0; x < y; x++)
{
Attachment tatt = tatts[x];
string tattname = String.Format("{0}\\{1}", tempFolder, tatt.Name);
tatt.SaveAs(tattname, true);
hdr.Append(
String.Format("<a href=\"{0}\" target=\"_blank\">{1}</a> ",
tattname, tatt.Name));
}
continue;
}

string attname = String.Format("{0}\\{1}", tempFolder, att.Name);
att.SaveAs(attname, true);
hdr.Append(String.Format("<a href=\"{0}\" target=\"_blank\">{1}</a> ",
attname, att.Name));
if (att.ContentID.Length > 0)
{

// Show embedded images.
html = html.Replace("cid:" + att.ContentID, attname);
}
else if (String.Compare(att.ContentType, 0, "image/", 0,
"image/".Length, true) == 0)
{

// show attached images.
html = html + String.Format("<hr><img src=\"{0}\">", attname);
}
}
}

Regex reg = new Regex("(<meta[^>]*charset[ \t]*=[ \t\"]*)([^<> \r\n\"]*)",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
html = reg.Replace(html, "$1utf-8");
if (!reg.IsMatch(html))
{
hdr.Insert(0,
"<meta HTTP-EQUIV=\"Content-Type\" Content=\"text-html; charset=utf-8\">");
}

// write html to file
html = hdr.ToString() + "<hr>" + html;
FileStream fs = new FileStream(htmlName, FileMode.Create,
FileAccess.Write, FileShare.None);

byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(html);
fs.Write(data, 0, data.Length);
fs.Close();
oMail.Clear();
}


static void Main(string[] args)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);


// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
// Convert all emails received to html page
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ConvertMailToHtml(files[i]);
}
}
}
}

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

read email and parse email in c#
ivan  
#16 Posted : Wednesday, July 24, 2013 1:31:27 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Parse Non-Delivery Report (NDS) in C#

In this section, I will introduce how to parse Non-delivery report (NDS) in C#.

Read Receipt
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

Delivery Receipt and FailureReport
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).

Parse 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.


[C# Example - Parse delivery report]
The following example codes demonstrate how to parse delivery report.

using System;
using System.Collections;
using System.Collections.Generic;
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;
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 )
{
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)
{
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);

// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}

// Get all *.eml files in specified folder and parse it one by one.
string[] files = Directory.GetFiles(mailbox, "*.eml");
for (int i = 0; i < files.Length; i++)
{
ParseReport(files[i]);
}
}
}
}
ivan  
#17 Posted : Wednesday, July 24, 2013 1:34:18 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Manage Folder using IMAP4/Exchange Web Service/WebDAV protocol in C#

In this section, I will introduce how to manage folders with IMAP4/Exchange Web Service/WebDAV protocol in C#.

Add/Delete Mail Folder
Because IMAP4/Exchange Web Service/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 add/delete folder with IMAP4/Exchange WebService/WebDAV protocol. Notice: POP3 protocol doesn't support this feature.

[C# - Add/Delete Folder - IMAP4/EWS/WebDAV]
The following example codes demonstrate how to add/delete folder.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace

namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// 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/2010 or
// later version) or WebDAV (Exchange 2000/2003) protocol.

// For Exchange Web Service/WebDAV protocol, please ignore port property
// and use domain\user as the user name.
MailServer oServer = new MailServer("imap4.emailarchitect.net",
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");

// Set IMAP4 server port
oServer.Port = 143;

// If your IMAP4 server requires SSL connection,
// Please add the following codes:
// oServer.SSLConnection = true;
// oServer.Port = 993;

try
{
oClient.Connect(oServer);
Imap4Folder folder = oClient.CreateFolder( null, "TestFolder" );

Imap4Folder [] folders = oClient.Imap4Folders;
int count = folders.Length;
for( int i = 0; i < count; i++ )
{
Imap4Folder fd = folders[i];
Console.WriteLine( "folder: {0}", fd.FullPath );
}

oClient.DeleteFolder( folder );
oClient.Logout();

oClient.Logout();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}

}
}
}


Copy/Move/Upload Email to Folder

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.
ivan  
#18 Posted : Wednesday, July 24, 2013 1:36:36 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
C# - Read email using POP3/IMAP4/Exchange Web Service/WebDAV - Sample Projects

After you downloaded the EAGetMail Component Installer and install it on your machine, there are many samples in the installation path.

Sample List
ivan  
#19 Posted : Wednesday, July 24, 2013 1:37:17 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
The end

any questions, comments are welcome.
Thanos  
#20 Posted : Wednesday, October 14, 2015 5:34:02 AM(UTC)
Thanos

Rank: Newbie

Groups: Registered
Joined: 10/14/2015(UTC)
Posts: 1

I have a question about getting the emails with eagetmail.
I want to get the emails from outlook but I do not want to delete the original ones from the outlook.
I saw how this can be done.
My question is that the next time that I will run the program I would like to get only the emails that has not been downloaded from previous time.
It is tricky because Outlook can be used individually so I do not have to handle only the unread ones but also some emails that are marked as read because the have been seen through outlook.
Is it possible to be down something like that?
ivan  
#21 Posted : Wednesday, October 14, 2015 6:07:29 AM(UTC)
ivan

Rank: Administration

Groups: Administrators
Joined: 11/11/2010(UTC)
Posts: 1,152

Thanks: 9 times
Was thanked: 55 time(s) in 55 post(s)
Hi, please have a look at this topic:

https://www.emailarchite...ail/kb/csharp.aspx?cat=9

You can use UIDL to mark the email as downloaded.
Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Powered by YAF.NET | YAF.NET © 2003-2024, Yet Another Forum.NET
This page was generated in 1.413 seconds.

EXPLORE TUTORIALS

© All Rights Reserved, AIFEI Software Limited & AdminSystem Software Limited.