How to connect to Gmail using node.js imapflow? - node.js

I'm using imapflow package like this:
import config from './config.js';
import { ImapFlow } from 'imapflow';
const client = new ImapFlow({
host: 'imap.gmail.com',
port: 993,
secure: true,
auth: {
user: 'muhemail#gmail.com',
pass: '123'
}
});
await client.connect();
console.log('OK');
And it throws with Invalid credentials (Failure). I've quadruple-checked that login and password are correct, IMAP is enabled in GMail settings. Less than secure apps aren't enabled though, and I'd prefer to keep it that way. When I try to use the same credentials in Thunderbird, it opens an OAuth login window, which I suppose I should somehow incorporate with imapflow? Or is there a different solution?

Gmail does not allow accessing its IMAP services by using plain username and password.
You should first get OAuth2.0 credentials via the Gmail api example (here) and then should convert it to xoauth2.
let {installed: {client_id, client_secret}} = require('./client_secret') // the client_secret.json file
let xoauth2gen = xoauth2.createXOAuth2Generator({
user: '*******', // the email address
clientId: client_id,
clientSecret: client_secret,
refreshToken: refresh_token
})
xoauth2gen.getToken(function(err, xoauth2token) {
if (err) {
return console.log(err)
}
let imap = new Imap({
xoauth2: xoauth2token,
host: 'imap.gmail.com',
port: 993,
tls: true,
authTimeout: 10000,
debug: console.log,
})

Related

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,
},
});

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 Godaddy, I've tried every solution to no avail

I bought a domain and an email adrees with GoDaddy with Office 365 Basic bundled with it.
I'm trying from a few days to send just an email with nodemailer from my node app without ever succeding because I always get a 535 Authentication Failed from user#domain.com.
I've scanned StackOverflow for days trying every solution, this is every setting I've tried to pass to nodemailer.createTransport:
const mailerConfig =
{
//First set of parameters tried
service: 'Godaddy',
host: "smtp.office365.com",
secureConnection: true,
port: 587,
auth:
{
user: "user#domain.com",
pass: "password"
}
//Second set of parameters tried
host: "smtp.office365.com",
secureConnection: false,
port: "587",
auth:
{
user : "user#domain.com",
pass : "password"
},
tls:
{
ciphers:'SSLv3'
}
//Third set of parameters tried
service: "outlook",
auth:
{
user: 'user#domain.com',
pass: 'password'
}
}
None of these three settings worked, someone has any idea?
Thanks.
There is a godaddy FAQ entry called "Manually configure email set up on Thunderbird" (which seems to be only accessible via WaybackMachine).
It mentions the following configuration:
Incoming (IMAP): imap.secureserver.net 993 SSL Normal password
Outgoing (SMTP): smtpout.secureserver.net 465,587 SSL Normal password
and
Username: Workspace Email address
Using the above, especially smtpout.secureserver.net as SMTP Host works for me – tested with godaddy email in 2021.
If anyone is still having issues, this config is working for me actually in Sept 2021:
var transporter = nodemailer.createTransport({
host: "smtpout.secureserver.net",
port: 587, // port for secure SMTP
auth: {
user: "youremailaddress",
pass: "yourpassword",
},
});
You need to enable all access
and don't forget to disable the sms/call confirmation for the login
by the way this code i used on firebase cloud function/nodemailer
cors(req, res, async () => {
var transporter = nodemailer.createTransport({
host: "smtp.office365.com",
port: 587, // port for secure SMTP
auth: {
user: "user#domain.com",
pass: "password",
},
tls: {
ciphers: 'SSLv3'
}
});
if (req.method === 'POST') {
var mailOptions = {
from:req.body.from,
to: req.body.email, // list of receivers
subject: req.body.subject, // Subject line
text: req.body.text,
};
return transporter.sendMail(mailOptions).then(() => {
res.status(200).send('Email has been sent to mr/ms : ' + req.body.email); return ("mail sent")
});
}
})
You must enable SMTP login for the O365 mailbox or user in the admin settings
If the user has multifactor turned on, then you need to use "app password", normal password won't work if MFA is enabled.
https://learn.microsoft.com/en-us/azure/active-directory/user-help/multi-factor-authentication-end-user-app-passwords
You need to disable security defaults or adjust Conditional Access policies.
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/concept-fundamentals-security-defaults
Also, you can debug issue using sign-in logs in azure user account.

NodeJS - nodemailer using nodemailer-smtp-transport

I'm having an issue getting nodemailer to work with AuthSMTP (https://www.authsmtp.com/).
var nodemailer = require('nodemailer');
var transOptions = {
host: 'mail.authsmtp.com',
port: 25,
secure: false,
auth: {
user: '...',
pass: '...'
}
};
var transporter = nodemailer.createTransport(transOptions);
var mainOptions = {
from: 'whatever#domain.com',
to: 'something#domain.com',
subject: 'hello',
text: 'hello world!'
};
var callback = function(err, info){
if (err) { throw err }
console.log('sent');
}
transporter.sendMail(mainOptions, callback);
The error I'm getting back from AuthSMTP is:
"Your program, application or device is trying to use SSL with our
service but SSL is not enabled on your account."
I don't want to enable SSL, and I have the secure property in the transport options object set to false as the docs say: https://github.com/andris9/nodemailer-smtp-transport#usage.
Why would AuthSMTP say I'm using SSL when I'm setting nodemailer not to use SSL...?
you may try this
var transOptions = {
host: 'mail.authsmtp.com',
port: 25,
secure: false,
ignoreTLS: true
auth: {
user: '...',
pass: '...',
}
secure – if true the connection will use TLS when connecting to
server. If false (the default) then TLS is used if server supports the
STARTTLS extension.
In most cases set this value to true if you are connecting to port 465. For port 587 or 25 keep it false.
ignoreTLS – if this is true and secure is false then TLS is not used
even if the server supports STARTTLS extension.
so, params like this:
secure: false, ignoreTLS: true,
If you want to be safe, I think just to set you email, start IMAP/SMTP and POP/SMTP service as below:
and add your pass on your email settings:

Error sending email using nodemailer via Office365 smtp (MEANjs scaffold)

I'm trying to use Office365 SMTP to send email using Nodemailer (in a MEANjs scaffold), but I get the following error:
[Error: 140735277183760:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:795:]
I'm using the following Nodemailer options:
{
host: 'smtp.office365.com',
port: '587',
auth: { user: 'xxxx', pass: 'xxxx' },
secure: 'false',
tls: { ciphers: 'SSLv3' }
}
Removing the tls field doesn't make a difference. What am I missing?
The solution was simple. The 'secure' field should be 'secureConnection'. The MEANjs scaffold that generated the configs created mailer options with the 'secure' field. The rest of the options are fine. For anyone that needs a working Office365 SMTP nodemailer options block, the following should work:
{
host: 'smtp.office365.com',
port: '587',
auth: { user: 'xxxx', pass: 'xxxx' },
secureConnection: false,
tls: { ciphers: 'SSLv3' }
}
I know this is old but if anyone looks this up in 2019, you can just add
service: "Outlook365"
and you won't have to specify connection options.
Node Mailer Docs
let transporter = nodemailer.createTransport({
service: "Outlook365",
auth: {
user: 'FROMUSER#office365.com',
pass: 'FROMUSERPASS'
},
})
let info = transporter.sendMail({
from: 'FROMUSER#office365.com',
to: 'TOUSER#office365.com',
subject: 'Test',
text: 'hello world',
html: '<h1>TEST</h1>'
})
This nodemailer documentation https://nodemailer.com/2-0-0-beta/setup-smtp/ indeed states options.secure and not options.secureConnection. It also suggests, in an example, that options.secure is expecting a boolean value true or false and not a string value 'true' or 'false'. Removing the '' from around 'false' works for me.
My problem was that the username and password were spelled correctly but I did not login in the Account after creation. So I used a mail program (Thunderbird) to login once and had to change my password and then I had access over Nodemailer.

Resources