Last active
December 12, 2021 00:06
-
-
Save adafycheng/d227436f4e8ae2d8e2a8d282efe21e6a to your computer and use it in GitHub Desktop.
Node.js program to send email via Gmail SMTP server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var cors = require('cors') | |
var nodemailer = require('nodemailer'); | |
/* | |
* Configurations | |
*/ | |
const allowedOrigin = ["https://adafycheng.github.io","http://localhost:5000"]; | |
const emailUser = 'testing@gmail.com'; | |
const password = 'hdkshfeioslcuwlc'; | |
var transporter = nodemailer.createTransport({ | |
host: 'smtp.gmail.com', | |
port: 587, | |
auth: { | |
user: emailUser, | |
pass: password | |
} | |
}); | |
// End Configurations | |
var app = express(); | |
app.use(express.urlencoded({ extended: false })); | |
// Middleware function | |
app.get("*", function(req, res, next) { | |
console.log(req.method + " " + req.path + " - " + req.ip); | |
next(); | |
}); | |
var corsOptions = { | |
origin: allowedOrigin, | |
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 | |
} | |
// Post params | |
app.post("/contact", cors(corsOptions), function(req, res, next) { | |
const body = req.body; | |
let fromEmail = body.contactEmail; | |
let fromName = body.contactName; | |
let toEmail = emailUser; | |
let emailSubject = 'Email sent from Portfolio Website'; | |
let message = body.contactMsg; | |
let mailOptions = { | |
from: fromEmail, | |
to: toEmail, | |
subject: emailSubject, | |
html: '<p>Message from <strong>' + fromName + ' (' + fromEmail + ')</strong></p><p>' + message + '</p>' | |
}; | |
// Send the email | |
transporter.sendMail(mailOptions, function(error, info){ | |
if (error) { | |
console.log(error); | |
} else { | |
console.log('Email sent: ' + info.response); | |
} | |
}); | |
res.json({"Message: ": "Contact message sent successfully."}); | |
}); | |
const server = app.listen(8080, () => { | |
const host = server.address().address; | |
const port = server.address().port; | |
console.log(`Example app listening at http://${host}:${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment