Parse Email in C++/CLI/CLR

In previous section, I introduced how to download email with background service. In this section, I will introduce how to parse email in C++/CLI/CLR.

Introduction

After you received the emails to the local folder, we can use the following code to parse the email now. The following code demonstrates how to parse from, to, cc, subject, body text, attachments of all emails file received by previous sample.

Note

Remarks: All of examples in this section are based on first section: A simple C++/CLI/CLR 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.

[C++/CLI/CLR Example - Parse email]

The following example codes demonstrate how to use EAGetMail POP3 component to parse email sender, to, cc, subject, body text and attachments.

Note

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

#include "stdafx.h"

using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace EAGetMail; //add EAGetMail namespace

void ParseEmail(String ^emlFile)
{
    Mail ^oMail = gcnew Mail("TryIt");
    oMail->Load(emlFile, false);

    // Parse Mail From/Sender
    Console::WriteLine("From: {0}", oMail->From->ToString());

    // Parse Mail To/Recipient
    array<MailAddress^> ^addrs = oMail->To;
    for (int i = 0; i < addrs->Length; i++)
    {
        Console::WriteLine("To: {0}", addrs[i]->ToString());
    }

    // Parse Mail CC
    addrs = oMail->Cc;
    for (int i = 0; i < addrs->Length; i++)
    {
        Console::WriteLine("To: {0}", addrs[i]->ToString());
    }

    // Parse Mail Subject
    Console::WriteLine("Subject: {0}", oMail->Subject);

    // Parse Mail Text/Plain body
    Console::WriteLine("TextBody: {0}", oMail->TextBody);

    // Parse Mail Html Body
    Console::WriteLine("HtmlBody: {0}", oMail->HtmlBody);

    // Parse Attachments
    array<Attachment^> ^atts = oMail->Attachments;
    for (int i = 0; i < atts->Length; i++)
    {
        Console::WriteLine("Attachment: {0}", atts[i]->Name);
    }
}

int main(array<System::String ^> ^args)
{
    try
    {
        ParseEmail("c:\\my folder\\test.eml");
    }
    catch (Exception ^ep)
    {
        Console::WriteLine(ep->Message);
    }

    return 0;
}

TextBody and HtmlBody

Not every email has both text/plain body text and html body text. However, Mail object provides both TextBody and HtmlBody properties smartly. If the email has only text/plain body, then Mail object converts the text/plain body to html body automatically; if the email has only html body, then Mail object converts the html body to text/plain body automatically.

Next Section

At next section I will introduce how to verify digital signature and decrypt email.

Appendix

Comments

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