简体   繁体   中英

Unhandled promise rejection while sending email using Node.js

I'm using this script for sending email:

var mailer = require('nodemailer');

var smtpTransport = mailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'user',
        pass: 'pass'
    }
});

 smtpTransport.sendMail({       
        sender: 'user',
        to: 'user',
        subject: 'Attachment!',
        body: 'mail content...',
        attachments: [{   
        filename: 'text3.txt',
        path: 'pat/to/file.txt' 
    }]
    }), function(err, success) {
        if (err) {
        }

    }

But I'm getting this error:

Unhandled promise rejection (rejection id: 9): Error: connect ETIMEDOUT

What's wrong?

Unhandled Promise rejection means that there is some Promise function that doesn't have a .catch . Nodemailer's .sendMail function is a Promise function so you can either have a callback or use it like a Promise.

In your code your fuction(err, sucess) is outside of your .sendMail function. Here is how you could correct it:

 smtpTransport.sendMail({       
    sender: 'user',
    to: 'user',
    subject: 'Attachment!',
    body: 'mail content...',
    attachments: [{   
    filename: 'text3.txt',
    path: 'pat/to/file.txt' 
}]
},(err, success) => {
    if (err) {
    }
});

Well, firstly what is wrong is you have a ETIMEDOUT error coming from your email call. Are you sure you have all the parameters correct?

Secondly use Promises, rather than callback style, and catch the rejection. Like this,

smtpTransport
  .sendMail(...)
  .then(success => console.log('success: ', success))
  .catch(error => console.log('error: ', error))

Maybe is a rejection from GMail, Try Login in to: https//www.google.com/setti ngs/security/lesssecureapps and TURN ON " Access for less secure apps ". Or use OAuth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM