Skip to content

Instantly share code, notes, and snippets.

@rishavk1102
Last active December 9, 2023 11:13
Show Gist options
  • Save rishavk1102/bd5dc98e70d0f535e920eee8e3024a52 to your computer and use it in GitHub Desktop.
Save rishavk1102/bd5dc98e70d0f535e920eee8e3024a52 to your computer and use it in GitHub Desktop.
Simple code to send an email using SendGrid with attachments
const express = require("express");
const mail = require("@sendgrid/mail");
const app = express();
// It is highly recommended to store the API Keys in a seperate file and DO NOT check it in Git
mail.setApiKey("__sendgrid_api_key__");
app.post('/email/send', (req, res) => {
let {
to,
cc,
bcc,
from,
subject,
text,
html,
attachments
} = req.body;
// Any 1 of to, cc or bcc are required to successfully send an email.
const message = {
to,
cc,
bcc,
from: {
name: from.name,
email: from.email,
},
replyTo: from.email,
subject,
text,
html,
attachments,
};
mail.send(message).then((response) => {
/*
* @param {JSONObject} response - Response received from SendGrid. It contains the email id with the key name as sg-mail-id
*/
res.status(200).send({
message: 'Email sent successfully!'
});
}).catch((err) => {
res.status(500).send({
message: 'Email not sent!',
error: err.message
});
});
})
let port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Webserver running on 3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment