Why isn't nodemailer working?

So I created a simple contact form that sends a POST request with all the necessary input values to my server-side so that I can use node-mailer to send a mail to me. I have enabled it to console.log() in case it didn’t work, and that’s all I’m getting. There are no formal errors in the logs either! Here’s the nodemailer code:


app.post("/contact", (req, res) => {
  // Instantiate the SMTP server
  const transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
      user: process.env.GMAIL_USER,
      pass: process.env.GMAIL_PAS // naturally, replace both with your real credentials or an application-specific password
    }
  });

  // Specify what the email will look like
  const mailOpts = {
    from: "Dr. Strange", 
    to: process.env.GMAIL_USER,
    subject: "You have got fan mail???!!!",
    text: `${req.body.name} (${req.body.email}) says: ${req.body.message}`
  };

  // Attempt to send the email
  transporter.sendMail(mailOpts, (error, response) => {
    if (error) {
      console.log("It failed!");
    } else {
      console.log("Yaay!!");
    }
  });
});

View the code at glitch.com/edit/#!/khaleelgibran. The concerned pages are the contact.html in the app folder and the server.js Feel free to look around! Also, there is React stuff in there.

You’ll need to enable Non-secure apps to access your Gmail account else you can’t send emails using the NodeMailer module. You can do that here.

No, I’ve already done that! :grinning:

Maybe Gmail doesn’t allow you to send an email to yourself. Otherwise, the email could be rejected due to the from section not being the sender’s email?

I don’t think so. I searched for nodemailer examples and I’ve seen everywhere that they just include a name, and in some cases, the email address, but still it’s used as text. Let me see if there’s anything with the POST requests, but what’s unusual is that I’m getting no errors. Also, I think I should tell you this, but when I click Submit in the contact form, the web page tries to reload, but doesn’t successfully do it.

There are two issues with the code above that might cause this:

  • there is no response sent to the browser, in the sendMail callback.
  • console log “it failed” should be seen on the server (glitch editor log), but it is not logging the error details

Once you get gmail’s error messages you can start diagnostics.

I suggest testing with something else before trying gmail … from nodemailer doc:

Autogenerated email test accounts from Ethereal.email

On the npm page they also say:

Gmail either works well or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you then don’t use it.

1 Like

I’ll try that but about the last bit:

Well, I got myself another email address (with protonmail) and it didn’t seem to reslove. I’ll try testing with the test accounts.

@mishavee, here’s an update:

This worked perfectly! I can’t seem to find out what’s wrong!

UPDATE:

At least I’m getting an error now:

{ Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs
534-5.7.14 bJiKg7e7G0j4lKBwYKToZC5rGADQHUgi2xNNoG5dDYhMVR75z3jsf94X2dyOU-o5TxlyH
534-5.7.14 B1hl9tW1edizWUCYfeCTCrGhThy9QNsFfRbqzQwr1lUY-8FTsKp7FQUugQP1X0Ds>
534-5.7.14 Please log in via your web browser and then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/78754 t198sm11330111qke.6 - gsmtp
    at SMTPConnection._formatError (/rbd/pnpm-volume/b2f03a5f-edac-4c67-87ab-3d2e27db6053/node_modules/.registry.npmjs.org/nodemailer/6.4.2/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
    at SMTPConnection._actionAUTHComplete (/rbd/pnpm-volume/b2f03a5f-edac-4c67-87ab-3d2e27db6053/node_modules/.registry.npmjs.org/nodemailer/6.4.2/node_modules/nodemailer/lib/smtp-connection/index.js:1523:34)
    at SMTPConnection._responseActions.push.str (/rbd/pnpm-volume/b2f03a5f-edac-4c67-87ab-3d2e27db6053/node_modules/.registry.npmjs.org/nodemailer/6.4.2/node_modules/nodemailer/lib/smtp-connection/index.js:550:26)
    at SMTPConnection._processResponse (/rbd/pnpm-volume/b2f03a5f-edac-4c67-87ab-3d2e27db6053/node_modules/.registry.npmjs.org/nodemailer/6.4.2/node_modules/nodemailer/lib/smtp-connection/index.js:942:20)
    at SMTPConnection._onData (/rbd/pnpm-volume/b2f03a5f-edac-4c67-87ab-3d2e27db6053/node_modules/.registry.npmjs.org/nodemailer/6.4.2/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
    at TLSSocket.SMTPConnection._onSocketData.chunk (/rbd/pnpm-volume/b2f03a5f-edac-4c67-87ab-3d2e27db6053/node_modules/.registry.npmjs.org/nodemailer/6.4.2/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
  code: 'EAUTH',
  response: '534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n534-5.7.14 bJiKg7e7G0j4lKBwYKToZC5rGADQHUgi2xNNoG5dDYhMVR75z3jsf94X2dyOU-o5TxlyH\n534-5.7.14 B1hl9tW1edizWUCYfeCTCrGhThy9QNsFfRbqzQwr1lUY-8FTsKp7FQUugQP1X0Ds>\n534-5.7.14 Please log in via your web browser and then try again.\n534-5.7.14  Learn more at\n534 5.7.14  https://support.google.com/mail/answer/78754 t198sm11330111qke.6 - gsmtp',
  responseCode: 534,
  command: 'AUTH PLAIN' }

Something to do with Gmail…

Yes, I figured it out! I replaced the example user and password details and with my Gmail settings and changed SMTP settings accordingly (and I started getting errors because the example had a .catch(console.error). Then I had to do something called ‘Unlock Captcha’ (by Gmail) which allows access to unsecure apps and logins. I had to do the Unlock Captcha thing everytime the project restarted (every 5 minutes) so I used Uptime Robot. I’ll close the issue, but I have one more trouble: how do I catch errors and res.send a reply accordingly. Here’s my code:

app.post("/contact", function(req, res) {
  async function main() {
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: "smtp.gmail.com",
      port: 465,
      secure: true, // true for 465, false for other ports
      auth: {
        user: process.env.GMAIL_USER, // generated ethereal user
        pass: process.env.GMAIL_PASS //generated ethereal password
      }
    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: `A Fan! ${req.body.name} - ${req.body.email}`, // sender address
      to: "khalby786@gmail.com", // list of receivers
      subject: `You've got fan mail from ${req.body.name}!!!`, // Subject line
      text: `Name: ${req.body.name}
Email: ${req.body.email} 
Message: ${req.body.message}` // plain text body
    });


  }

  main().catch(console.error);
  console.log("Yaay!"); // This is an adjustment!
  res.send("The message has been sent  !"); // This is also an adjustment!
});






UPDATE:
There is no point in using Uptime Robot. Every time I send a message using the contact form, I have to do the Unlock Captcha thing so that it can send something to my Gmail account.

1 Like

Looks a lot like the example code in ethereal :stuck_out_tongue:

Its already catching the errors, so replace console.error with your own function, example:

  main()
    .then(()=>{
      console.log('ok');
      res.send('ok');
    })
    .catch(err => {
      console.error(err);
      res.send(err);
    });

Note that sending from a gmail account with a different from address than the account has a good chance of being treated as spam by the receiving system.

That’s what I told you earlier :stuck_out_tongue::

And no it’s not being treated as spam either!


Thanks for this, but what’s the answer to

???

This article suggests using [email protected] for the user and from address, I haven’t tried it … https://community.nodemailer.com/using-gmail/

@mishavee, I’ll try using the oAuth2 method!

Thanks @mishavee! That article helped! I used oAuth2 and it worked!

1 Like