问题
I'm trying to use nodemailer in a Cloud Functions for Firebase but keep getting errors seeming to be that the smpt server cant be reached or found. Iv'e tried gmail, outlook and a normal hosted smpt service. It works well from my local node server.
This is the logged error I receive from the failed attempt to send email:
{
Error: getaddrinfoENOTFOUNDsmtp-mail.outlook.comsmtp-mail.outlook.com: 587aterrnoException(dns.js: 28: 10)atGetAddrInfoReqWrap.onlookup[
asoncomplete
](dns.js: 76: 26)code: 'ECONNECTION',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'smtp-mail.outlook.com',
host: 'smtp-mail.outlook.com',
port: '587',
command: 'CONN'
}
回答1:
I created a cloud function (http event) to send emails from the contact form section of my site with the following way:
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const rp = require('request-promise');
//google account credentials used to send email
const mailTransport = nodemailer.createTransport(
`smtps://user@domain.com:password@smtp.gmail.com`);
exports.sendEmailCF = functions.https.onRequest((req, res) => {
//recaptcha validation
rp({
uri: 'https://recaptcha.google.com/recaptcha/api/siteverify',
method: 'POST',
formData: {
secret: 'your_secret_key',
response: req.body['g-recaptcha-response']
},
json: true
}).then(result => {
if (result.success) {
sendEmail('recipient@gmail.com', req.body).then(()=> {
res.status(200).send(true);
});
}
else {
res.status(500).send("Recaptcha failed.")
}
}).catch(reason => {
res.status(500).send("Recaptcha req failed.")
})
});
// Send email function
function sendEmail(email, body) {
const mailOptions = {
from: `<noreply@domain.com>`,
to: email
};
// hmtl message constructions
mailOptions.subject = 'contact form message';
mailOptions.html = `<p><b>Name: </b>${body.rsName}</p>
<p><b>Email: </b>${body.rsEmail}</p>
<p><b>Subject: </b>${body.rsSubject}</p>
<p><b>Message: </b>${body.rsMessage}</p>`;
return mailTransport.sendMail(mailOptions);
}
来源:https://stackoverflow.com/questions/43306324/how-can-i-use-nodemailer-with-cloud-functions-for-firebase