Search code examples
amazon-web-servicessalesforceapex-codeamazon-ses

How should I create an email with attachments (MIME) for Amazon Simple Email Service using force.com?


I would like to create emails with attachments via force.com through Amazon Web Services' Simple Email Service service because of the force.com organization-wide limit of 1,000 single outbound email messages per day.

The SendEmail method in AWS' SES does not support attachments, but they do provide support for raw emails via SendRawEmail (at least for most file type that you'd be interested in sending).

As far as I can tell, you can't get the raw version of a SingleEmailMessage and need to construct it yourself.

How should I create a multipart MIME email message in APEX?


Solution

  • You can use the EncodingUtil class to convert the attachment to Base64.

    Lay out your email according to the MIME standards.

    Here's a borrowed example:

    Content-Transfer-Encoding: 7bit
    Content-Type: multipart/mixed; boundary="_----------=_10167391557129230"
    MIME-Version: 1.0
    Date: Thu, 21 Mar 2002 19:32:35 UT
    From: martin dot zahn at akadia dot ch
    To: martin dot zahn at akadia dot ch
    Subject: MIME test
    X-Mailer: MIME::Lite 2.106  (B2.11; Q2.03)
    
    This is a multi-part message in MIME format.
    
    --_----------=_10167391557129230
    Content-Transfer-Encoding: binary
    Content-Type: text/plain
    
    Hello world!
    
    --_----------=_10167391557129230
    Content-Transfer-Encoding: base64
    Content-Type: application/zip; name="test_file.zip"
    
    UEsDBBQAAAAIAEAUmicKJJts5wUAANkOAAAHAAAAaG93LmNnaa1XbW/bRgz+
    7AD5D6ziJPJmR8k+DEj8snWd0wRonS51VwxNYcj22bpZ1qm6cx0v8H77SN5J
    APsNAAAAAA==
    
    --_----------=_10167391557129230--
    
    .