node.jsemailemail-attachmentsamazon-sescourier-api

How do I attach a file to an email sent with AWS SES using Courier?


I would like to add a PDF to an email I'm sending using Courier. I've set up my account to use Amazon SES as my email provider. I'm using the Courier Node.js SDK to send the message:

const courier = CourierClient();

const { messageId } = await courier.send({
  eventId: "MONTHLY_BILLING", 
  recipientId: "81462728-70d2-4d71-ab44-9d627913f1dd", 
  data: {
    "tennant_id": "W5793",
    "tennant_name": "Oscorp, Inc.",
    "billing_date": {
      "month": "November",
      "year": "2020"
    },
    "amount": 99.0
  }
});

How can I also include the invoice as a PDF?


Solution

  • You can include an attachment by using a Provider Override. Each provider's overrides are different, but you can learn more about the AWS SES Overrides in the Courier Docs.

    You'll need to get the file you'd like to attach as a base64 encoded string. This will differ based on where your file is located. To retrieve a file from a filesystem, you can do the following:

    const fs = require('fs');
    
    const file = fs.readFileSync("/path/to/file");
    const strFile = new Buffer(file).toString("base64");
    

    Now you can update your Courier send method to include the override:

    const courier = CourierClient();
    
    const { messageId } = await courier.send({
      eventId: "MONTHLY_BILLING", 
      recipientId: "81462728-70d2-4d71-ab44-9d627913f1dd", 
      data: {
        "tennant_id": "W5793",
        "tennant_name": "Oscorp, Inc.",
        "billing_date": {
          "month": "November",
          "year": "2020"
        },
        "amount": 99.0
      },
      override: {
        "aws-ses": {
          attachments: [
            {
              fileName: "FileName.pdf",
              contentType: "application/pdf",
              data: strFile
            }
          ]
        }
      }
    });