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