In previous section, I introduced how to convert email to HTML page. In this section, I will introduce how to parse Non-delivery report (NDR) in C#.
Sections:
Some e-mail applications, such as Microsoft Office Outlook, employ a read-receipt tracking mechanism. A sender selects the receipt request option prior to sending the message. Upon opening the email, each recipient has the option of notifying the sender that the message was opened and read.
However, there is no guarantee that you will get a read-receipt. Some possible reason are that very few e-mail applications or services support read receipts, or simply because users disable the functionality. Those do support read-receipt aren’t necessarily compatible with or capable of recognizing requests from a different e-mail service or application
It is also called a DSN (delivery service notification), which is a request to the recipient’s email server to send you a notification about the delivery of an email you’ve just sent. The notification takes the form of an email, and will tell you if your delivery succeeded (Delivery Receipt), failed, got delayed (Failure Report).
For many email campaign applications, the very important task is detecting if the email is received by recipient or not. Parsing the delivery report is the common way to get the email status. EAGetMail .NET class provides a built-in function (GetReport) to parse the report. The following sample demonstrates how to parse the delivery-report.
If ReporType is DeliveryReceipt
or ReadReceipt
, the report probably
has only OriginalSender, OriginalRecipient and OriginalMessageID information in
the report, it depends on the mail server that generated the report.
Note
Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.
The following example codes demonstrate how to parse delivery report.
Note
To get the full sample projects, please refer to Samples section.
using System;
using System.Text;
using System.IO;
using EAGetMail; // add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void ParseReport(string emlFile)
{
Mail oMail = new Mail("TryIt");
oMail.Load(emlFile, false);
if (!oMail.IsReport)
{
Console.WriteLine("This is not a delivery report.");
return;
}
MailReport oReport = oMail.GetReport();
switch (oReport.ReportType)
{
case DeliveryReportType.DeliveryReceipt:
Console.WriteLine("This is a delivery receipt!");
break;
case DeliveryReportType.ReadReceipt:
Console.WriteLine("This is a read receipt!");
break;
case DeliveryReportType.Deleted:
Console.WriteLine("This is a unread receipt, this email was deleted without read!");
break;
case DeliveryReportType.DelayedReport:
Console.WriteLine("This is a delayed report, server will retry to deliver it automatically!");
break;
default:
Console.WriteLine("This is a failure report!");
break;
}
Console.WriteLine("OriginalSender: {0}", oReport.OriginalSender);
Console.WriteLine("OriginalRecipient: {0}", oReport.OriginalRecipient);
Console.WriteLine("OriginalMessageID: {0}", oReport.OriginalMessageID);
if (oReport.ReportType == DeliveryReportType.FailureReport || oReport.ReportType == DeliveryReportType.DelayedReport)
{
Console.WriteLine("ErrCode: {0}", oReport.ErrCode);
Console.WriteLine("ErrDescription: {0}", oReport.ErrDescription);
Console.WriteLine("OriginalSubject: {0}", oReport.OriginalSubject);
Console.WriteLine("ReportMTA: {0}", oReport.ReportMTA);
Console.WriteLine(oReport.OriginalHeaders.ToString());
}
}
static void Main(string[] args)
{
try
{
ParseReport("c:\\my folder\\test.eml");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
To retrieve and parse Failure Report (NDR), you should monitor your sender mailbox. Here I will introduce how to use EAGetMail Service to monitor a mailbox and retrieve non-delivery report and insert it to SQL server on a regular basis.
To use EAGetMail Service, you need to download EAGetMail Service and install it on your machine at first.
Then create a table in your SQL database like this:
CREATE TABLE [dbo].[Failure_Report](
[reportid] [int] IDENTITY(1,1) NOT NULL,
[address] [nvarchar](255) NOT NULL,
[error_code] [nchar](10) NOT NULL,
[error_desc] [nchar](255) NOT NULL,
[error_datetime] [datetime] NOT NULL
) ON [PRIMARY]
GO
Create a C# console application named “parse_reports”, then
Input the following codes:
using System;
using System.Text;
using EAGetMail;
using System.IO;
using System.Data.SqlClient;
namespace parse_reports
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: Parse_Reports.exe [email folder path]\r\n");
Console.WriteLine("eg: Parse_Reports.exe \"c:\\my folder\"\r\n");
return;
}
try
{
// change it to your sql server address, database, user and password
// The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
// e.g.: Server=serveraddress\\instancename;
// open database connection
SqlConnection oConn = new SqlConnection("Server=localhost;Database=myDB;User Id=myUser;Password=myPassword;");
oConn.Open();
string[] files = Directory.GetFiles(args[0], "*.eml");
Console.WriteLine("Total {0} email(s)", files.Length);
int count = files.Length;
for (int i = 0; i < count; i++)
{
string fileName = files[i];
if (ParseEmail(fileName, oConn))
{
// Delete the local report file.
File.Delete(fileName);
}
}
oConn.Close();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
Console.WriteLine(ep.StackTrace);
}
}
static bool ParseEmail(string fileName, SqlConnection oConn)
{
Mail oMail = new Mail("TryIt");
oMail.Load(fileName, true);
// detect if this is a report or receipt
if (!oMail.IsReport)
{
Console.WriteLine("Not a report or receipt!");
return false;
}
MailReport oReport = oMail.GetReport();
// we only process failure report
if (oReport.ReportType != DeliveryReportType.FailureReport)
{
Console.WriteLine("Not a failure report!");
return false;
}
Console.WriteLine("OriginalRecipient: {0}", oReport.OriginalRecipient);
Console.WriteLine("ErrorCode: {0}", oReport.ErrCode);
Console.WriteLine("ErrorDesc: {0}", oReport.ErrDescription);
string errorDesc = oReport.ErrDescription;
if (errorDesc.Length > 250)
errorDesc = errorDesc.Substring(0, 250);
// INSERT the result to database.
string sql = "INSERT INTO [dbo].[Failure_Report] " +
" ([address] " +
" ,[error_code] " +
" ,[error_desc] " +
" ,[error_datetime]) " +
" VALUES ( @address, @error_code, @error_desc, GETDATE())";
SqlCommand command = new SqlCommand(sql, oConn);
command.Parameters.AddWithValue("@address", oReport.OriginalRecipient);
command.Parameters.AddWithValue("@error_code", oReport.ErrCode);
command.Parameters.AddWithValue("@error_desc", errorDesc);
command.ExecuteNonQuery();
command.Dispose();
return true;
}
}
}
Finally, open EAGetMail Service Manager -> Mail Pull Configuration -> New:
Input your sender mailbox account information
Create a folder named “inbox” on your machine, this folder is used to store .EML file.
Input the folder full path to “Save email file(s) to specified local folder:”;
Input application full path [SPACE] folder full path to: “Run specified application after download is finished”.
For example:
If your application full path is d:\parse_reports.exe
and your folder is d:\inbox
, then input:
"d:\parse_reports.exe" "d:\inbox"
With above setting, EAGetMail Service checks mailbox every 15 minutes and once there is non-delivery report, it will invoke parse_reports.exe to process non-delivery report and insert it to database like this:
Important
If you have “Leave a copy of message on mail server” unchecked, EAGetMail Service will delete all emails in your mailbox after the emails were retrieved to local folder. If your mailbox is only used to retrieve non-delivery report, then I recommend you have “Leave a copy of message on mail server” unchecked to get better performance.
You can run your application directly under DOS prompt without EAGetMail Service. If there is any error, you can debug and fix it.
"d:\parse_reports.exe" "d:\inbox"
EAGetMail Service is a common solution to process email on a regular basis, you can use above solution to download and process normal emails as well. You just need to change/extend the codes in parse_reports.exe
Common SQL Driver Download
If SQL Server is installed on a remote server, and you don’t have SQL driver installed on local machine, then you need to download and install corresponding driver on local machine.
Next Section
At next section I will introduce how to manage folders with IMAP4/Exchange Web Service (EWS)/WebDAV protocol.
Appendix
Comments
If you have any comments or questions about above example codes, please click here to add your comments.