nodemailer and gmail APIs - node.js

Im trying to get nodemailer working using Google GMail API.
I've got my Google project set up - using their oauth sandbox for redirect,
I've got a clientID, secret and refresh token from my developers console.
The Code
const nodemailer = require('nodemailer');
const xoauth2 = require('xoauth2');
// create reusable transporter
let transporter = nodemailer.createTransport( {
service: 'gmail',
xoauth2: xoauth2.createXOAuth2Generator({
user: 'me#myDomain.com',
clientid: 'blahblahblah.apps.googleusercontent.com',
clientSecret: 'k33p-gUeSsINg',
refreshToken: '123BritneyIsTheBest'
}),
tls: {
rejectUnauthorized: false
}
} );
// setup email data
let mailOptions = {
from: 'me#myDomain.com',
to: 'me#yahoo.com',
subject: 'Hello there Google API...',
text: 'Hello Google API',
html: '<b>Hello Google API</b>'
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: ', info.messageId);
});
The Error.
{
Error: Mail command failed: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError l24sm4075119ywk.21 - gsmtp
at SMTPConnection._formatError (C:\abc\index.js:591:19)
at SMTPConnection._actionMAIL (C:\abc\index.js:1350:34)
at SMTPConnection._responseActions.push.str (C:\abc\index.js:840:18)
at SMTPConnection._processResponse (C:\abc\index.js:747:20)
at SMTPConnection._onData (C:\abc\index.js:543:14)
at TLSSocket._socket.on.chunk (C:\abc\index.js:495:47)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
code: 'EENVELOPE',
response: '530-5.5.1 Authentication Required. Learn more at\n530 5.5.1 https://support.google.com/mail/?p=WantAuthError l24sm4075119ywk.21 - gsmtp',
responseCode: 530,
command: 'MAIL FROM'
}
I have tried this - and it works, but it's my understanding that this is very unsecured and NOT acceptable for production.
const nodemailer = require('nodemailer');
// create reusable transporter object
let transporter = nodemailer.createTransport( {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'me#myDomain.com',
pass: 'Seriously?'
}
});
... all the rest is the same, removed for brevity...
The existing posts solutions have not helped.
Thank You

How about this modification?
From :
let transporter = nodemailer.createTransport( {
service: 'gmail',
xoauth2: xoauth2.createXOAuth2Generator({
user: 'me#myDomain.com',
clientid: 'blahblahblah.apps.googleusercontent.com',
clientSecret: 'k33p-gUeSsINg',
refreshToken: '123BritneyIsTheBest'
}),
tls: {
rejectUnauthorized: false
}
} );
To :
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'oauth2',
user: 'me#myDomain.com',
clientId: 'blahblahblah.apps.googleusercontent.com', // This key is "clientId".
clientSecret: 'k33p-gUeSsINg',
refreshToken: '123BritneyIsTheBest'
},
tls: {
rejectUnauthorized: false
}
});
Note :
Please confirm whether https://mail.google.com/ was included in the scope, when you retrieved the refresh token.
Please confirm whether gmail API is enabled.
It may be required to turn on "Allow less secure apps: ON" at https://myaccount.google.com/lesssecureapps.
Reference :
nodemailer OAuth2
In my environment, I confirmed that this works fine. But if this was not useful for you, I'm sorry.

Related

NodeMailer keeps timing out

I'm building my first node project and I'm trying to send mails to users using nodemailer and OAuth2.0. It did work last night but suddenly started timing out this morning no matter what, it runs for a few minutes and then times out without sending the mail.
This is my code so far
const nodemailer = require("nodemailer");
const sendEmail = async (email, subject, text) => {
try {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD,
clientId: process.env.OAUTH_CLIENTID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
refreshToken: process.env.OAUTH_REFRESH_TOKEN
}
});
await transporter.sendMail({
from: 'user#gmail.com',
to: email,
subject: subject,
text: text,
});
console.log("email sent sucessfully");
} catch (error) {
console.log(error, "email not sent");
}
};
and I'm calling the function this way await sendEmail(email, "Password reset", link)
I get this error message after a few minutes
Error: connect ETIMEDOUT 173.194.76.108:465
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
errno: -60,
code: 'ESOCKET',
syscall: 'connect',
address: '173.194.76.108',
port: 465,
command: 'CONN'
} email not sent
I would appreciate any help as I'm really frustrated already
I fixed this by adding this to the transporter object
host: 'smtp.gmail.com',
port: 587,
secure: false,

Why does nodemailer throw the error: Invalid credentials? [duplicate]

I would like to find a way to send email from my app using nodemailer to the users either with some kind of google authentication or any other way. Below mentioned working code has stopped working after Google has disabled less secure app option.
const nodemailer = require('nodemailer')
const sendEmail = async options => {
const transporter = nodemailer.createTransport({
// host: "smtp.gmail.com",
// port: "465",
// secure: true,
service:'gmail',
auth: {
user: "USER_EMAIL",
pass: "USER_PASSWORD"
},
tls:{rejectUnauthorized:false}
})
const message = {
from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
to: options.email,
subject: options.subject,
text: options.message,
html: options.message,
attachments: [
{
filename: '.png',
path: __dirname + '.png',
cid: '.png'
}
]
}
const info = await transporter.sendMail(message)
console.log('Message sent : %s', info.messageId)
console.log(__dirname)
}
module.exports = sendEmail
At the time of writing, Less Secure Apps is no longer supported by google. And you can't use your google account password.
You're gonna have to generate a new app password.
App passwords only work if 2-step verification is turned on.
Follow this steps to get the app password
Go to https://myaccount.google.com/security
Enable 2FA
Create App Password for Email
Copy that password (16 characters) into the pass parameter in Nodemailer auth.
const client = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "username#gmail.com",
pass: "Google-App-Password-Without-Spaces"
}
});
client.sendMail(
{
from: "sender",
to: "recipient",
subject: "Sending it from Heroku",
text: "Hey, I'm being sent from the cloud"
}
)
You should check out Xoauth2.
Nodmailer supports serval types of Oauth
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
type: "OAuth2",
user: "user#example.com",
clientId: "000000000000-xxx0.apps.googleusercontent.com",
clientSecret: "XxxxxXXxX0xxxxxxxx0XXxX0",
refreshToken: "1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx",
accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
expires: 1484314697598,
},
});

Using Webmail with Nodemailer

I used gmail with node mailer to create a login system in js node.
In development mode I used gmail.
const sendEmail = async options =>{
//1)Create a transporter
// const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_SEND_SESSION,
pass: process.env.EMAIL_SEND_PASSWORD,
}
});
//2) Define the mail options
const mailOptions = {
from:'Creative Point <test764#gmail.com>',
to:options.email,
subject:options.subject,
html:options.message
}
//3) Actually send the email
await transporter.sendMail(mailOptions);
};
But in production mode I would like to use webmail,I received when I created the data and port account on cpanel.
const transporter = nodemailer.createTransport({
service:'smtp.specialsoft.ro ',
port: 465,
auth: {
user: process.env.EMAIL_SEND_SESSIONCPANEL,
pass: process.env.EMAIL_SEND_PASSWORDCPANEL,
}
});
But it gives me the next mistake.
Error: There was an error sending the email.Try again later!Error: Invalid login: 535-5.7.8 Username
and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials g20sm3266545ejz.88 - gsmtp
at C:\Users\Cosmin\Desktop\Authentification System Node
JS,Express,JsonWebToken\controllers\sessionController.js:56:21
at processTicksAndRejections (internal/process/task_queues.js:93:5)
I haven't found anything relevant on the internet about this error.
I solved the problem by following the steps below.
I installed a module: nodemailer-smtp-transport.
const smtpTransport = require('nodemailer-smtp-transport');
I corrected the host name and some options.
host:'mail.mydomani.ro'
secureConnection: false,
tls: {
rejectUnauthorized: false
}
3)I integrated the module nodemailer-smtp-transport in the transporter.
const transporter = nodemailer.createTransport(smtpTransport({
host:'mail.mydomanin.ro',
secureConnection: false,
tls: {
rejectUnauthorized: false
},
port: 587,
auth: {
user: process.env.EMAIL_SEND_SESSION,
pass: process.env.EMAIL_SEND_PASSWORD,
}
}));

Send Email Using Microsoft 365 Email Server In NodeJS

let transporter = nodemailer.createTransport({
service: "Outlook365",
host: 'smtp.office365.com',
port: 587,
tls: {
ciphers:'SSLv3'
},
auth: {
user: 'username',
pass: 'password'
}
});
I have an EAUTH error while sending an email, please check the image for error.
[1]: https://i.stack.imgur.com/snt3T.jpg
This code should do what you wish, you'll need to set your password to test this.
If the password is incorrect, you'll get an error:
Error: Invalid login: 535 5.7.3 Authentication unsuccessful message.
const nodemailer = require('nodemailer');
// Set this from config or environment variable.
const PASSWORD = '....';
async function send365Email(from, to, subject, html, text) {
try {
const transportOptions = {
host: 'smtp.office365.com',
port: '587',
auth: { user: from, pass: PASSWORD },
secureConnection: true,
tls: { ciphers: 'SSLv3' }
};
const mailTransport = nodemailer.createTransport(transportOptions);
await mailTransport.sendMail({
from,
to,
replyTo: from,
subject,
html,
text
});
} catch (err) {
console.error(`send365Email: An error occurred:`, err);
}
}
send365Email("from#example.com", "to#example.com", "Subject", "<i>Hello World</i>", "Hello World");
You will need to disable the SmtpClientAuthenticationDisabled through the online power shell with the command
Set-TransportConfig -SmtpClientAuthenticationDisabled $false
You can check for more information at Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online
You can find the detailed information here:
https://developer.microsoft.com/en-us/graph/quick-start?code=M.R3_BAY.822b5ade-d816-85bb-ec94-8c349cdfca4b&state=option-node

nodemailer and zoho email issue '530 Must issue a STARTTLS command first.'

I am using the latest version of nodemailer version 4.1.0. I tried using the sample code available here
https://nodemailer.com/smtp/
Here is my code
let transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port:587,
secure: false,
auth: {
user: this.user,
pass: this.password
}
});
var mailOptions: nodemailer.SendMailOptions = {
from: ****#***.com,
to: test#abc.com,
subject: 'Hello ✔',
text: 'Hello world ✔',
html: '<b>Hello world ✔</b>'
};
transporter
.sendMail(mailOptions)
.then(
(info) => {
// console.log(info);
resolve({status: info.messageId})
}
)
.catch(err => {
// console.log(err);
reject({status: err.toString()})
})
I get the following error. I have set the secure flag as false, and have also used ignodeTLS. The previous version of nodemailer 0.7.1 did not have any issues. Am I missing out on any specific configuration?
{ Error: Invalid login: 530 Must issue a STARTTLS command first.
at SMTPConnection._formatError
(C:\Project\NotificationService\node_modules\nodemailer\lib\smtp-connection\index.js:577:19)
at SMTPConnection._actionAUTHComplete (C:\Project\NotificationService\node_modules\nodemailer\lib\smtp-connection\index.js:1306:34)
at SMTPConnection._responseActions.push.str (C:\Project\NotificationService\node_modules\nodemailer\lib\smtp-connection\index.js:349:26)
at SMTPConnection._processResponse (C:\Project\NotificationService\node_modules\nodemailer\lib\smtp-connection\index.js:733:20)
at SMTPConnection._onData (C:\Project\NotificationService\node_modules\nodemailer\lib\smtp-connection\index.js:529:14)
at Socket._socket.on.chunk (C:\Project\NotificationService\node_modules\nodemailer\lib\smtp-connection\index.js:481:47)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:548:20)
code: 'EAUTH',
response: '530 Must issue a STARTTLS command first.',
responseCode: 530,
command: 'AUTH PLAIN' }
you can also use this without these tls parameter default value is false.
you got the error because of you don't pass service:'zoho' in nodemailer
let transporter = nodemailer.createTransport({
service:'Zoho',
host: this.service,
port:587,
secure: false,
auth: {
user: this.user,
pass: this.password
}
});
After going through the typings( "#types/nodemailer") file I added the following flags
1) service :'Zoho'
2) requireTLS :false
it is working now :)
let transporter = nodemailer.createTransport({
service:'Zoho',
host: this.service,
port:587,
secure: false,
ignoreTLS:true,
requireTLS:false,
auth: {
user: this.user,
pass: this.password
}
});
In the year 2022, I got this on the official documentation https://nodemailer.com/smtp/well-known/
let transporter = nodemailer.createTransport({
service: 'SendPulse', // no need to set host or port etc.
auth: {
user: 'account.email#example.com',
pass: 'smtp-password'
}
});
transporter.sendMail(...)
So, for Zoho just simply:
let transporter = nodemailer.createTransport({
service: 'Zoho', // no need to set host or port etc.
auth: {
user: 'account.email#example.com',
pass: 'smtp-password'
}
});
transporter.sendMail(...)
Just test it and works. I believe it doesn't need to put any setting if we use "Well-known services"
Hope this helps someone drop by in this thread :).

Resources