Sample code for 30+ languages & platforms
Unicode C++

Send HTML Email with Attachments

See more SMTP Examples

Demonstrates how to send an HTML email with file attachments.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkMailManW.h>
#include <CkEmailW.h>
#include <CkStringBuilderW.h>

void ChilkatSample(void)
    {
    bool success = false;

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    CkMailManW mailman;

    mailman.put_SmtpHost(L"smtp.my-starttls-mail-server.com");

    mailman.put_SmtpUsername(L"MY-SMTP-USERNAME");
    mailman.put_SmtpPassword(L"MY-SMTP-PASSWORD");

    mailman.put_StartTLS(true);
    mailman.put_SmtpPort(587);

    // Create a new email object
    CkEmailW email;
    email.put_Subject(L"Test SMTP API to Send HTML Email with Attachments");
    email.put_From(L"Joe Programmer <joe@my-starttls-mail-server.com>");
    email.AddTo(L"Chilkat Support",L"support@chilkatsoft.com");

    // Add a plain-text alternative body, which will likely never be seen.
    // (It is shown if the receiving email client is incapable of displaying HTML email.)
    email.AddPlainTextAlternativeBody(L"This is a plain-text alternative body...");

    // Our HTML will include an image, so add the related image here.
    const wchar_t *contentIdStarfish = email.addRelatedFile(L"qa_data/jpg/starfish.jpg");
    if (email.get_LastMethodSuccess() != true) {
        wprintf(L"%s\n",email.lastErrorText());
        return;
    }

    // The src attribute for the image tag is set to the contentIdStarfish:
    CkStringBuilderW sbHtml;
    sbHtml.Append(L"<html><body><p>This is an HTML email with an embedded image.</p>");
    sbHtml.Append(L"<p><img src=\"cid:CONTENT_ID_STARFISH\" /></p></body></html>");
    int numReplacements = sbHtml.Replace(L"CONTENT_ID_STARFISH",contentIdStarfish);

    email.AddHtmlAlternativeBody(sbHtml.getAsString());

    // Finally, add some attachments to the email.
    // Add a file attachment.
    success = email.AddFileAttachment2(L"qa_data/pdf/fishing.pdf",L"application/pdf");
    if (success != true) {
        wprintf(L"%s\n",email.lastErrorText());
        return;
    }

    // Add an attachment where the content is contained in a string.
    const wchar_t *content = L"This is the content of the 2nd attached file.";
    email.AddStringAttachment(L"someText.txt",content);

    // Send the HTML email.
    success = mailman.SendEmail(email);
    if (success != true) {
        wprintf(L"%s\n",mailman.lastErrorText());
        return;
    }

    success = mailman.CloseSmtpConnection();
    if (success != true) {
        wprintf(L"Connection to SMTP server not closed cleanly.\n");
    }

    wprintf(L"HTML email with attachments sent!\n");
    }