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 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\Samples_VS2008\pop3_imap4_simple.vcNative or C:\Program Files (x86)\EAGetMail\Samples_VS2008\pop3_imap4_simple.vcNative 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 <atlbase.h>
#include <atlcom.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;
}

void _GenerateHtmlForEmail(CString &htmlName, CString &emlFile, CString& tempFolder)
{
    IMailPtr oMail;
    oMail.CreateInstance("EAGetMailObj.Mail");
    oMail->LicenseCode = _T("TryIt");
    oMail->LoadFile(emlFile.GetString(), VARIANT_FALSE);

    if(oMail->IsEncrypted == VARIANT_TRUE)
    {
        //this email is encrypted, we decrypt it by user default certificate.
        oMail = oMail->Decrypt(NULL);

    }

    if(oMail->IsSigned == VARIANT_TRUE)
    {
        // This email is digital signed.
        ICertificatePtr oCert = oMail->VerifySignature();
        _tprintf(_T("This email contains a valid digital signature.\r\n"));
    }

    CString html = (TCHAR*)oMail->HtmlBody;
    CString hdr;
    hdr.Preallocate(1024 * 5);

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

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

    long LBound = 0, UBound = 0;
    SAFEARRAY *psa = NULL;

    _variant_t arAddr = oMail->To;

    psa = arAddr.parray;
    SafeArrayGetLBound(psa, 1, &LBound);
    SafeArrayGetUBound(psa, 1, &UBound);

    INT count = UBound-LBound+1;
    if(count > 0)
    {
        hdr.Append(_T("<b>To:</b> "));
        for(long i = LBound; i <= UBound; i++)
        {
            _variant_t vtAddr;
            SafeArrayGetElement(psa, &i, &vtAddr);

            IMailAddressPtr pAddr;
            vtAddr.pdispVal->QueryInterface(__uuidof(IMailAddress), (void**)&pAddr);

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

            hdr.Append(_FormatHtmlTag(tp.GetString()));
            if(i < UBound)
            {
                hdr.Append(_T(";"));
            }
        }
        hdr.Append(_T("<br>"));
    }

    arAddr.Clear();
    arAddr = oMail->Cc;

    psa = arAddr.parray;
    SafeArrayGetLBound(psa, 1, &LBound);
    SafeArrayGetUBound(psa, 1, &UBound);

    count = UBound-LBound+1;
    if(count > 0)
    {
        hdr.Append(_T("<b>Cc:</b> "));
        for(long i = LBound; i <= UBound; i++)
        {
            _variant_t vtAddr;
            SafeArrayGetElement(psa, &i, &vtAddr);

            IMailAddressPtr pAddr;
            vtAddr.pdispVal->QueryInterface(__uuidof(IMailAddress), (void**)&pAddr);

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

            hdr.Append(_FormatHtmlTag(tp.GetString()));
            if(i < UBound)
            {
                hdr.Append(_T(";"));
            }
        }
        hdr.Append(_T("<br>"));
    }

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

    _variant_t atts = oMail->Attachments;
    psa = atts.parray;
    SafeArrayGetLBound(psa, 1, &LBound);
    SafeArrayGetUBound(psa, 1, &UBound);

    count = UBound-LBound+1;
    if(count > 0)
    {
        ::CreateDirectory(tempFolder.GetString(), NULL);
        hdr.Append(_T("<b>Attachments:</b>"));
        for(long i = LBound; i <= UBound; i++)
        {
            _variant_t vtAtt;
            SafeArrayGetElement(psa, &i, &vtAtt);

            IAttachmentPtr pAtt;
            vtAtt.pdispVal->QueryInterface(__uuidof(IAttachment), (void**)&pAtt);

            CString name = (TCHAR*)pAtt->Name;
            if(name.CompareNoCase(_T("winmail.dat")) == 0)
            {
                // this attachment is in OUTLOOK RTF (TNEF) format, decode it here.
                _variant_t tatts;
                tatts = oMail->ParseTNEF(pAtt->Content, VARIANT_TRUE);

                long XLBound = 0, XUBound = 0;

                SAFEARRAY* tpsa = tatts.parray;
                SafeArrayGetLBound(tpsa, 1, &XLBound);
                SafeArrayGetUBound(tpsa, 1, &XUBound);
                for(long x = XLBound; x <= XUBound; x++)
                {
                    _variant_t vttAtt;
                    SafeArrayGetElement(tpsa, &x, &vttAtt);
                    IAttachmentPtr ptAtt;
                    vttAtt.pdispVal->QueryInterface(__uuidof(IAttachment), (void**)&ptAtt);

                    CString tattname = tempFolder;
                    tattname.Append(_T("\\"));
                    tattname.Append((TCHAR*)ptAtt->Name);
                    ptAtt->SaveAs(tattname.GetString(), VARIANT_TRUE);

                    hdr.Append(_T("<a href=\""));
                    hdr.Append(tattname);
                    hdr.Append(_T("\" target=\"_blank\">"));
                    hdr.Append((TCHAR*)ptAtt->Name);
                    hdr.Append(_T("</a> "));
                }
                continue;
            }

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

            hdr.Append(_T("<a href=\""));
            hdr.Append(attname);
            hdr.Append(_T("\" target=\"_blank\">"));
            hdr.Append((TCHAR*)pAtt->Name);
            hdr.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("\">"));
            }
        }
    }

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

    html = hdr + "<hr>" + html;
    IToolsPtr oTools;
    oTools.CreateInstance("EAGetMailObj.Tools");
    oTools->WriteTextFile(htmlName.GetString(), html.GetString(), CP_UTF8);

    oMail->Clear();
    oMail.Release();
}

void ConvertMailToHtml(LPCTSTR lpszFile)
{
    try
    {
        CString fileName = lpszFile;

        int pos = fileName.ReverseFind(_T('.'));
        CString mainName = fileName.Mid(0, pos);
        CString htmlName = mainName + _T(".htm");

        CString tempFolder = mainName;
        WIN32_FIND_DATA findData;
        HANDLE hFind = ::FindFirstFile(htmlName.GetString(), &findData);
        BOOL bExist = FALSE;

        if(hFind != INVALID_HANDLE_VALUE)
        {
            ::FindClose(hFind);
            bExist = TRUE;
        }

        if(!bExist)
        { // We haven't generate the html for this email, generate it now.
            _GenerateHtmlForEmail(htmlName, fileName, tempFolder);
        }

    }
    catch(_com_error &ep)
    {
        _tprintf(_T("Error: %s\r\n"), (const TCHAR*)ep.Description());
    }
}

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

    ConvertMailToHtml(_T("c:\\my folder\\test.eml"));

    return 0;
}

32bit/x64 ActiveX DLL

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

File Platform
Installation Path\EAGetMailObj.dll 32 bit
Installation Path\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.