whenever i run the code I'm getting the error " Error: Greeting never received at SMTPConnection._formatError...."
function automatedMailSender(req,res){
var mailOptions = {
from: "abc <abc#test.com>", // sender address
to: 'nit#test.com', // list of receivers
subject: 'Hello ', // Subject line
text: 'Hello world ?', // plain text body
html: '<b>Hello world ?</b>' // html body
};
var mailer=nodemailer.createTransport({
host: 'mail.test.com',
port: 465,
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'mymail#test.com',
pass: '1234'
}
});
mailer.sendMail(mailOptions, (error, response)=>{
if(error){
console.log('mail not sent \n',error);
}
else{
console.log("Message sent: " ,response.message);
}
});
}
I'm I doing something wrong in the code.
The answer in right in your code
port: 465,
secure: false, // secure:true for port 465, secure:false for port 587
The value for "secure" should be true for port 465
If you are using Gmail to send mails then try this.
Allow less secure apps to connect to Gmail.
Try something like that, it work perfectly for me:
//Create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(
'smtps://USERNAME%40gmail.com:PASSWORD#smtp.gmail.com');
// setup e-mail data
var mailOptions = {
from: '"Michel 👥" <recipe#example.com>', // sender address
to: 'bernard#example.com', // list of receivers
subject: 'Hello', // Subject line
text: 'Bonjour!' // plaintext body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
If is still doesn't work you have a little tuto here
var mailer=nodemailer.createTransport({
host: 'mail.test.com',
port: 465,
secure: true, // secure:true for port 465, secure:false for port 587
transportMethod: 'SMTP',
auth: {
user: 'mymail#test.com',
pass: '1234'
}
});
The value for secure should be true for port 465 and use transportMethod: 'SMTP'
const express = require('express');
const router = express.Router();
const { Email } = require('../models/email.model');
const { User } = require('../models/user.model');
const nodemailer = require('nodemailer');
//post email
router.post('/send', async (req, res) => {
if (req.query) {
var query = {}
if (req.query.lastname) { query.lastname = req.query.lastname }
if (req.query.firstname) { query.firstname = req.query.firstname }
if (req.query.email) { query.email = req.query.email }
if (req.query.isactive) { query.isActive = req.query.isactive }
if (req.query.isgain) { query.isGain = req.query.isgain }
}
const email = new Email({
title: req.body.title,
subject: req.body.subject,
text: req.body.context,
description: req.body.description
});
if (req.body.title && req.body.subject && req.body.context) {
const user_db = await User.find(query)
const user_db_email = user_db.map(x => x.email)
var smtpTransport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: { user: 'ghiles#gmail.com', pass: 'g' },
tls: { rejectUnauthorized: false }, // do not fail on invalid certs
});
var mailOptions = {
to: user_db_email,
from: 'fatb#gmail.com',
subject: req.body.subject,
text: req.body.context
};
email.save().then(() => {
smtpTransport.sendMail(mailOptions)
.then(() => res.status(200).json(email))
.catch(() => res.status(500).json({ success: false, message: `erreur dans l'envoi de mail` }))
}).catch(() => res.status(200).json({ success: false, message: `erreur dans le serveur` }))
} else {
res.status(400).json({ success: false, message: `Veuillez renseigner le titre et l'objet et le contexte du mail` })
}
module.exports = router;
tls:{
rejectUnauthorized:false
}
fixed it by using the above code in mailer variable.
Thanks guys
host: 'smtp.host.com',
port: 587, // 587 or 25 or 2525
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'mymail#test.com',
pass: '1234'
}
Try this. prefixing smtp and changing the port.
Related
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;
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
I'm trying to set up nodemailer for an app. I'm receiving an error when I try it.
This is my setup:
email = setting.email;
password = setting.password;
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '***********#gmail.com', // real email
pass: '*********' // real password
}});
// var transporter = nodemailer.createTransport({
// service: 'gmail',
// auth: {
// user: email, // Your email id
// pass: password // Your password
// }
// });
var mailOptions = {// sender address
from: email,
to: to, // list of receivers
subject: sub, // Subject line
text: text, //, /// plaintext body
html: html
}
//console.log(JSON.stringify(mailOptions));
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.error(error);
} else {
console.log(info.response);
}
;
});
});
} catch (error) {
console.error(error);
}
This is the first time I've tried using nodemailer. I am using real email and password. The error are:
(node:18974) [DEP0025] DeprecationWarning: sys is deprecated. Use util
instead. Magic happens on port 5000 ERROR! ERROR! ERROR! ERROR!
provider_analytic_daily saved. { Error: Connection timeout
at SMTPConnection._formatError (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:528:15)
at SMTPConnection._onError (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:514:16)
at SMTPConnection. (/root/faszz/node_modules/smtp-connection/lib/smtp-connection.js:236:14)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5) code: 'ETIMEDOUT', command: 'CONN' }
functionObj = {};
functionsObj.getSmtpTransport = function() {
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "<your email address>",
pass: "<your pass>"
}
});
return smtpTransport;
}
functionsObj.sendMailForPasswordReset = function(to, token) {
var smtpTransport = functionsObj.getSmtpTransport();
var mailOptions = {
to: to,
subject: "Blabla.com Reset Password",
html: "Hi,<br> Click to link for resetting password.<br><a href='https://<blabla.com>/reset/" + urlencode(token) + "'>Click Me !!!</a>"
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
return error;
}
else {
return true;
}
});
};
Hi,
The code above worked in my project without any error. But you should allow to third party softwares to use your google account from google.
Here the google's support page for this case:
https://support.google.com/accounts/answer/6010255?hl=en
I recommend that all input should be validated :) For example if you are taking "to" parameter from user. You should validate "to" parameter is a valid email address ?
I have nodejs get request which need to send the base 64 string as image in the email which as shown below
router.post('/sendEmailNotification', function(req, res, next){
var inlineBase64 = require('nodemailer-plugin-inline-base64');
//here i have big image
let img ='/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBx'
var transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 587,
secure: false,
// secure: true,
secureConnection: false,// true for 465, false for other ports
auth: {
user: 'dhanalakshmi.07k#gmail.com',
pass: '23'
},
tls:{
rejectUnauthorized:false
}
});
transporter.use('compile', inlineBase64({cidPrefix: 'somePrefix_'}));
var mailOptions = {
from: 'dhanalakshmi.06k#gmail.com',
to: 'dhanalakshmi.06k#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!',
html: '<img src=data:image/png;base64,'+img+'/>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
res.send(info.response);
}
});
});
after the email send this should received as image but it showing the entire tag with image string please say
html: '<img src=data:image/png;base64,'+img+'/>' how should i send this to get the actual image
Use it like this:
html: '<html><body><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA9QAAADmCAIAAAC77FroAAAAAXNSR0IArs4c6QAAAAlwSFlzAAAO..."></body></html>'
I'm trying to build an app that sends an email when something is triggered.
I'm not getting any errors, but getting no emails to my inbox.
This is the code:
SMTP:
var SMTPServer = require('smtp-server').SMTPServer;
var server = new SMTPServer({
secure: false, authOptional: true
});
server.listen(465);
emailjs:
var email = require('emailjs');
var emailServer = email.server.connect({
host: 'localhost',
port: 465,
ssl: false
});
emailServer.send({
text: 'Hey howdy',
from: 'NodeJS',
to: 'Wilson <person#gmail.com>',
cc: '',
subject: 'Greetings'
}, function (err, message) {
console.log(err || message);
});
The output I see on my console is:
{ attachments: [],
alternative: null,
header:
{ 'message-id': '<1470995427701.0.2864#DESKTOP-M85CNRC>',
date: 'Fri, 12 Aug 2016 12:50:27 +0300',
from: '=?UTF-8?Q?NodeJS?= <>',
to: '=?UTF-8?Q?Wilson?= <person#gmail.com>',
cc: '',
subject: '=?UTF-8?Q?Greetings?=' },
content: 'text/plain; charset=utf-8',
text: 'Hey howdy' }
Any idea about what's missing?
Thanks
i am using nodemailer-smtp-transport and is working perfectly for me, follow is my configuration inside the function through which i am sending mail. Hope this may help.
var nodemailer = require('nodemailer'),
smtpTransport = require("nodemailer-smtp-transport");
//configuration
var transporter = nodemailer.createTransport(smtpTransport ({
auth: {
user: user, //email of sender
pass: pass //password of sender
},
host: host, //my email host
secureConnection: true,
port: 587,
tls: {
rejectUnauthorized: false
},
}));
var mailOptions = {
from: user,
to: to,
subject: subject,
text: text
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log("success");
}
});
In emailjs file host cannot be localhost it should be like :smtp.your-email.com.
var server = email.server.connect({
user: "username",
password:"password",
host: "smtp.your-email.com",
ssl: true
});
I use an Gmail account not very important for my tests in stead of module smtp-server.
First: Required activate the use less secure apps at your own risk as indicated in the Gmail documentation:
https://myaccount.google.com/u/2/lesssecureapps?pageId=none
After:
var email = require("emailjs");
var server = email.server.connect({
user: "YOUR_ACCOUNT#gmail.com",
password:"YOUR_PASSWORD",
host: "smtp.gmail.com",
ssl: true
});
server.send({
text: "Hello world",
from: "YOUR_NAME <YOUR_ACCOUNT#gmail.com>",
to: "FRIEND_NAME <FRIEND_ACCOUNT#gmail.com>",
subject: "Hello"
}, function(err, message) { console.log(err || message); });