Coded Geekery

BlogWritingAboutContact
BlogWritingAboutContact

Sendgrid

Send an email to a user.

const sendgrid = require('@sendgrid/mail') sendgrid.setApiKey(process.env.SENDGRID_API_KEY) export default async (req, res) => { let response; try { response = await sendgrid.send({ to: req.body.to, from: req.body.from, subject: req.body.subject, text: req.body.text }).then((response) => { console.log(response[0].statusCode) console.log(response[0].headers) }) .catch((error) => { console.error(error) }) } catch (error) { return res.status(error.statusCode || 500).json({ error: error.message }); } return res.status(200).json({ result: response.message }); };

Usage#

  • Create Sendgrid Account

  • First, create a Sendgrid account. Then, retrieve your API key.

  • Add & Verify Domain

  • If you want emails to come from your email address, you'll need to add a domain. Don't want this right now? Use the sandbox domain.

  • Add Environment Variables

  • To securely access the API, we need to include the secret with each request.

    Remember: never commit secrets to git. Thus, we should use an environment variable.

    Not Playing

    Spotify

    Coded Geekery

    TwitterGitHubInstagramgumroadbuymeacoffee

    Stuff

    HomeAbout MeContact Me

    © 2022 Roger Stringer. All rights reserved.