Create SMTP Server to send, receiving E-mails (custom domain) - node.js

I gonna to create SMTP Server to send, receiving E-mails, using nodemailer
I have a custom domain from namecheap to do this
tried use this code but i don't receive any email on my Gmail account
const nodemailer = require('nodemailer');
const { SMTPServer } = require("smtp-server")
const server = new SMTPServer({
onData(stream, session, callback) {
console.log('test')
},
disabledCommands: ['AUTH'],
secure: false
});
server.listen(25)
const transporter = nodemailer.createTransport({
host: '192.168.1.2',
port: 25,
secure: false,
auth: {
user: '',
pass: ''
},
tls: {
rejectUnauthorized: false
}
});
transporter.sendMail({ from: "support#myDomain.com", to: "myGmail#gmail.com", text: "text", subject: "subject" })
.then(info => {
console.log(info)
}).catch(err => {
console.log(err)
})
log error:
test
Error: Message failed: 421 Timeout - closing connection
There any method to create smtp server using node js for send, receiving E-mails?

Related

response: '535-5.7.8 Username and Password not accepted. Learn more at\n'

My Node js code is sending proper email on localhost but in backend there showing email and password not valid ?
const nodemailer = require("nodemailer");
const sendEmail = async (subject, message, send_to, sent_from, reply_to) => {
// Create Email Transporter
const transporter = nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
// Options for sending email
const options = {
from: sent_from,
to: send_to,
reply_to: reply_to,
subject: subject,
html: message,
};
// Check email sent successfully or not
transporter.sendMail(options, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
};
module.exports = sendEmail;

"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

Nodejs Nodemailer not sending e-mail

I'm using nodemailer to send email validations with no success, I get no errors when sending the e-mail, it actually says the e-mail was sent but I recieve nothing.
I tried sending e-mails using this e-mail (with gmail integration) and it works fine.
This is my config
import Mailer from "nodemailer";
async function sendEmail(emailData) {
const SMTP = process.env.EMAIL_SMTP;
const SENDER = Mailer.createTransport({
host: SMTP,
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_SENDER,
pass: process.env.EMAIL_SENDER_PASSWORD
},
tls: {
ignoreTLS: true
}
});
const RECEIVER = {
from: process.env.EMAIL_SENDER,
to: emailData.to,
subject: emailData.subject,
text: emailData.text,
};
SENDER.sendMail(RECEIVER, function (error) {
if (error) {
console.log(error);
} else {
console.log("E-mail sent"); // E-mail sent is fired at console
}
});
await SENDER.verify(function (err, success) {
console.log({ err, success }); // {err: null, success: true}
})
}
I'm trying to send this using local env, does this work locally or the SMTP should match my domain?

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.

SMTP using nodemailer in nodejs without GMail

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

Resources