Zsombor
Zsombor

Reputation: 27

Nodemailer Gmail Authentication Issue

I'm trying to use Nodemailer in a Node.js application to send emails via Gmail. However, I'm encountering an authentication issue with the error message "Missing credentials for 'PLAIN'." I've reviewed my code and environment variables, and everything seems correct.

// Import nodemailer module
import nodemailer from 'nodemailer';

// Create a transporter using Gmail SMTP
const transporter = nodemailer.createTransport({
  host: 'smtp.gmail.com',
  port: 465,
  secure: true,
  auth: {
    user: process.env.ADDRESS,
    pass: process.env.MAILING_SERVICE_APP_PASSWORD,
  },
  tls: {
    rejectUnauthorized: false, 
  },
});

// Function to send an email
async function sendEmail(to: string, subject: string, text: string) {
  // Email options
  const mailOptions = {
    from: process.env.ADDRESS,
    to: to,
    subject: subject,
    text: text,
  };

  // Send email
  return transporter.sendMail(mailOptions);
}

// Export the sendEmail function
export default sendEmail;

I've double-checked my environment variables, and I have set an App password for this gmail account. However, I'm still getting the same error. Can someone help me identify the issue with my Nodemailer setup?

Here is the entire error message:

[0] 2:49:04 PM - Found 0 errors. Watching for file changes.
[1] POST /register 200 149.764 ms - 475
[1] Error sending email:  Error: Missing credentials for "PLAIN"
[1]     at SMTPConnection._formatError (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:790:19)
[1]     at SMTPConnection.login (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:444:38)
[1]     at C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-transport\index.js:272:32
[1]     at SMTPConnection.<anonymous> (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:213:17)
[1]     at Object.onceWrapper (node:events:628:28)
[1]     at SMTPConnection.emit (node:events:514:28)
[1]     at SMTPConnection._actionEHLO (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:1347:14)
[1]     at SMTPConnection._processResponse (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:969:20)
[1]     at SMTPConnection._onData (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:755:14)
[1]     at SMTPConnection._onSocketData (C:\Users\zsomb\OneDrive\Desktop\University\Projects\DataProcessing-BackEnd\node_modules\nodemailer\lib\smtp-connection\index.js:193:44) {
[1]   code: 'EAUTH',
[1]   command: 'API'
[1] }

Upvotes: 0

Views: 697

Answers (2)

PRATIK0112358
PRATIK0112358

Reputation: 1

You might be using the environment variable in a wrong way. Try by manually entering the auth details once.

#ENV SAMPLE
DB_STRING=MONGO_URL
PORT=3000
JWT_SECRET=JWT_SECRET


# Mailing Services
EMAIL=***[email protected]
PASSWORD=PASSWORD

#Mailling endpoint

app.post("/sendotp", async (req, res) => {
  try {
    const { email } = req.body;
    const otp = otpGenerator.generate(6, {
      upperCaseAlphabets: false,
      specialChars: false,
    });
    let transporter = nodemailer.createTransport({
      host: "smtp.gmail.com",
      port: 587,
      secure: false,
      auth: {
        user: process.env.EMAIL,
        pass: process.env.PASSWORD,
      },
    });

    const transport = await transporter.sendMail({
      from: '"no-reply" <[email protected]>', // sender address
      to: email,
      subject: "VERIFY YOU OTP ",
      html: `
      <!DOCTYPE html>
      <html>
        <head>
          <style>
            body {
              font-family: Arial, sans-serif;
              margin: 0;
              padding: 0;
              background-color: #f4f4f4;
            }
            .container {
              width: 100%;
              max-width: 600px;
              margin: 0 auto;
              background-color: #ffffff;
              padding: 20px;
              box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            }
            .header {
              background-color: #007BFF;
              color: white;
              padding: 10px;
              text-align: center;
            }
            .content {
              padding: 20px;
            }
            .footer {
              background-color: #28A745;
              color: white;
              text-align: center;
              padding: 10px;
              margin-top: 20px;
            }
            .otp {
              font-size: 24px;
              font-weight: bold;
              color: #FF5733;
            }
            .section {
              margin-bottom: 20px;
            }
            .section h2 {
              color: #343A40;
            }
            .section p {
              color: #555555;
            }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="header">
              <h1>VERIFY YOU OTP</h1>
            </div>
            <div class="content">
              <div class="section">
                <h2>OTP Verification</h2>
                <p>Your  OTP is <span class="otp">${otp}</span></p>
              </div>
              
              <div class="section">
                <h2>Contact Us</h2>
                <p>If you have any questions or need further assistance, feel free to contact us at ${process.env.EMAIL}</p>
              </div>
            </div>
            <div class="footer">
              <p>&copy; 2024 Pratik Dhimal. All rights reserved.</p>
            </div>
          </div>
        </body>
      </html>
      `,
    });
    res.json({otp});
  } catch (error) {
    res.json({
      msg: "Something went wrong please try agian later ",
    });
  }
});

Upvotes: 0

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117106

This is what I am using the only diffrence is the port i think

const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    let testAccount = await nodemailer.createTestAccount();

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: '[REDACTED]',
            pass: '[Apps password redacted]',
        },
    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
        from: '"Linda Lawton " <[REDACTED]>', // sender address
        to: "[REDACTED]", // list of receivers
        subject: "Hello ✔", // Subject line
        text: "Hello world?", // plain text body
        html: "<b>Hello world?</b>", // html body
    });

    console.log("Message sent: %s", info.messageId);

    // Preview only available when sending through an Ethereal account
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

}

main().catch(console.error);

I did try chaning my point to 465 and setting secure to true and adding the tls. still works.

Upvotes: 1

Related Questions