Search code examples
emailgmail-apiemail-attachments

Gmail API sender not sending multiple attachments


I am using Gmail API to send an email in JavaScript. It's working fine for text plus one attachment. But when I try to send two attachments, only the first one gets attached, and nothing for the other one. My code for building the message is:

  var nl = '\n';
  var boundary = "__myapp__";

const messageParts = [
        'MIME-Version: 1.0',
        'Content-Transfer-Encoding: 7bit',
        'From: XXXX Support <XXXXX@XXXXX.XXXXX>',
        'To: Moin <' + event.email + '>',
        'subject: ' + utf8Subject,
        'Content-Type: multipart/mixed; boundary=' + boundary + nl,
        '--' + boundary,
        'Content-Type: text/plain; charset=UTF-8',
        'Content-Transfer-Encoding: 7bit' + nl,
        messageBody+ nl,
        '--' + boundary,
        'Content-Type: Application/pdf; name=' + testFileName,
        'Content-Disposition: attachment; filename=' + testFileName,
        'Content-Transfer-Encoding: base64' + nl,
        testFile.Body.toString('base64'),
        '--' + boundary,
        'Content-Type: Application/pdf; name=' + testFileName,
        'Content-Disposition: attachment; filename=' + testFileName,
        'Content-Transfer-Encoding: base64',
        testFile.Body.toString('base64'),
        '--' + boundary + '--'
      ]

After this I create a string from the array. The code above is just testing with attaching the same small attachment of 6k twice, to avoid anything to do with limits. I think I have an error in how I've built the message somehow, but can't work out where.


Solution

  • In your first attachment:

     'Content-Type: Application/pdf; name=' + testFileName,
        'Content-Disposition: attachment; filename=' + testFileName,
        'Content-Transfer-Encoding: base64' + nl,
        testFile.Body.toString('base64'),
        '--' + boundary,
    

    In your second attachment:

        'Content-Type: Application/pdf; name=' + testFileName,
        'Content-Disposition: attachment; filename=' + testFileName,
        'Content-Transfer-Encoding: base64',
        testFile.Body.toString('base64'),
    

    You are missing the trailing newline for the "content-transfer-encoding" header item.

    I strongly suggest using an existing library to compose MIME message, so you don't have to worry about these details. See: https://www.npmjs.com/package/mimemessage