Sendgrid
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
1
Create Sendgrid Account
First, create a Sendgrid account. Then, retrieve your API key.
2
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.
3
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.