Visual C++ - Convert email to HTML

The following c++ codes demonstrate how to convert email to a HTML page and display it using Web browser Control.

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.

Installation

Before you can use the following sample codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.

Add reference

To better demonstrate how to retrieve email and parse email, let’s create a Visual C++ console project named “receiveemail” at first, and then add the reference of EAGetMail in your project.

Visual C++ console project

To use EAGetMail POP3 & IMAP4 ActiveX Object in your project, the first step is “Add header files of EAGetMail to your project”. Please go to C:\Program Files\EAGetMail\Include\tlh or C:\Program Files (x86)\EAGetMail\Include\tlh folder, find eagetmailobj.tlh and eagetmailobj.tli, and then copy these files to your project folder. You can start to use it to retrieve email and parse email in your project.

add reference in C++

Visual C++ - Parse and convert email to HTML - example

The following example codes demonstrate converting email to HTML page. In order to run it correctly, please change email server, user, password, folder, file name value to yours.

Note

To get full sample projects, please download and install EAGetMail on your machine.

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

32bit/x64 ActiveX DLL

Seperate builds of run-time dll for 32 and x64 platform

File Platform
Installation Path\Lib\native\x86\EAGetMailObj.dll 32 bit
Installation Path\Lib\native\x64\EAGetMailObj.dll 64 bit

Distribution

  • Standard EXE

    For VB6, C++, Delphi or other standard exe application, you can distribute EAGetMailObj.dll with your application to target machine without COM-registration and installer. To learn more detail, please have a look at Registration-free COM with Manifest File.

  • Script

    For ASP, VBScript, VBA, MS SQL Stored Procedure, you need to install EAGetMail on target machine by EAGetMail installer, both 32bit/x64 DLL are installed and registered.

Appendix

Comments

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