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

InstallationBefore 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# projectTo 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.

Add Reference of EAGetMail to Visual Stuido C#.NET ProjectTo 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.

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

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

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.

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.

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.

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.

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.

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.

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

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

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.

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

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.

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.

#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; }

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

UIDLManager ObjectWith 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 ServerWith 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.

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.

Retrieve emails in scheduleEAGetMail 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.

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.

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

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.

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

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.

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

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

Read ReceiptSome 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 FailureReportIt 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 ReportFor 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.

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

Add/Delete Mail FolderBecause 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.

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

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.

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?

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.