SendGrid email forwarding hook on free plan
Cost-effective solution to handle inbound emails
Cost-effective solutions are essential in software development. SendGrid’s free plan covers sending emails, but receiving emails requires a paid plan. This article demonstrates how to use the SendGrid Inbound Parse webhook to forward incoming emails to your own email account at no additional cost.
Create /api/sendgrid/mail-forwarding endpoint
Choose your best node.js framework (e.g.: express, next.js, nuxt.js, nest.js, …) and create a new endpoint with the name you want.
First, install the required packages (@sendgrid/mail and multer):
npm i @sendgrid/mail multer --save Here is the TS code snippet, that I use to forward incoming emails to my personal email account.
// /sendgrid/mail-forwarding.ts
import sendGridMail from '@sendgrid/mail';
import multer from 'multer';
const SENDGRID_API_KEY = 'API_KEY'; // Use your own SendGrid api_key
const SENDGRID_TO_EMAIL = 'to@example.com'; // Use your personal email address to receive mails
const SENDGRID_FROM_EMAIL = 'from@example.com'; // Use the email address or domain you verified on SendGrid
const initMiddleware = (middleware: any) => {
return (req: Request, res: Response) =>
new Promise((resolve, reject) => {
middleware(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
};
sendGridMail.setApiKey(SENDGRID_API_KEY!);
type ResponseData = {};
const upload = multer();
const multerAny = initMiddleware(
upload.any() // Note that Multer limits to 1MB file size by default
);
export default async (req: Request, res: Response<ResponseData>) => {
if (req.method !== 'POST') {
return res.status(405).json({});
}
await multerAny(req, res);
const body = req.body;
if (!body['text'] && !body['html']) {
return res.status(400).json({});
}
const mailData: sendGridMail.MailDataRequired = {
to: SENDGRID_TO_EMAIL,
from: SENDGRID_FROM_EMAIL!,
replyTo: body['from'],
subject: body['subject'] ?? 'Forwarded email',
text: body['text'],
html: body['html']
};
try {
await sendGridMail.send(mailData);
} catch (_error: any) {
return res.status(500).json({});
}
res.status(200).json({});
}; SendGrid - Inbound Parse
Visit SendGrid / Settings page, here is the link. On the screen press the Add Host & URL and set the following options:
- Receiving Domain: // Choose your domain
- Destination URL: // Location of your deployed API endpoint
- Additional Options
- SPAM CHECK ✅
- SEND RAW ❌
Conclusion
This lightweight forwarding endpoint has been reliably processing hundreds of emails in production without issues.