I have tried a lot of solutions that worked for others on here, but I've been tackling this for a few days and am still at a loss. For some reason, sending emails via localhost works perfectly, but when the site is live, it does not. Here is my code:
app.post('/contact', (req, res) => {
const CLIENT_ID = process.env.C_ID;
const CLIENT_SECRET = process.env.C_SECRET;
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const REFRESH_TOKEN = process.env.R_TOKEN;
const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
async function sendMail() {
try {
const accessToken = await oAuth2Client.getAccessToken();
const transport = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: process.env.EMAIL_USER,
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
refreshToken: REFRESH_TOKEN,
accessToken: accessToken,
},
});
const mailOptions = {
from: req.body.email,
to: process.env.EMAIL_USER,
subject: `Message from ${req.body.email}`,
text: req.body.message
};
const result = await transport.sendMail(mailOptions)
return result
} catch (error) {
return error
}
}
sendMail()
.then((result) => console.log('Email sent: ', result), res.send('success'))
.catch((error) => console.log(error.message));
});
Here are the main solutions I've tried:
- https://myaccount.google.com/lesssecureapps
- https://accounts.google.com/b/0/displayunlockcaptcha
- Previously added "port: 465" and "host: "smtp.gmail.com"" lines above auth as well but that was a no-go.
- If it's any help, here is the tutorial video I followed for the nodemailer settings: https://youtu.be/-rcRf7yswfM
Any ideas? Thank you for reading.
EDIT: To add to this, I'm not getting any error messages no matter what I do. To preface this, I'm relatively new at this.
EDIT*: I tried to send an email via the web server on google cloud SDK(?) and this came up:
Error: No refresh token is set. Which doesn't make too much sense to me.
Also saw this in there which I didn't understand:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client