SMTP using nodemailer in nodejs without GMail - node.js

I am using node mailer with GMail
smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "myemail ",
pass: "mypass"
}
});
which is working fine, but I want to use my own email server instead of GMail.
This:
smtpTransport = nodemailer.createTransport("SMTP", {
service: "mymailservr link url",
port : 25
auth: {
user: "myemail ",
pass: "mypass"
}
});
It throws this error:
connect ECONNREFUSED

The service option is only for well-known services. To specify your own host, set host.
var smtpTransport = nodemailer.createTransport('SMTP', {
host: 'yourserver.com',
port: 25,
auth: {
user: 'username',
pass: 'password'
}
});

make sure you have the latest NodeMailer version installed
as of today (15-jan-2020) it is v6.4.2
npm install nodemailer --save
This should work:
const nodemailer = require('nodemailer');
let transporter = nodemailer.createTransport({
host: 'smtp.server.com', // <= your smtp server here
port: 2525, // <= connection port
// secure: true, // use SSL or not
auth: {
user: 'userId', // <= smtp login user
pass: 'E73oiuoiC34lkjlkjlkjlkjA6Bok7DAD' // <= smtp login pass
}
});
let mailOptions = {
from: fromEmailAddress, // <= should be verified and accepted by service provider. ex. 'youremail#gmail.com'
to: toEmailAddress, // <= recepient email address. ex. 'friendemail#gmail.com'
subject: emailSubject, // <= email subject ex. 'Test email'
//text: emailData.text, // <= for plain text emails. ex. 'Hello world'
html: htmlTemplate // <= for html templated emails
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error.message);
}
console.log('Message sent: %s', info.messageId);
});
Hope this helps,
Thank you.

var nodemailer = require('nodemailer');
var smtpTransport = require("nodemailer-smtp-transport");
var transporter = nodemailer.createTransport(smtpTransport({
host : "example.com",
port: 25,
auth : {
user : "username",
pass : "password"
}
}));

Related

"Invalid login: 535-5.7.8 Username and Password not accepted" while sending mail from nodejs using office 365 mail

I am getting error "Invalid login: 535-5.7.8 Username and Password not accepted" while trying to send mail using nodejs.
Below is my configuration
this._transport = nodemailer.createTransport({
service: 'Outlook365',
name: 'smtp.office365.com',
host: 'smtp.office365.com', // Office 365 server
port: '587',
secure: false,
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD,
},
secureConnection: false,
tls: { ciphers: 'SSLv3' }
})
and while sending the mail
var mailOptions = {
from: `Admin<${settingObj.Contact_Email}>`,
to: req.body.email,
subject: "Subject",
html: 'Hello ' + '<b>' + req.body.email + '<br>Thank You for contacting'
};
var sendMail = await transporter.sendMail(mailOptions);
below is sendmail function
async sendMail(from, to, subject, tplName, locals) {
try {
const mailer = new Mailer();
const templateDir = path.join(__dirname, "../views/", 'email-templates', tplName + '/html')
const email = new Email({
message: { from: from },
transport: { jsonTransport: true },
views: { root: templateDir, options: { extension: 'ejs' } }
});
let getResponse = await email.render(templateDir, locals);
if (getResponse) {
let options = { from: from, to: to, subject: subject, html: getResponse };
let mailresponse = await mailer._transport.sendMail(options);
if (mailresponse) {
return true;
}
else {
return false;
}
}
}
catch (e) {
console.log("44>>", e.message);
return false;
}
};
Before doing anything, ensure you are able to log in to your office 365 account with your username and password.
if you're facing this error in a hosted app, make sure you've created the env variables in config-vars/parameter-store/secrets or whichever is applicable for the platform?
Use telnet to access your office 365 SMTP account, doing so, you can get to know if it's a problem with your code or the settings.
Here is my working code,
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
app.get('/', (req, resp)=>{
const email = `
<h3>Hello dee.....</h3>
<ul>
<li>Name: Deepak </li>
<li>Email: dee#dee.com </li>
</ul>
<h2>Message<h2>
<p>Wassup....howdeeee</p>
`
let transporter = nodemailer.createTransport({
host: "smtp.office365.com",
port: '587',
auth: {
user: '....',
pass: 'blahhhhh'
},
secureConnection: false,
tls: { ciphers: 'SSLv3' }
});
transporter.sendMail({
from: '.....',
to: '.....',
subject: 'Test for twix',
text: 'hello twix',
html: email
}).then(res=>{
console.log("success........", res)
resp.send("yeahhhhhhhh", res);
}).catch(e=>{
console.log("failed........", e)
});
});
app.listen(5000, console.log("Server listening to 6k"));
I enabled two-factor authentication and logged out of all active sessions then tried again, it worked fine with the above code.
Updated answer in response to comments
const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
app.get('/send', async (req, resp) => {
let transporter = nodemailer.createTransport({
host: "smtp.office365.com",
port: '587',
auth: {
user: '......',
pass: '......'
},
secureConnection: false,
tls: { ciphers: 'SSLv3' }
});
var mailOptions = {
from: '.......',
to: '.......',
subject: "Twix mailer",
html: 'Hello ' + '<b>' + 'deechris27' + '<br>Thank You for contacting'
};
let sendMail = await transporter.sendMail(mailOptions);
console.log("twix email.....", sendMail.response);
});
app.listen(5000, console.log("Server listening to 5k"));
Success message below
Suggested changes
this._transport = nodemailer.createTransport({
service: 'Outlook365', // remove this
name: 'smtp.office365.com', // not needed
host: 'smtp.office365.com',
port: '587',
secure: false, // remove this
auth: {
user: process.env.MAIL_USERNAME, // hardcode username to try
pass: process.env.MAIL_PASSWORD, // hardcode pwd to try in local
},
secureConnection: false,
tls: { ciphers: 'SSLv3' }
});
comment out sendMail(from, to, subject, tplName, locals) function. Where is this called? this appears to be like you're trying to do what Nodemailer does internally. Though it wouldn't throw an invalid login error, I advise you to comment out for debugging.
I got the email "Hello deechris27 Thank You for contacting" to my inbox when this
let sendMail = await transporter.sendMail(mailOptions); promise was resolved.
createTransport of nodemailer returns an instance of Mailer which provides the sendMail function. The "From" address in mailOptions should be same as the auth.user.
I'm using Nodemailer Version 6.6.3. Refer to node_modules -> nodemailer -> lib -> nodemailer.js for more clarity.
Helpful Resources:
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/concept-fundamentals-security-defaults
https://answers.microsoft.com/en-us/outlook_com/forum/all/i-cant-send-e-mails-from-my-server-through-office/999b353e-9d4f-49b2-9da9-14d6d4e6dfb5
On your Outlook dashboard, you need to allow less secure apps from your outlook account to send emails. Through this link. Allow less secure apps

How to send mail using Nodemailer in Node.js

I tried to send e-mail using Nodemailer in Node.js but it is not working. I don't know why it is not working. If anyone knows, please help, to find the solution.
Getting this error:
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 9sm14519585pfh.160 - gsmtp
data.controller.js:
const nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mygmail#gmail.com',
pass: 'mypass'
}
});
let mailOptions = {
from: "mygmail#example.com", // sender address
subject: "Hello ✔", // Subject line
text: "Hello This is an auto generated Email for testing from node please ignore it", // plaintext body
to: "togmail#gmail.com"
}
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
const nodemailer = require('nodemailer');
const email = 'myemail#gmail.com';
const password = '**********';
You should set smtp host as smtp.gmail.com.
You can set smtp port number as 587 or 465.
587 is tls and 465 is ssl.
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: `${email}`,
pass: `${password}`
}
});
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
var mail = 'message';
const from_email = 'sender#email.com';
const to_email = 'receiver#email.com';
var mailOptions = {
from: email,
to: to_email,
subject: 'Your subject',
text: mail
};
}
});
I used above code, so that I sent mail.
Please try this.

Nodemailer - Missing credentials for "PLAIN"

I am working with node.js and tried sending email via Nodemailer but I'm getting this error:
Missing credentials for "PLAIN"
function(token, user, done) { //sends mail
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'aimanmumtazxyz#gmail.com',
pass: process.env.GMAILPW
}
});
Any help anybody?
const nodemailer = require("nodemailer");
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: userName, // Enter your userName or email
pass: password // Enter your password
}
});
// send mail with defined transport object
await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: "bar#example.com, baz#example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>" // html body
}, (err, info)=>{
if (err) {
throw new Error(err)
} else {
console.log('Email sent: ' + info.response);
}
});
For more information about nodemailer, please check this link: https://nodemailer.com/about/
For sending an email by Gmail, please check this link: https://nodemailer.com/usage/using-gmail/

sending email via nodemailer not working

I have a simple piece of code which is not working as expected. I am using nodemailer.
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'personal gmail address',
pass: 'password'
}
});
var mailOptions = {
from: 'personal gmail address',
to: 'personal gmail address',
subject: 'Hello world!',
text: 'Plaintext message example.'
};
smtpTransport.sendMail(mailOptions, function(err) {
console.log('Message sent!');
});
I am getting the Message Sent in console. But no emails in inbox.
For gmail service I use this :
const smtpTransport = require('nodemailer-smtp-transport')
const nodemailer = require('nodemailer')
const transport = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'pass'
}
}))
But you need to allow less secure authentication on your gmail account or emails are not sent.
I think the steps are :
Go to : https://www.google.com/settings/security/lesssecureapps
set the Access for less secure apps setting to Enable
Found this SO: self signed certificate in certificate chain error in mail .
I needed to add this and it worked for me.
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myemail#gmail.com',
pass: 'password'
},
tls: {
rejectUnauthorized: false
}
});
Can you check for the error message.
...
smtpTransport.sendMail(mailOptions, function(err) {
if(err)
{
console.log(err);
}
else
{
console.log('Message sent!');
}
});
Because in the sample code you had, even if the nodemailer returns valid error, it will still print Message Sent
Some times message can be queued or say any type of error in the mailOptions, the message cant be delivered.

Nodemailer without Gmail

I'm using NodeJS and I want to configure my email account with Nodemailer.
All the Nodemailer examples that I found are for Gmail...
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'gmail.user#gmail.com',
pass: 'userpass'
}
});
How can I put another service? In special I bought a email domain in ovh (SSL0.OVH.NET) and I interested to configure this email account.
I tried but I don't found the way to get this...
Thank you!
I create a module Mail for send html mails by SMTP
exports.send = function(email, subject, htmlcontent, callback) {
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var configMail = require('../bin/config').mail;//my json configurations mail
var transporter = nodemailer.createTransport(smtpTransport({
host: configMail.host, //mail.example.com (your server smtp)
port: configMail.port, //2525 (specific port)
secureConnection: configMail.secureConnection, //true or false
auth: {
user: configMail.auth.user, //user#mydomain.com
pass: configMail.auth.pwd //password from specific user mail
}
}));
var mailOptions = {
from: configMail.email,
to: email,
subject: subject,
html: htmlcontent
};
transporter.sendMail(mailOptions, function(err, info){
transporter.close();
if(err) {
callback(err, info);
}
else {
callback(null, info);
}
});
}
The usage:
var Mail = require('../utils/Mail'); //require this module
Mail.send('[EMAIL TO SEND]', '[TITLE]', '[YOUR HTML TEMPLATE MAIL]', function(err, info) {
if(err) {
//error
}
else {
//Email has been sent and you can see all information in var info
}
});
On creating an email id in the domain (mostly through c panel), check the mail configurations for that mail address and look for SMTP details such as port, username, etc. Then enter those details in the nodemailer transporter. For example, my transporter details were:
const transporter = nodemailer.createTransport({
host: "mail.schoolprogramming.tech",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: "demo#schoolprogramming.tech",
pass: "**************"
}
});

Resources