How to send an e-mail from Node.js?

2020-07-24 04:52发布

问题:

I'm trying to send an e-mail from a React/Node.js application. Currently, I'm trying to use emailjs module.

The code is the following:

const emailjs = require('emailjs')

sendEmail(email) {
  var server    = emailjs.server.connect({
    user:    "USERNAME", 
    password:"PASSWORD", 
    host:    "HOST_URL", 
    ssl:     false
  });
  server.send({
    text:    'Message', 
    from:    '"Sender" <mail@provider.com>', 
    to:      email,
    subject: "Some message subject"
  }, 
  function(err, message) { 
    console.log(err || message); 
  });
}

When this method is executed, I get the following error: net.Socket is not a constructor.

How can I send an e-mail from a Node.JS application (using any NPM module, not necessarily emailjs)?

Update 1 (30.07.2017 09:12 MSK): Nodemailer doesn't work -- I get the error 09:11:03 web.1 | Module not found: Can't resolve 'dns' in 'C:\myproject\node_modules\nodemailer\lib\mailer'.

回答1:

I use nodemailer to send emails and just love how simple it is.

This is the website to that module: https://nodemailer.com/about/

It has all the examples that you can follow Below is an example I got from w3school. I always use this and works like charm. Depends on what kind of email you use (gmail, hotmail, outlook,...), make proper changes and you're good

var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'myfriend@yahoo.com',
  subject: 'Sending Email using Node.js',
  text: 'That was easy!'
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});


回答2:

I found the cause of the problem. Originally, the function for sending the e-mail was located inside a React component. An answer in this question said it's impossible to send an e-mail from the front end.

So I moved the e-mail sending routine into server.js and now the original error disappeared.



回答3:

Hi @DP_ and everyone.-

I had succesfuly implemented nodemailer, thanks to you also, i had the same DNS error and moved the Send function to server.js and that helped me a lot. However to make it work with Nodemailer i used Hapi.js and also xoauth2 becouse i want to send a custom e-mail through gmail, which is very important for me. You need to configure Xoauth2 first at Google Api and add the api's to your account first, then wait some time till your refreshToken is approved and add it to your app. And that is in short what i did, hope this helps somebody becouse it took me some time to get it working.