Parse Email Body, Attachment and Convert Email to HTML page in Visual C++

In previous section, I introduced how to parse winmail.dat. In this section, I will introduce how to parse email body and attachment, then convert email to a HTML page and display it using Web browser in Visual C++.

Introduction

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.

Note

Remarks: All of examples in this section are based on first section: A simple Visual 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.

[Visual C++ Example - Convert email to HTML]

The following example codes demonstrate how to use EAGetMail POP3 component to convert email to HTML page.

Note

To get the full sample projects, please refer to Samples section.

#include "stdafx.h"
#include <windows.h>
#include <atlstr.h>

#include "eagetmailobj.tlh"
using namespace EAGetMailObjLib;

CString _FormatHtmlTag(LPCTSTR lpszSrc)
{
    CString src = lpszSrc;

    src.Replace(_T(">"), _T("&gt;"));
    src.Replace(_T("<"), _T("&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.
void
ParseEmailToHtml(CString &emlFile)
{
    try
    {
        int pos = emlFile.ReverseFind(_T('.'));
        CString htmlFile = emlFile.Mid(0, pos) + _T(".htm");
        CString attachmentFolder = emlFile.Mid(0, pos);

        IMailPtr oMail;
        oMail.CreateInstance(__uuidof(EAGetMailObjLib::Mail));
        oMail->LicenseCode = _T("TryIt");

        oMail->LoadFile(emlFile.GetString(), VARIANT_FALSE);

        if (oMail->IsEncrypted == VARIANT_TRUE)
        {
            try
            {
                //this email is encrypted, we decrypt it by user default certificate.
                // you can also use specified certificate like this
                // oCert = new Certificate();
                // oCert.Load("c:\\test.pfx", "pfxpassword", Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
                // oMail = oMail.Decrypt( oCert );
                oMail = oMail->Decrypt(NULL);
            }
            catch (_com_error &ep)
            {
                _tprintf(_T("%s\r\n"), (TCHAR*)ep.Description());
                oMail->LoadFile(emlFile.GetString(), VARIANT_FALSE);
            }
        }

        if (oMail->IsSigned == VARIANT_TRUE)
        {
            try
            {
                //this email is digital signed.
                ICertificatePtr oCert = oMail->VerifySignature();
                _tprintf(_T("This email contains a valid digital signature.\r\n"));
                //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 (_com_error &ep)
            {
                _tprintf(_T("%s\r\n"), (TCHAR*)ep.Description());
            }
        }

        // Decode winmail.dat (TNEF) automatically'
        // also convert RTF body to HTML body automatically
        oMail->DecodeTNEF();

        CString html = (TCHAR*)oMail->HtmlBody;

        CString header;
        header.Preallocate(1024 * 5);

        header.Append(_T("<font face=\"Courier New,Arial\" size=2>"));
        header.Append(_T("<b>From:</b> "));

        CString tempValue = (TCHAR*)oMail->From->Name;
        tempValue += _T("<");
        tempValue += (TCHAR*)oMail->From->Address;
        tempValue += _T(">");
        header.Append(_FormatHtmlTag(tempValue.GetString()));
        header.Append(_T("<br>"));

        IAddressCollectionPtr addressList = oMail->ToList;
        if (addressList->Count > 0)
        {
            header.Append(_T("<b>To:</b> "));
            for (long i = 0; i < addressList->Count; i++)
            {
                IMailAddressPtr pAddr = addressList->GetItem(i);

                tempValue = (TCHAR*)pAddr->Name;
                tempValue += _T("<");
                tempValue += (TCHAR*)pAddr->Address;
                tempValue += _T(">");

                header.Append(_FormatHtmlTag(tempValue.GetString()));
                header.Append(_T(";"));
            }
            header.Append(_T("<br>"));
        }

        addressList->Clear();
        addressList = oMail->CcList;

        if (addressList->Count > 0)
        {
            header.Append(_T("<b>Cc:</b> "));
            for (long i = 0; i < addressList->Count; i++)
            {
                IMailAddressPtr pAddr = addressList->GetItem(i);

                tempValue = (TCHAR*)pAddr->Name;
                tempValue += _T("<");
                tempValue += (TCHAR*)pAddr->Address;
                tempValue += _T(">");

                header.Append(_FormatHtmlTag(tempValue.GetString()));
                header.Append(_T(";"));
            }
            header.Append(_T("<br>"));
        }

        header.Append(_T("<b>Subject:</b>"));
        header.Append(_FormatHtmlTag((TCHAR*)oMail->Subject));
        header.Append(_T("<br>"));

        IAttachmentCollectionPtr attList = oMail->AttachmentList;
        if (attList->Count > 0)
        {
            ::CreateDirectory(attachmentFolder.GetString(), NULL);
            header.Append(_T("<b>Attachments:</b>"));

            for (long i = 0; i < attList->Count; i++)
            {
                IAttachmentPtr pAtt = attList->GetItem(i);

                CString name = (TCHAR*)pAtt->Name;

                CString attName = attachmentFolder;
                attName.Append(_T("\\"));
                attName.Append((TCHAR*)pAtt->Name);
                pAtt->SaveAs(attName.GetString(), VARIANT_TRUE);

                header.Append(_T("<a href=\""));
                header.Append(attName);
                header.Append(_T("\" target=\"_blank\">"));
                header.Append((TCHAR*)pAtt->Name);
                header.Append(_T("</a> "));

                CString contentID = (TCHAR*)pAtt->ContentID;
                CString contentType = (TCHAR*)pAtt->ContentType;
                if (contentID.GetLength() > 0)
                {
                    CString find = _T("cid:");
                    find.Append(contentID);
                    //show embedded image.
                    html.Replace(find, attName);
                }
                else if (_tcsnicmp(contentType.GetString(), _T("image/"), _tcslen(_T("image/"))) == 0)
                {
                    //show attached image
                    html.Append(_T("<hr><img src=\""));
                    html.Append(attName);
                    html.Append(_T("\">"));
                }
            }
        }

        header.Insert(0, _T("<meta HTTP-EQUIV=\"Content-Type\" Content=\"text-html; charset=utf-8\">"));

        html = header + "<hr>" + html;

        IToolsPtr oTools;
        oTools.CreateInstance(__uuidof(EAGetMailObjLib::Tools));
        oTools->WriteTextFile(htmlFile.GetString(), html.GetString(), CP_UTF8);
    }
    catch (_com_error &exp)
    {
        _tprintf(_T("%s\r\n"), (TCHAR*)exp.Description());
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    // Initialize COM environment
    ::CoInitialize(NULL);

    CString emlFile = _T("c:\\my folder\\test.eml");
    ParseEmailToHtml(emlFile);
    return 0;
}

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

pop3, imap4 samples

Next Section

At next section I will introduce how to parse Non-delivery report.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.