How to define custom domain email in nodemailer?

Zeshan Virk picture Zeshan Virk · Apr 17, 2018 · Viewed 8k times · Source

I'm trying to send email using Nodejs package Nodemailer, but i'm unable to change the from email to my custom domain email. Any help will be appreciated. here is the code i'm using to send an email.

transporter.sendMail({
   from: '[email protected]',
   to: '[email protected]',
   subject: 'Message',
   text: 'I hope this message gets through!',
   auth: {
            user: '[email protected]'
         }
});

Answer

FernandoTN picture FernandoTN · Apr 24, 2018

Just like it is pointed out in the nodemailer documentation https://nodemailer.com/smtp/

You need to configure a transporter with your custom domain info (host, port, user and password) You can find this info in the email configuration of your specific hosting provider.

var transporter = nodemailer.createTransport({
    host: 'something.yourdomain.com',
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: '[email protected]', // your domain email address
      pass: 'password' // your password
    }
  });

Then you can go on and define the mail options:

  var mailOptions = {
    from: '"Bob" <[email protected]>',
    to: '[email protected]',
    subject: "Hello",
    html : "Here goes the message body"
  };

Finally you can go on and use the transporter and mailOptions to send an email using the function sendEmail

  transporter.sendMail(mailOptions, function (err, info) {
    if (err) {
      console.log(err);
      return ('Error while sending email' + err)
    }
    else {
      console.log("Email sent");
      return ('Email sent')
    }
  });