DEV Community

SWAPNIL AHMMED SHISHIR
SWAPNIL AHMMED SHISHIR

Posted on

Set up Gmail App Password for Nodemailer

βœ… Step-by-Step: Set up Gmail App Password for Nodemailer


πŸ” 1. Enable 2-Step Verification

  1. Go to https://myaccount.google.com/security
  2. Scroll to the "Signing in to Google" section.
  3. Find 2-Step Verification.
  4. Click it and set it up (if not already enabled).
  • You may be asked to verify your phone number.
  • Complete the process.

πŸ”‘ 2. Generate an App Password

  1. Once 2-Step Verification is enabled, stay on the Security page.

  2. Scroll down to App passwords (under "Signing in to Google").

You’ll only see this option after enabling 2FA.

  1. Click App passwords (You might be asked to re-enter your password).

  2. Under "Select app", choose "Mail".

  3. Under "Select device", choose "Other", and type something like DocumentStamp App.

  4. Click Generate.

  5. Copy the 16-character app password (example: jgme rbts kixk lwvd).

  • This is your EMAIL_PASS.

πŸ› οΈ 3. Update Your .env File

In your project’s .env file:

EMAIL_USER=yourmail@gmail.com
EMAIL_PASS= # ← Your generated app password
Enter fullscreen mode Exit fullscreen mode

Make sure you DO NOT commit this .env file to GitHub or share it publicly.


πŸš€ 4. Use in Nodemailer Code

Example Nodemailer setup (sendEmail.js):

const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS,
  },
});

module.exports = async function sendEmail({ to, subject, html }) {
  await transporter.sendMail({
    from: `"DocumentStamp" <${process.env.EMAIL_USER}>`,
    to,
    subject,
    html,
  });
};
Enter fullscreen mode Exit fullscreen mode

πŸ“₯ 5. Send Mail to a Specific Email (e.g., demo@gmail.com)

In your controller (submitBookForm), import and call sendEmail:

import sendEmail from "../utils/sendEmail.js"; // adjust path

await sendEmail({
  to: "demo@gmail.com", // receiver email
  subject: "New Book Form Submission",
  html: `
    <h2>New Submission Received</h2>
    <p><strong>Name:</strong> ${name} ${lastName}</p>
    <p><strong>Email:</strong> ${email}</p>
    <p><strong>Message:</strong> ${message}</p>
    ${image_url ? `<p><strong>File:</strong> <a href="https://yourdomain.com${image_url}">Download</a></p>` : ""}
  `,
});
Enter fullscreen mode Exit fullscreen mode

βœ… Final Checks

  • Make sure .env is loaded using dotenv:
  import dotenv from "dotenv";
  dotenv.config();
Enter fullscreen mode Exit fullscreen mode
  • Deploy only after .env is properly configured.
  • If you get Gmail auth errors: regenerate the app password.

Top comments (0)