Twillio’s Sendgrid is one of the most popular email services used across the world.
Sending an email from the front-end is a three-step process:
- We send the mail content (parsed HTML) to our backend app
- Backend server accepts the request and forwards the request content to the Mail Send server (v2 / v3) with the required authentication
- Backend server then returns the Mail Send server’s response to the front-end app
We cannot send an email directly using Sendgrid API or any secure email service from the front-end alone. This is because we need to protect the API key provided by Sendgrid from being exposed by the browser. The key is used by Sendgrid for authentication.
Assuming you have the API key in your Sendgrid account, you can follow along. Please note that in the below example, we’re running the following apps:
- Vue.js (front-end) on http://localhost:3131
- Node.js (back-end) on https://localhost: 3000
Front-end setup
First, let’s have a look at how we can create a message body from the front-end (Vue.js):
<template>
<div id="app">
<button @click="sendMail"></button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
emailTemplateString: "<p>Hello world!</p>",
};
},
methods: {
async sendMail() {
const result = await fetch("http://localhost:3000/sendmail", {
body: JSON.stringify(this.createEmailBody()),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
if (result.status === 200) {
alert("Mail sent successfully!");
}
},
createEmailBody() {
return {
content: [
{
type: "text/html",
value: this.emailTemplateString,
},
],
};
},
},
};
</script>
Code language: HTML, XML (xml)
In the above code, we have nothing but a button that calls the sendMail method. Inside this method, we make an API call to our backend server. It can be anywhere (hosted) and the endpoint can be anything. We must have the same endpoint in our backend, ready to receive the requests. We’ve parsed the email body content on line 18. It’s worth noticing that on line 31, we created an array of “content”. This is a standard set by Sendgrid. We can find the API reference for the same here.
A basic Sendgrid request body looks like this:
{
from: "tom@example.com",
personalizations: [
{
to: ["john@example.com"],
subject: "Hello there!"
}
],
reply_to: "nina@example.com",
content: [
{
type: "text/html",
value: "<p>Hello world!</p>",
}
]
}
Code language: JavaScript (javascript)
However, we only send the “content” part from the front-end. We’re actually done with the front-end part!
Back-end setup
First, we need to install a few npm libraries. We can run the below command to install them all at once:
npm install express cors body-parser @sendgrid/mail --save
Code language: CSS (css)
We can now create a helper method named helpers/emailHelper.js:
const createEmailRequestBody = (content) => {
const emailRequestBody = {
from: "tom@example.com",
personalizations: [
{
to: ["john@example.com"],
subject: "Hello there!"
}
],
reply_to: "nina@example.com",
content
}
return emailRequestBody
}
module.exports = {
createEmailRequestBody
}
Code language: JavaScript (javascript)
This method created a complete request body for the Sendgrid Mail Send API.
We now create a helper method to send the mail named helpers/sendgridHelper.js:
const client = require('@sendgrid/mail');
client.setApiKey("YOUR-SENDGRID-API-KEY");
const sendMessage = async (message) => {
let response = null;
try {
response = await client.send(message)
} catch (error) {
if (error.response) {
console.error(error.response.body)
response = error.response.body;
}
}
return response
}
module.exports = {
sendMessage
}
Code language: JavaScript (javascript)
Finally, here’s our app.js server:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const emailHelper = require("./helpers/emailHelper");
const sendgridHelper = require('./helpers/sendgridHelper');
const strings = require("./strings");
const port = 3000;
// initialize express
const app = express();
// application/json parser
const jsonParser = bodyParser.json();
// application/x-www-form-urlencoded parser
const urlEncodedParser = bodyParser.urlencoded({ extended: false });
// express middleware
app.use(
cors({
origin: ["http://localhost:3131"],
})
);
// routes
app.get("/", (req, res, next) => {
res.send(404)
});
app.post("/sendmail", jsonParser, async (req, res) => {
const mailRequestBody = emailHelper.createEmailRequestBody(req.body.content);
const response = await sendgridHelper.sendMessage(mailRequestBody)
if(response && response?.length && response[0]?.statusCode == 202) {
res.status(200).send({
message: "Mail sent successfully!"
})
} else {
res.status(400).send(response)
}
});
// server port
app.listen(port, () => {
console.log("Express running on port ", port);
});
Code language: PHP (php)
In the above code, we’ve first added our Vue.js app’s exclusion to the CORS on line 21. This will allow our Vue app to make requests to our server without CORS violations.
We’ve then accepted the request made from the front-end on line 30. We first created the email request body, and then sent it to the Mail Send API. If then checked the response code and if it was accepted, we sent a success message to our front-end app.
If you have any suggestions or doubts, sound off in the comments below!