Mail Constructor


Initializes a new instance of the Mail class.

[Visual Basic]
Public Sub New( _
    licenseCode As String _
)
[C#]
public Mail( 
    string licenseCode 
);
[C++]
public: Mail( 
    String* licenseCode 
);
[JScript]
public function Mail( 
    licenseCode : String 
);

Parameters

licenseCode
The license code for EAGetMail POP3 & IMAP4 Component, for evaluation usage, please use "TryIt" as the license code.

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]

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

    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 att As Attachment = atts(i)
            'this attachment is in OUTLOOK RTF format, decode it here.
            If (String.Compare(att.Name, "winmail.dat") = 0) Then
                Dim tatts() As Attachment
                Try
                    tatts = Mail.ParseTNEF(att.Content, True)
                    Dim y As Integer = tatts.Length
                    For x As Integer = 0 To y - 1
                        Dim tatt As Attachment = tatts(x)
                        Dim tattname As String = String.Format("{0}\{1}", tempFolder, tatt.Name)
                        'Save attachment to temporal folder.
                        tatt.SaveAs(tattname, True)
                        hdr.Append(String.Format("<a href=""{0}"" target=""_blank"">{1}</a> ", tattname, tatt.Name))
                    Next
                Catch ep As Exception
                    MessageBox.Show(ep.Message)
                End Try
            Else
                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
            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#]
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";
    //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 );
        }
    }

    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];
            // 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 )
                {
                    MessageBox.Show( 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 );
                    // save attachment to temporal folder.
                    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 );
            // 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++]
using namespace System::IO;
using namespace System::Text;
using namespace System::Text::RegularExpressions;
using namespace EAGetMail;

private: String* _FormatHtmlTag( String *src )
{
    src = src->Replace( S">", S"&gt;" );
    src = src->Replace( S"<", S"&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(S".");
    String *mainName = emlFile->Substring(0, pos);
    String *htmlName = String::Format( S"{0}.htm", 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(S"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(S"c:\\test.pfx", S"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( S"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,
            //  S"addressbook" );
            // then you can use send the encrypted email back to this sender.
        }
        catch(Exception *ep )
        {
            MessageBox::Show( ep->Message );
        }
    }

    String *html = oMail->HtmlBody;
    StringBuilder *hdr = new StringBuilder();

    hdr->Append( S"<font face=\"Courier New,Arial\" size=2>" );
    hdr->Append( String::Format( S"<b>From:</b> {0}<br>", _FormatHtmlTag(oMail->From->ToString())));
    MailAddress*  addrs[] = oMail->To;
    int count = addrs->Length;
    if( count > 0 )
    {
        hdr->Append( S"<b>To:</b> ");
        for( int i = 0; i < count; i++ )
        {
            hdr->Append(  _FormatHtmlTag(addrs[i]->ToString()));
            if( i < count - 1 )
            {
                hdr->Append( S";" );
            }
        }
        hdr->Append( S"<br>" );
    }

    addrs = oMail->Cc;

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

    hdr->Append( String::Format( S"<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( S"<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, S"winmail.dat" ) == 0 )
            {
                Attachment* tatts[] = NULL;
                try
                {
                    tatts = Mail::ParseTNEF( att->Content, true );
                }
                catch(Exception *ep )
                {
                    MessageBox::Show( ep->Message );
                    continue;
                }

                int y = tatts->Length;
                for( int x = 0; x < y; x++ )
                {
                    Attachment *tatt = tatts[x];
                    String *tattname = String::Format( S"{0}\\{1}", tempFolder, tatt->Name );
                    //save attachment to temporal folder
                    tatt->SaveAs( tattname , true );
                    hdr->Append( String::Format(S"<a href=\"{0}\" target=\"_blank\">{1}</a> ", tattname, tatt->Name ));
                }
                continue;
            }

            String *attname = String::Format( S"{0}\\{1}", tempFolder, att->Name );
            //save attachment to temporal folder
            att->SaveAs( attname , true );
            hdr->Append( String::Format( S"<a href=\"{0}\" target=\"_blank\">{1}</a> ", attname, att->Name ));
            if( att->ContentID->Length > 0 )
            {   // show embedded image.
                html = html->Replace( String::Format( S"cid:{0}", att->ContentID), attname );
            }
            else if( String::Compare( att->ContentType, 0, S"image/", 0, S"image/"->Length, true ) == 0 )
            {
                // show attached image.
                html = String::Concat( html, String::Format( S"<hr><img src=\"{0}\">", attname ));
            }
        }
    }

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

    html = html->Insert( 0, S"<hr>" );
    html = html->Insert( 0, hdr->ToString());

    //save html to file
    FileStream *fs = new FileStream(htmlName, FileMode::Create,FileAccess::Write, FileShare::None );
    unsigned char data __gc[] = System::Text::UTF8Encoding::UTF8->GetBytes( html );
    fs->Write(data, 0, data->Length);
    fs->Close();
    oMail->Clear();
}