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
  • 477
  • 2
  • 12
  • `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

1

Can you please try :

USERNAME='example@gmailcom'

There should not be space between assignments.

Deepak Jha
  • 162
  • 2
  • 10
0

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

0

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,109
  • 7
  • 16