1

I am trying to implement the nodemailer for contacts form. I have gone through many resources and I got the below code. server.js

// require('dotenv').config();
require('dotenv').config({ path: require('./.env') });
const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");

const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(5000, () => console.log("Server Running"));

const contactEmail = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.USERNAME,
    pass: process.env.PASSWORD,
  },
});

contactEmail.verify((error) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Ready to Send");
  }
});

router.post("/contact", (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const phonenumber= req.body.phonenumber;
  const address= req.body.address;
  const EmailSubject= req.body.EmailSubject;
  const message = req.body.message; 
  const mail = {
    from: name,
    to: process.env.SEND_TO_EMAIL,
    // subject: "Email from Fans",
    subject: 'Email From Fans: ' + EmailSubject,
    html: `<p>Name: ${name}</p><p>Email: ${email}</p><p>Contact No: ${phonenumber}</p><p>Address: ${address}</p><p>Message: ${message}</p>`,
  };
  contactEmail.sendMail(mail, (error) => {
    if (error) {
      res.json({ status: "ERROR" });
    } else {
      res.json({ status: "Thanks for your time. Your message has been sent successfully!" });
    }
  });
});

In this file, it's clearly mentioned that I am using the dotenv for the environment to take the value from the .env file. below is my .env file

USERNAME = example@gmail.com
PASSWORD = **********
SEND_TO_EMAIL = example2@gmail.com
API_HOST = http://localhost:5000/contact

When I am running command node server then I am getting below error.

PS E:\project> node server
E:\project\.env:1
USERNAME = example@gmail.com
                  ^

SyntaxError: Invalid or unexpected token
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)

I don't understand what mistakes I have done. Is there any rule to run or access the .env file? I followed the two discussion

  1. Cant access variables from .env file in node.js application
  2. Node.js Everywhere with Environment Variables! But still no luck!
Kwall
  • 549
  • 4
  • 15
  • `require('dotenv').config({ path: require('./.env') });`. I don't think you've to require the `path` in the configuration but give a string as path `require('dotenv').config({ path: './.env' });` – Srinath Kamath Aug 05 '21 at 06:10
  • @SrinathKamath same error Server Running Error: Missing credentials for "PLAIN" – Kwall Aug 05 '21 at 06:13
  • Are you able to get the env variables in the console? try to print the variables in the console. – Srinath Kamath Aug 05 '21 at 06:15
  • @SrinathKamath It's not getting print `undefined undefined undefined undefined` – Kwall Aug 05 '21 at 06:23
  • 1
    There you go, you have the answer! So just try removing the path from config. By default `dotenv` tries to find a `.env` in the same folder from where the function was called. otherwise provide a path like so `config( { path : 'path/to/your/env' } )` – Srinath Kamath Aug 05 '21 at 08:17
  • @SrinathKamath It's working now after many attempts.:), thanks!! – Kwall Aug 05 '21 at 19:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/235673/discussion-between-srinath-kamath-and-kwall). – Srinath Kamath Aug 05 '21 at 19:16

3 Answers3

2

Can you please try :

USERNAME='example@gmailcom'

There should not be space between assignments.

  • 1
    Now I am getting a new error `node server Server Running Error: Missing credentials for "PLAIN"` – Kwall Aug 05 '21 at 06:07
  • You must be using some actual email address and password. if using gmail address, it's not going to allow you directly. you may need to enable from Google oauth credentials. –  Aug 05 '21 at 06:18
  • You may find more details on this link. https://stackoverflow.com/questions/48854066/missing-credentials-for-plain-nodemailer –  Aug 05 '21 at 06:20
  • OK, but whenever I put the correct credential instead of process.env.USERNAME then It's working fine. – Kwall Aug 05 '21 at 06:25
  • var env = require('node-env-file'); env(__dirname + '/.env'); can you give a try on 'node-env-file' it's working for me. –  Aug 05 '21 at 06:46
  • Should I need to install node-env-file or packages? – Kwall Aug 05 '21 at 06:52
  • yes, you need to install. –  Aug 05 '21 at 06:57
1

As Deepak Jha pointed out, there should be no spaces between the assignments:

USERNAME='SOME_VALUE'

For the error Missing credentials for "PLAIN" that's an authentication error from Gmail. Here is a thread about that: Missing credentials for “PLAIN” nodemailer.

Aaron Sarnat
  • 1,207
  • 8
  • 16
0

Simple but please try USERNAME = "example@gmailcom". The error is pointing the @ character. And add the missing dot ;)