Mail Class


Provides properties and methods for presenting an e-mail message.

System.Object
    EAGetMail.Mail

[Visual Basic]
Public Class Mail
[C#]
public class Mail
[C++]
public ref class Mail
[JScript]
public class Mail

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Public Constructors

Mail Constructor Initializes a new instance of the Mail class.

Public Properties

Attachments Gets an array of the attachments of the email message.
BodyHeaders Gets the headers of the body part.
Cc Gets an array of e-mail addresses that receive a carbon copy (CC) of the e-mail message.
Content Gets the content of the email message.
From Gets the e-mail address of the sender.
Headers Gets the HeaderCollection for headers of the e-mail message.
HtmlBody Gets the html body of the e-mail message.
IsEncrypted Gets whether the email is encrypted by digital certificate.
IsReport Gets whether the email is a delivery report.
IsSigned Gets whether the email has a digital signature.
OriginalBodyFormat Gets the body text format of the e-mail message.
Priority Gets the priority of the e-mail message.
ReceivedDate Gets the date time when the server received this email.
ReplyTo Gets the email address to reply this email.
SentDate Gets the date time when the sender sent this email.
Subject Gets the subject of the e-mail message.
Tag Gets or sets an object that contains data to associate with the Mail.
TextBody Gets the text body of the e-mail message.
To Gets an array of recipient e-mail addresses.

Public Methods

Clear Clears all data in Mail class.
DecodeTNEF Parses the winmail.dat (TNEF attachment) automatically in current mail instance.
Decrypt Decrypts the encrypted email by digital certificate. This method is obsoleted, use DecryptMessage method instead.
DecryptMessage Decrypts the encrypted email by digital certificate.
GetReport Gets detailed information of a delivery report.
Load Loads a RFC822 message (*.eml) file or binary email content to current Mail instance.
LoadOMSG Loads a Outlook MSG (*.msg) file or binary email content to current Mail instance.
ParseTNEF Parses the winmail.dat (TNEF attachment).
SaveAs Saves the e-mail message to a file (*.eml file).
SaveAsOMSG Saves the e-mail message to a Outlook MSG file (*.msg file).
VerifySignature Verifies the digital signature of the email. This method is obsoleted, use VerifyMessageSignature method instead.
VerifyMessageSignature Verifies the digital signature of the email.

Example

[Visual Basic, C#, C++] The following example demonstrates how to parse email with EAGetMail POP3 & IMAP4 Component. To get the full samples of EAGetMail, please refer to Samples section.

[Visual Basic - Parse Email]

Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports EAGetMail

Private Function _FormatHtmlTag(ByVal src As String) As String
    src = src.Replace(">", ">")
    src = src.Replace("<", "&lt;")
    _FormatHtmlTag = src
End Function

' we parse the email file and generate a html + attachment folder for the email, once the html is create,
' you can open this html with IE and view the content and get the attachments.
Public Sub ParseEmailToHtml(ByVal emlFile As String)
     'if the email is c:\test.eml, then we will generate the c:\test.htm to
     'display the body text and save the attachments to c:\test folder
     Dim pos As Integer = emlFile.LastIndexOf(".")
     Dim mainName As String = emlFile.Substring(0, pos)
     Dim htmlName As String = mainName + ".htm"
     Dim tempFolder As String = mainName

    ' For evaluation usage, please use "TryIt" as the license code, otherwise the 
    ' "invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
    ' "trial version expired" exception will be thrown.
    Dim oMail As New Mail("TryIt")
    oMail.Load(emlFile, False)

    If (oMail.IsEncrypted) Then
        Try
            'this email is encrypted, we decrypt it by user default certificate.
            ' you can also use specified certificate like this
            ' Dim oCert As new Certificate()
            ' oCert.Load("c:\test.pfx", "pfxpassword", Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
            ' oMail = oMail.Decrypt(oCert)
            oMail = oMail.Decrypt(Nothing)
        Catch ep As Exception
            MessageBox.Show(ep.Message)
            oMail.Load(emlFile, False)
        End Try
    End If

    If (oMail.IsSigned) Then
        Try
            'this email is digital signed.
            Dim cert As EAGetMail.Certificate = oMail.VerifySignature()
            MessageBox.Show("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 ep As Exception
            MessageBox.Show(ep.Message)
        End Try
    End If

    ' Parse from, to, cc, body and attachments.
    ' Decode winmail.dat (TNEF) automatically
    ' also convert RTF body to HTML body automatically
    oMail.DecodeTNEF()

    Dim html As String = oMail.HtmlBody
    Dim hdr As New StringBuilder
    hdr.Append("<font face=""Courier New,Arial"" size=2>")
    hdr.Append("<b>From:</b> " + _FormatHtmlTag(oMail.From.ToString()) + "<br>")

    Dim addrs() As MailAddress = oMail.To
    Dim count As Integer = addrs.Length
    If (count > 0) Then
        hdr.Append("<b>To:</b> ")
        For i As Integer = 0 To count - 1
            hdr.Append(_FormatHtmlTag(addrs(i).ToString()))
            If (i < count - 1) Then
                hdr.Append(";")
            End If
        Next
        hdr.Append("<br>")
    End If

    addrs = oMail.Cc
    count = addrs.Length
    If (count > 0) Then
        hdr.Append("<b>Cc:</b> ")
        For i As Integer = 0 To count - 1
            hdr.Append(_FormatHtmlTag(addrs(i).ToString()))
            If (i < count - 1) Then
                hdr.Append(";")
            End If
        Next
        hdr.Append("<br>")
    End If

    hdr.Append(String.Format("<b>Subject:</b>{0}<br>" & vbCrLf, _FormatHtmlTag(oMail.Subject)))
    
    Dim atts() As Attachment = oMail.Attachments
    count = atts.Length
    If (count > 0) Then
        If (Not Directory.Exists(tempFolder)) Then
            Directory.CreateDirectory(tempFolder)
        End If

        hdr.Append("<b>Attachments:</b>")
        For i As Integer = 0 To count - 1
            Dim attname As String = String.Format("{0}\{1}", tempFolder, att.Name)
            'Save attachment to temporal folder.
            att.SaveAs(attname, True)
            hdr.Append(String.Format("<a href=""{0}"" target=""_blank"">{1}</a> ", attname, att.Name))
            If (att.ContentID.Length > 0) Then
                'show embedded image.
                html = html.Replace("cid:" + att.ContentID, attname)
            ElseIf (String.Compare(att.ContentType, 0, "image/", 0, "image/".Length, True) = 0) Then
                'show attached image.
                html = html + String.Format("<hr><img src=""{0}"">", attname)
            End If
        Next
    End If

    Dim reg As Regex = New Regex("(<meta[^>]*charset[ \t]*=[ \t""]*)([^<> \r\n""]*)", _
     RegexOptions.Multiline Or RegexOptions.IgnoreCase)
    html = reg.Replace(html, "$1utf-8")
    If Not (reg.IsMatch(html)) Then
        hdr.Insert(0, "<meta HTTP-EQUIV=""Content-Type"" Content=""text-html; charset=utf-8"">")
    End If
    'Save to a html file.
    html = hdr.ToString() + "<hr>" + html
    Dim fs As New FileStream(htmlName, FileMode.Create, FileAccess.Write, FileShare.None)
    Dim data() As Byte = System.Text.UTF8Encoding.UTF8.GetBytes(html)
    fs.Write(data, 0, data.Length)
    fs.Close()
    oMail.Clear()
End Sub


[C# - Parse Email] using System.IO; using System.Text; using System.Text.RegularExpressions; using EAGetMail; private string _FormatHtmlTag(string src) { src = src.Replace(">", "&gt;"); src = src.Replace("<", "&lt;"); return src; } // we parse the email file and generate a html + attachment folder for the email, once the html is create, // you can open this html with IE and view the content and get the attachments. public void ParseEmailToHtml(string emlFile) { //if the email is c:\test.eml, then we will generate the c:\test.htm to //display the body text and save the attachments to c:\test folder int pos = emlFile.LastIndexOf("."); string mainName = emlFile.Substring(0, pos); string htmlName = mainName + ".htm"; string tempFolder = mainName; //For evaluation usage, please use "TryIt" as the license code, otherwise the //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then //"trial version expired" exception will be thrown. Mail 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) { MessageBox.Show(ep.Message); oMail.Load(emlFile, false); } } if(oMail.IsSigned) { try { // this email is digital signed. EAGetMail.Certificate cert = oMail.VerifySignature(); MessageBox.Show("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) { MessageBox.Show(ep.Message); } } // Parse from, to, cc, body and attachments. // Decode winmail.dat (TNEF) automatically // also convert RTF body to HTML body automatically oMail.DecodeTNEF(); string html = oMail.HtmlBody; StringBuilder hdr = new StringBuilder(); hdr.Append("<font face=\"Courier New,Arial\" size=2>"); hdr.Append( "<b>From:</b> " + _FormatHtmlTag(oMail.From.ToString()) + "<br>"); 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>"); } 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))); 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]; string attname = String.Format("{0}\\{1}", tempFolder, att.Name); // save attachment to temporal folder. 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 image. html = html.Replace("cid:" + att.ContentID, attname); } else if(String.Compare(att.ContentType, 0, "image/", 0, "image/".Length, true) == 0) { // show attached image. 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\">"); } //save 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(); }
[C++/CLI - Parse Email] using namespace System; using namespace System::Text; using namespace System::Text::RegularExpressions; using namespace System::Collections; using namespace System::IO; using namespace EAGetMail; //add EAGetMail namespace String^ _FormatHtmlTag(String ^src) { src = src->Replace(">", "&gt;"); src = src->Replace("<", "&lt;"); return src; } // we parse the email file and generate a html + attachment folder for the email, once the html is create, // you can open this html with IE and view the content and get the attachments. public: void ParseEmailToHtml(String ^emlFile) { //if the email is c:\test.eml, then we will generate the c:\test.htm to //display the body text and save the attachments to c:\test folder int pos = emlFile->LastIndexOf("."); String^ mainName = emlFile->Substring(0, pos); String^ htmlName = String::Format("{0}.htm", mainName); String^ tempFolder = mainName; //For evaluation usage, please use "TryIt" as the license code, otherwise the //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then //"trial version expired" exception will be thrown. Mail ^oMail = gcnew 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 = gcnew Certificate(); // oCert->Load("c:\\test.pfx", "pfxpassword", // Certificate::CertificateKeyLocation::CRYPT_USER_KEYSET); // oMail = oMail->Decrypt(oCert); oMail = oMail->Decrypt(nullptr); } 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."); // 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 from, to, cc, body and attachments. // Decode winmail.dat (TNEF) automatically // also convert RTF body to HTML body automatically oMail->DecodeTNEF(); String ^html = oMail->HtmlBody; StringBuilder ^hdr = gcnew StringBuilder(); hdr->Append("<font face=\"Courier New,Arial\" size=2>"); hdr->Append(String::Format("<b>From:</b> {0}<br>", _FormatHtmlTag(oMail->From->ToString()))); array<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>"); } 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))); array<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]; 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)); String^ simage = "image/"; if(att->ContentID->Length > 0) { // Show embedded image. html = html->Replace(String::Format("cid:{0}", att->ContentID), attname); } else if(String::Compare(att->ContentType, 0, "image/", 0, simage->Length, true) == 0) { // show attached image. html = String::Concat(html, String::Format("<hr><img src=\"{0}\">", attname)); } } } Regex ^reg = gcnew Regex("(<meta[^>]*charset[ \t]*=[ \t\"]*)([^<> \r\n\"]*)", (RegexOptions)(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\">"); } html = html->Insert(0, "<hr>"); html = html->Insert(0, hdr->ToString()); FileStream ^fs = gcnew FileStream(htmlName, FileMode::Create,FileAccess::Write, FileShare::None); array<unsigned char>^ data = System::Text::UTF8Encoding::UTF8->GetBytes(html); fs->Write(data, 0, data->Length); fs->Close(); oMail->Clear(); }

See Also

Mail.From Property
Mail.To Property
Mail.Cc Property
Mail.TextBody Property
Mail.HtmlBody Property
Mail.Attachments Property

Online Tutorials

Parse Email in C# - Tutorial
Parse winmail.dat(TNEF) in C# - Tutorial
Parse Email in VB.NET - Tutorial
Parse winmail.dat(TNEF) in VB.NET - Tutorial
Parse Email in C++/CLI - Tutorial
Parse winmail.dat(TNEF) in C++/CLI - Tutorial