Scan/Replace Text in Email Body in C++

This example may help C++ programmers needing to scan email bodies for strings and automatically replace:

void EmailBodyExample(void)
    {
    CkEmail email;

    // Set the plain-text and HTML alternative bodies.
    // Note: Because we're using literal strings, the strings passed
    // to these methods are ANSI strings (i.e. they are 1-byte per char
    // in this case).
    email.AddPlainTextAlternativeBody("á, é, í, ó, ú, abc");
    email.AddHtmlAlternativeBody("<html><body><p>á, é, í, ó, ú, abc</p></body></html>");

    // Suppose we don't know the language or charset of the email?
    // Maybe it's Chinese, perhaps it's Hebrew...
    // You can get the body text in utf-8 (the multibyte encoding of Unicode)
    // for all languages.  Here's how to do it:
    CkString strPlainTextBody;
    CkString strHtmlBody;

    // Get the email bodies into the CkString objects:
    email.GetPlainTextBody(strPlainTextBody);
    email.GetHtmlBody(strHtmlBody);

    // Now get the utf-8 (null-terminated) strings:
    const char *strUtf8PlainTextBody = strPlainTextBody.getUtf8();
    const char *strUtf8HtmlBody = strHtmlBody.getUtf8();

    // Suppose you want to modify the body and replace it?
    // Let's replace "abc" with "123".
    // One way to do it is like this:
    strPlainTextBody.replaceAllOccurances("abc","123");

    // Tell the email object that "const char *" arguments will point to utf-8,
    // not ANSI:
    email.put_Utf8(true);

    // Pass the modified utf-8 string.
    // AddPlainTextAlternativeBody will replace the existing plain-text
    // body if it already exists.
    email.AddPlainTextAlternativeBody(strPlainTextBody.getUtf8());

    // Another way to do it:
    char *tmpBuf = new char[strHtmlBody.getSizeUtf8()+1];   // Add 1 for the terminating null
    strcpy(tmpBuf,strUtf8HtmlBody);
    char *abc = strstr(tmpBuf,"abc");
    if (abc)
	{
	*abc = '1'; abc++;
	*abc = '2'; abc++;
	*abc = '3';
	}
    email.AddHtmlAlternativeBody(tmpBuf);

    delete [] tmpBuf;

    // Save the email and examine it using a text editor or email client..
    email.SaveEml("out.eml");
    }
Tags :