Skip to content

Instantly share code, notes, and snippets.

@clodal
Last active August 23, 2021 06:50
Show Gist options
  • Save clodal/13029ca2da1efc8fca8217094e683029 to your computer and use it in GitHub Desktop.
Save clodal/13029ca2da1efc8fca8217094e683029 to your computer and use it in GitHub Desktop.
How to setup a new Mail lambda for sending emails

Amplify Email Template Solution (AWS Pinpoint + Mail)

We use Mail to generate email template html body. We need to use a Lambda because Mail is a backend-only package as it relies on ESJ (a kind of server-side templating language). Using Mail on the FE is not possible.

The idea is to fire a request to this lambda to generate the html template and pass it off to AWS Pinpoint to fire the email.

Pre-Requisites

  1. amplify add analytics and amplify push to add Pinpoint
  2. Access Key & Secret Access Key of IAM User with PinPointFullAccess
  3. And also enable email channel in Pinpoint interface

Add Mail Lambda

  1. Create Mail Lambda
➜  api git:(feature/add-mail-infra) amplify add api
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the project: mail
? Provide a path (e.g., /items) /mail
? Choose a Lambda source Create a new Lambda function
? Provide a friendly name for your resource to be used as a label for this category in the project: mail
? Provide the AWS Lambda function name: mail
? Choose the function template that you want to use: Serverless express function (Integration with Amazon API Gateway)
? Do you want to access other resources created in this project from your Lambda function? No
? Do you want to edit the local lambda function now? No
Succesfully added the Lambda function locally
? Restrict API access No
? Do you want to add another path? No
Successfully added resource mail locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud
  1. In ./amplify/backend/function/mail/src, do npm install mailgen to install mailgen
  2. In ./amplify/backend/function/mail/src/app.js, add the following method to create the method handler:
var Mail = require('mail')

/**
 * Create mail template
 * @link https://www.npmjs.com/package/mail
 */
app.post('/mail', function(req, res) {
  try {
    // Add your code here
    const { config = {}, email } = req.body

    // Configure mail by setting a theme and your product info
    const mailGenerator = new Mail({
      theme: 'default',
      product: config,
    });

    // Generate an HTML email with the provided contents
    const html = mailGenerator.generate(email);

    // Generate the plaintext version of the e-mail (for clients that do not support HTML)
    const text = mailGenerator.generatePlaintext(email);

    res.json({ success: 'post call succeed!', html, text })
  } catch (err) {
    res.json({ err })
  }
});
  1. Then do amplify push to save these lambda changes
  2. In src/config.ts, paste the newly generated lambda from src/aws-exports.js to update the config:
{
  ...
  aws: {
    ...
    aws_cloud_logic_custom: [
      {
        name: 'mail',
        endpoint: 'https://<HASH>.execute-api.<REGION>.amazonaws.com/<ENV>',
        region: '<REGION>',
      },
    ],
  }
}
  1. In AWS Console, Add the following to the Lambda env var config
aws_pinpoint_access_key_id="AKIA-XXXXXXXXXXXXXXXXXX"
aws_pinpoint_secret_access_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
  1. Restart project server
  2. In code, fire the API as such:
import { API } from 'aws-amplify'

const response = await API.post('mail', '/mail', {
  body: {
    config: {
      name: 'Mom & Pop',
      link: 'https://momandpop.sg',
    },
    email: {
      body: {
        name: 'John Appleseed',
        intro: "Welcome to Mail! We're very excited to have you on board.",
        action: {
          instructions: 'To get started with Mail, please click here:',
          button: {
            color: '#22BC66', // Optional action button color
            text: 'Confirm your account',
            link: 'https://mail.js/confirm?s=d9729feb74992cc3482b350163a1a010',
          },
        },
        outro: "Need help, or have questions? Just reply to this email, we'd love to help.",
      },
    },
  },
})

Note on Troubleshooting AWS Lambda: If you face issues with the Lambda returning an error. Check go to AWS Console > Lambda > Your Function > CloudWatch Logs and find out the cause.

  1. At this point you can find the generated html + text template in the response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment