SendGrid

Send an email to a user.

S
import sendgrid from '@sendgrid/mail';

sendgrid.setApiKey(process.env.SENDGRID_API_KEY);

export default async (req, res) => {
  try {
    await sendgrid.send({
      to: 'your@email.com',
      from: 'your@email.com',
      subject: 'jamstackfns',
      text: 'Hello, world!'
    });
  } catch (error) {
    return res.status(error.statusCode || 500).json({ error: error.message });
  }

  return res.status(200).json({ error: '' });
};
import sendgrid from '@sendgrid/mail';

sendgrid.setApiKey(process.env.SENDGRID_API_KEY);

exports.handler = async (event, context) => {
  try {
    await sendgrid.send({
      to: 'your@email.com',
      from: 'your@email.com',
      subject: 'jamstackfns',
      text: 'Hello, world!'
    });
  } catch (error) {
    return res.status(error.statusCode || 500).json({ error: error.message });
  }

  return {
    statusCode: 200,
    body: JSON.stringify({ error: '' })
  };
};

Usage#

1

Create SendGrid Account

First, create a SendGrid account. Then, generate an API key.

2

Add Sender Authentication

To protect against spam, SendGrid requires customers to verify their Sender Identities.

  1. Navigate to Sender Authentication.
  2. Click "Create New Sender".
  3. Fill out the form and click "Create".
  4. Verify your email address.
3

Add Environment Variables

To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable.

  • Netlify: Settings -> Build & deploy -> Environment -> Environment variables.
  • Vercel: Settings -> General -> Environment Variables.

Alternatively, you can add the enviornment variable to your vercel.json or netlify.toml file.

New functions in your inbox

Get access to functions when they're added.