简体   繁体   中英

Send email in Node.js with nodemailer

My target is to be able to send email without setting credentials. For this purpose I've picked up the nodemailer module. Here is my code:

var nodemailer = require('nodemailer');
var message = {
  from: "test@gmail.com",
  to: "test1@gmail.com",
  subject: "Hello ✔",
  text: "Hello world ✔",
  html: "<b>Hello world ✔</b>"
};
nodemailer.mail(message);

According to documentation the "direct" transport method should be used (actually I don't know nothing about transport methods at all). But unfortunately this method is absolutely unstable - sometimes it works sometimes it doesn't. Could anyone shed some light on it? How can I send email without configuring SMTP transport credentials?

  1. Sure, but it totally depends on server's configuration. Most email servers will not work unless you use authentication. It is 2017 🙂
  2. Well, AFAIK nodemailer detects the correct configuration based on the email domain, in your example you have not set the transporter object so it uses the default port 25 configured. To change the port specify in options the type. And I highly recommend you to specify it explicitly.
  3. Probably windows firewall or antivirus preventing outgoing access. Try to get debug/error messages. We need something to help you more.

Here is a new version of the nodemailer and here is an example how to use it:

const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    host: 'smtp.example.com',
    port: 465,
    secure: true, // secure:true for port 465, secure:false for port 587
    auth: {
        user: 'username@example.com',
        pass: 'userpass'
    }
});

// setup email data with unicode symbols
let mailOptions = {
    from: '"Fred Foo 👻" <foo@blurdybloop.com>', // sender address
    to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ?', // plain text body
    html: '<b>Hello world ?</b>' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log(error);
    }
    console.log('Message %s sent: %s', info.messageId, info.response);
});

I hope it helps.

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