首页 > 解决方案 > Unable to send email through nodemailer

问题描述

I'm developing node.js application in localhost. In this I'm trying to send mail using nodemailer.

Here is the code to used to send mail:

const nodemailer = require('nodemailer');
module.exports = {
sendMail : function( message, htmlMessage, subject, email ) {
const transporter = nodemailer.createTransport( {
service : 'gmail',
host : 'smtp.gmail.com',
auth : {
user : 'username',
pass : 'password'
            },
tls: {
rejectUnauthorized: false
            }
        });
// setup email data with unicode symbols
let mailOptions = {
from : 'sender mail id', // sender address
to : email, // list of receivers
subject : subject, // Subject line
text : message, // plain text body
html : htmlMessage // html body
        };
// send mail with defined transport object
transporter.sendMail( mailOptions, (error, info) => {
if (error) {
return console.log(error);
            }
console.log('Message sent: %s', info.messageId);
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
        });
    }
};

I'm getting the below error:

Error: connect ETIMEDOUT 74.125.130.108:587

at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {

errno: -4039,

code: 'ESOCKET',

syscall: 'connect',

address: '74.125.130.108',

port: 587,

command: 'CONN'

}

Kindly someone help me to resolve this issue.

标签: node.jsemailnodemailer

解决方案


如果您的防火墙已经关闭,您应该进行这些更改。

const nodemailer = require('nodemailer');
module.exports = {
sendMail : function( message, htmlMessage, subject, email ) {
                     const transporter = nodemailer.createTransport({
                                         service : 'gmail',
                                         auth : {
                                                 user : 'username',
                                                 pass : 'password'
                                                }
                                        });
// setup email data with unicode symbols
let mailOptions = {
            from : 'xyz@gmail.com', // sender address
            to : email, // list of receivers
            subject : subject, // Subject line
            text : message, // plain text body
        };
// send mail with defined transport object
transporter.sendMail( mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message sent: %s', info.messageId);
            console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
        });
    }
};

设置后,打开链接https://myaccount.google.com/lesssecureapps并打开“开启”允许不太安全的应用:开启。然后通过运行您的节点服务器进行检查。


推荐阅读