Skip to content

Instantly share code, notes, and snippets.

@ahmnouira
Created October 2, 2021 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmnouira/83155f5c173d1dc66751a86824b73c67 to your computer and use it in GitHub Desktop.
Save ahmnouira/83155f5c173d1dc66751a86824b73c67 to your computer and use it in GitHub Desktop.
Node.js + Nodemailer: Sending email with Gmail
const express = require("express");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, from, size, fields, type"
);
next();
});
app.get("/", (req, res, next) => {
res.send("Well, it works.");
});
/**
* Send email
*/
app.post('/sendemail', (req, res, next) => {
const subject = req.body.subject;
const email = req.body.email;
const message = req.body.message;
let smtpTransport = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
secure: true,
port: 465,
auth: {
user: <contact@gmail.com>,
pass: <password>
}
});
let mailOptions = {
from: email, //sender adress
to: "ahmnouira@gmail.com", //receive adress
subject: `Subject - ${subject}`,
html: `
<b>- From: </b> ${email} <br />
<b>- Subject: </b> ${subject} <br />
<b>- Message: </b> <br /> <br/> ${message}
`
};
smtpTransport
.sendMail(mailOptions)
.then((result) => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(400).json(err);
})
})
/**
* Error handler
*/
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
res.status(status).json({ message: message, data: data });
});
app.listen(3000, () => {
console.log("up and running on 3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment