Sendgrid
Last updated
npm install @sendgrid/mailconst sgMail = require('@sendgrid/mail');
sgMail.setApiKey('YOUR_SENDGRID_API_KEY');
const msg = {
to: 'recipient@example.com',
from: 'sender@example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail
.send(msg)
.then(() => {
console.log('Email sent successfully');
})
.catch((error) => {
console.error(error);
});Email sent successfullyconst msg = {
to: 'recipient@example.com',
from: 'sender@example.com',
templateId: 'd-f43daeeaef504760851f727007e0b5d6',
dynamicTemplateData: {
name: 'John Doe',
company: 'Acme Inc.'
},
};
sgMail.send(msg);const express = require('express');
const app = express();
app.post('/webhook', express.json(), (req, res) => {
const events = req.body;
events.forEach(event => {
console.log('Event:', event.event);
console.log('Email:', event.email);
});
res.sendStatus(200);
});
app.listen(3000, () => console.log('Webhook server running on port 3000'));const messages = [
{
to: 'recipient1@example.com',
from: 'sender@example.com',
subject: 'Hello, Recipient 1',
text: 'This is a test email for Recipient 1',
},
{
to: 'recipient2@example.com',
from: 'sender@example.com',
subject: 'Hello, Recipient 2',
text: 'This is a test email for Recipient 2',
},
];
sgMail
.send(messages)
.then(() => console.log('Emails sent successfully'))
.catch((error) => console.error(error));# Development
export SENDGRID_API_KEY='YOUR_API_KEY'
# Production (e.g., Heroku)
heroku config:set SENDGRID_API_KEY='YOUR_API_KEY'