Reputation: 637
I am using the Sendgrid API to send emails from my Node.js project. When running on my local machine this works just fine but now I have deployed to Digital Ocean (Ubuntu) the mails do not send. I have read that Digital Ocean blocks smtp ports by default and you can apparently open them through the command line but I can't find an easy to understand explanation on how to do this.
const nodemailer = require("nodemailer");
const sendgridTransport = require('nodemailer-sendgrid-transport');
const transporter = nodemailer.createTransport(sendgridTransport({
auth: {
api_key: process.env.SENDGRID_API
}
}));
return transporter.sendMail({
to: '[email protected]',
from: email,
subject: subject,
html: `<h1>Contact Form</h1>
<p>Name: ${name}</p>
<p>Email: ${email}</p>
<p>${comments}</p>
`
});
UPDATE
If I remove the .env for the api key and actually hardcode it in eg:
const transporter = nodemailer.createTransport(sendgridTransport({
auth: {
api_key: '12345677788999'
}
}));
then my emails send. This is my .env file ( I am using dotenv)
DB_USER=username
DB_PASSWORD=password
DB_NAME=mydbname
SENDGRID_API=12345677788999
So, not sure why that would be?
Upvotes: 1
Views: 1585
Reputation: 153
I had the same issue using SendGrid, Digitalocean (Ubuntu) and PM2.
It seems that PM2 doesn't automatically detect changes in .env file as @himank mentioned in his answer, so i had to delete the project from PM2, then started it again.
Kindly note:
I followed this guide to set global Environment variables: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-environment-variables-in-linux/
I also followed this guide to configure PM2 with my Nodejs (Nestjs) project: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-20-04
Upvotes: 0
Reputation: 439
Have you exported this "SENDGRID_API" in the environment. Then only you can use process.env.SomeEnvironmentVar.
If you are using PM2. You will have to add it to the ecosystem file. Then it will use that config and boot your application. Making all the vars available.
Upvotes: 1