带有 Gmail 和 NodeJS 的 Nodemailer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19877246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nodemailer with Gmail and NodeJS
提问by tonymx227
I try to use nodemailer to implement a contact form using NodeJS but it works only on local it doesn't work on a remote server...
我尝试使用 nodemailer 来实现使用 NodeJS 的联系表单,但它仅适用于本地,不适用于远程服务器...
My error message :
我的错误信息:
[website.fr-11 (out) 2013-11-09T15:40:26] { [AuthError: Invalid login - 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.
[website.fr-11 (out) 2013-11-09T15:40:26] 534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787
[website.fr-11 (out) 2013-11-09T15:40:26] 534 5.7.14 54 fr4sm15630311wib.0 - gsmtp]
[website.fr-11 (out) 2013-11-09T15:40:26] name: 'AuthError',
[website.fr-11 (out) 2013-11-09T15:40:26] data: '534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbvlX\r\n534-5.7.14 V-dFQLgb7aRCYApxlOBuha5ESrQEbRXK0iVtOgBoYeARpm3cLZuUS_86kK7yPis7in3dGC\r\n534-5.7.14 N1sqhr3D2IYxHAN3m7QLJGukwPSZVGyhz4nHUXv_ldo9QfqRydPhSvFp9lnev3YQryM5TX\r\n534-5.7.14 XL1LZuJL7zCT5dywMVQyWqqg9_TCwbLonJnpezfBLvZwUyersknTP7L-VAAL6rhddMmp_r\r\n534-5.7.14 A_5pRpA> Please log in via your web browser and then try again.\r\n534-5.7.14 Learn more at https://support.google.com/mail/bin/answer.py?answer=787\r\n534 5.7.14 54 fr4sm15630311wib.0 - gsmtp',
[website.fr-11 (out) 2013-11-09T15:40:26] stage: 'auth' }
My controller :
我的控制器:
exports.contact = function(req, res){
var name = req.body.name;
var from = req.body.from;
var message = req.body.message;
var to = '*******@gmail.com';
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "******@gmail.com",
pass: "*****"
}
});
var mailOptions = {
from: from,
to: to,
subject: name+' | new message !',
text: message
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
res.redirect('/');
}
});
}
回答by brafdlog
I solved this by going to the following url (while connected to google with the account I want to send mail from):
我通过访问以下网址解决了这个问题(使用我想从中发送邮件的帐户连接到 google):
https://www.google.com/settings/security/lesssecureapps
https://www.google.com/settings/security/lesssecureapps
There I enabled less secure apps.
在那里我启用了不太安全的应用程序。
Done
完毕
回答by Greg T
See nodemailer's official guide to connecting Gmail:
参见 nodemailer 的官方连接 Gmail 指南:
https://community.nodemailer.com/using-gmail/
https://community.nodemailer.com/using-gmail/
-
——
It works for me after doing this:
这样做后它对我有用:
- Enable less secure apps - https://www.google.com/settings/security/lesssecureapps
- Disable Captcha temporarily so you can connect the new device/server - https://accounts.google.com/b/0/displayunlockcaptcha
- 启用安全性较低的应用程序 - https://www.google.com/settings/security/lesssecureapps
- 暂时禁用验证码,以便您可以连接新设备/服务器 - https://accounts.google.com/b/0/displayunlockcaptcha
回答by Zaheen
Easy Solution:
简单的解决方案:
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: '[email protected]',
pass: 'realpasswordforaboveaccount'
}
}));
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Sending Email using Node.js[nodemailer]',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Step 1:
第1步:
go here https://myaccount.google.com/lesssecureappsand enable for less secure apps. If this does not work then
去这里https://myaccount.google.com/lesssecureapps并启用不太安全的应用程序。如果这不起作用,那么
Step 2
第2步
go here https://accounts.google.com/DisplayUnlockCaptchaand enable/continue and then try.
去这里https://accounts.google.com/DisplayUnlockCaptcha并启用/继续然后尝试。
for me step 1 alone didn't work so i had to go to step 2.
对我来说,单独的第 1 步不起作用,所以我不得不转到第 2 步。
i also tried removing the nodemailer-smtp-transport package and to my surprise it works. but then when i restarted my system it gave me same error, so i had to go and turn on the less secure app (i disabled it after my work).
我还尝试删除 nodemailer-smtp-transport 包,令我惊讶的是它有效。但是当我重新启动系统时,它给了我同样的错误,所以我不得不打开安全性较低的应用程序(我在工作后禁用了它)。
then for fun i just tried it with off(less secure app) and vola it worked again!
然后为了好玩,我只是在关闭(安全性较低的应用程序)的情况下尝试了它,然后再次运行!
回答by Laurent Perrin
You should use an XOAuth2 tokento connect to Gmail. No worries, Nodemailer already knows about that:
您应该使用XOAuth2 令牌连接到 Gmail。不用担心,Nodemailer 已经知道了:
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
XOAuth2: {
user: smtpConfig.user,
clientId: smtpConfig.client_id,
clientSecret: smtpConfig.client_secret,
refreshToken: smtpConfig.refresh_token,
accessToken: smtpConfig.access_token,
timeout: smtpConfig.access_timeout - Date.now()
}
}
};
You'll need to go to the Google Cloud Consoleto register your app. Then you need to retrieve access tokens for the accounts you wish to use. You can use passportjsfor that.
您需要转到Google Cloud Console来注册您的应用。然后,您需要检索要使用的帐户的访问令牌。你可以使用passportjs。
Here's how it looks in my code:
这是它在我的代码中的样子:
var passport = require('passport'),
GoogleStrategy = require('./google_oauth2'),
config = require('../config');
passport.use('google-imap', new GoogleStrategy({
clientID: config('google.api.client_id'),
clientSecret: config('google.api.client_secret')
}, function (accessToken, refreshToken, profile, done) {
console.log(accessToken, refreshToken, profile);
done(null, {
access_token: accessToken,
refresh_token: refreshToken,
profile: profile
});
}));
exports.mount = function (app) {
app.get('/add-imap/:address?', function (req, res, next) {
passport.authorize('google-imap', {
scope: [
'https://mail.google.com/',
'https://www.googleapis.com/auth/userinfo.email'
],
callbackURL: config('web.vhost') + '/add-imap',
accessType: 'offline',
approvalPrompt: 'force',
loginHint: req.params.address
})(req, res, function () {
res.send(req.user);
});
});
};
回答by Daniel says Reinstate Monica
I had the same problem. Allowing "less secure apps"in my Google security settings made it work!
我有同样的问题。在我的 Google 安全设置中允许“安全性较低的应用程序”使它起作用!
回答by Mohammad Masoudzadeh
Worked fine:
工作正常:
1- install nodemailer, package if not installed
(type in cmd) : npm install nodemailer
1- 安装nodemailer,如果未安装则打包(输入 cmd):npm install nodemailer
2- go to https://myaccount.google.com/lesssecureappsand turn on Allow less secure apps.
2- 转到https://myaccount.google.com/lesssecureapps并打开允许不太安全的应用程序。
3- write code:
3-写代码:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'truePassword'
}
});
const mailOptions = {
from: '[email protected]', // sender address
to: '[email protected]', // list of receivers
subject: 'test mail', // Subject line
html: '<h1>this is a test mail.</h1>'// plain text body
};
transporter.sendMail(mailOptions, function (err, info) {
if(err)
console.log(err)
else
console.log(info);
})
4- enjoy!
4-享受!
回答by Ahmet Can Güven
Same problem happened to me too. I tested my system on localhost then deployed to the server (which is located at different country) then when I try the system on production server I saw this error. I tried these to fix it:
同样的问题也发生在我身上。我在 localhost 上测试了我的系统,然后部署到服务器(位于不同的国家/地区),然后当我在生产服务器上尝试系统时,我看到了这个错误。我试过这些来修复它:
- https://www.google.com/settings/security/lesssecureappsEnabled it but it was not my solution
- https://g.co/allowaccessI allowed access from outside for a limited time and this solved my problem.
- https://www.google.com/settings/security/lesssecureapps启用它,但这不是我的解决方案
- https://g.co/allowaccess我允许在有限的时间内从外部访问,这解决了我的问题。
回答by Angel M.
For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)
对我来说,使用端口和安全性是这样工作的(我在没有安全设置的情况下使用 PHP 从 gmail 发送电子邮件时遇到问题)
I hope will help someone.
我希望会帮助某人。
var sendEmail = function(somedata){
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL,
// you can try with TLS, but port is then 587
auth: {
user: '***@gmail.com', // Your email id
pass: '****' // Your password
}
};
var transporter = nodemailer.createTransport(smtpConfig);
// replace hardcoded options with data passed (somedata)
var mailOptions = {
from: '[email protected]', // sender address
to: '[email protected]', // list of receivers
subject: 'Test email', // Subject line
text: 'this is some text', //, // plaintext body
html: '<b>Hello world ?</b>' // You can choose to send an HTML body instead
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
return false;
}else{
console.log('Message sent: ' + info.response);
return true;
};
});
}
exports.contact = function(req, res){
// call sendEmail function and do something with it
sendEmail(somedata);
}
all the config are listed here(including examples)
回答by Hamid
Non of the above solutions worked for me. I used the code that exists in the documentation of NodeMailer. It looks like this:
上述解决方案都不适合我。我使用了NodeMailer 文档中存在的代码。它看起来像这样:
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: '[email protected]',
serviceClient: '113600000000000000000',
privateKey: '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBg...',
accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x',
expires: 1484314697598
}
});
回答by sfnd
Try disabling captchas in your gmail account; probably being triggered based on IP address of requestor. See: How to use GMail as a free SMTP server and overcome captcha
尝试在您的 Gmail 帐户中禁用验证码;可能是基于请求者的 IP 地址触发的。请参阅:如何使用 GMail 作为免费的 SMTP 服务器并克服验证码

