Nodemailer with email-templates not sending email - javascript

I'm using nodemailer with npm package email-templates. I'm not getting email. Template is working when i set preview:true. Getting error on console Error: No recipients defined.Why this error coming? Tried many things but nodemailer is sending empty email every time. Hope you understand my issue.
Error:
Error: No recipients defined
at SMTPConnection._formatError (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:784:19)
at SMTPConnection._setEnvelope (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:995:34)
at SMTPConnection.send (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:615:14)
at sendMessage (E:\testing\node_modules\nodemailer\lib\smtp-transport\index.js:227:28)
at E:\testing\node_modules\nodemailer\lib\smtp-transport\index.js:285:25
at SMTPConnection._actionAUTHComplete (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:1537:9)
at SMTPConnection.<anonymous> (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:550:26)
at SMTPConnection._processResponse (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:942:20)
at SMTPConnection._onData (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (E:\testing\node_modules\nodemailer\lib\smtp-connection\index.js:195:44)
at TLSSocket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:182:23) {
code: 'EENVELOPE',
command: 'API'
}
My directory structure:
├── app.js
└── emails
└── forget-password
├── html.pug
├── subject.pug
Node mailer with template:
const nodemailer = require('nodemailer');
var generator = require('generate-password');
const Email = require('email-templates');
exports.sendNodeForgotPasswordMail = function (email, GeneratePassword) {
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'my_email',
pass: 'my_password'
},
tls: {
rejectUnauthorized: false
}
});
const emailVar = new Email({
message: {
from: 'testing#gmail.com'
},
preview: true,
send: true,
transport: {
jsonTransport: true
}
});
emailVar.send({
template: 'forget-password',
message: {
to: email
},
locals: {
password: GeneratePassword
}
}) .then(res => {
console.log('res.originalMessage', res.originalMessage)
}).catch(console.error);
return transporter.sendMail(emailVar, function (err, info) {
if (err)
console.log(err);
else
console.log(info);
});
};
Html.pug:
p Your new password is: #{password}
subject.pug
= `Password reset request`

the reason is that you dont need to require nodemailer instead of make your transporter with nodemailer you need to pass it in JSON like so.
exports.sendNodeForgotPasswordMail = function (email, GeneratePassword) {
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'my_email',
pass: 'my_password'
},
tls: {
rejectUnauthorized: false
}
});
becomes:
transport: {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'my_email',
pass: 'my_password'
},
tls: {
rejectUnauthorized: false
}
}
const Email = require('email-templates'); <-- with this is enough.

If anyone else is looking how to solve this, i manage to make it work based on #Irving Caarmal answer and the code is the following:
function sendTokenEmail(userEmail, token, templateName) {
const email = new Email({
message: {
from: 'someemail#gmail.com',
},
preview: true,
send: true,
transport: {
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
},
},
})
return email
.send({
template: templateName,
message: {
to: userEmail,
},
locals: {
token,
},
})
.then((res) => {
console.log('res.originalMessage', res.originalMessage)
})
}

if anyone has an issue with getting on their email address the mail generated you should add at the level with send: true also the option preview: false (PS: this worked for me) without having the preview set to false the email would not come even if the docs say:
If you want to send emails in development or test environments, set options.send to true.
Example:
const email = new Email({
message: {
from: process.env.SMTP_USER,
},
send: true,
preview: false,
transport: {
host: process.env.SMTP_HOST,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
},
})
await email.send({
template: 'template-of-choice',
message: {
from: 'email-address'
},
locales: {}
})
Hope it helps :)

Related

nodemailer - can't send mail with rediffmail

I'm trying to send mail from rediffmail using nodemailer
Here's the code snippet
var transporter = nodemailer.createTransport({
host: "smtp.rediffmail.com", // hostname
port:25, secureConnection: false,
secure: false,
tls: {
ciphers: "SSLv3",
},
auth: {
user: process.env.MAILADDRESS,
pass: process.env.MAILPASS,
},
});
var mailOptions = {
from: process.env.MAILADDRESS,
to: email,
subject: "Sending using Node.js",
html: "<h1>hoohaa</h1>That was eafefesy!",
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err);
} else {
console.log(
`Password recovery Email sent to ${email} : ${info.response}`
);
}}
and the error which I get is :
{ errno: -4039, code: 'ESOCKET', syscall:
'connect', address: '202.137.235.17', port: 25, command:
'CONN' }
Maybe you could use smtp.gmail.com ?
Remove the TLS. You're not using ssl so you don't need it.

How to restructure my class for reusability

I am currently working on a class which handles emails being sent by the web app.
import nodemailer from "nodemailer"
import jwt from 'jsonwebtoken'
class emailModel {
async sendEmail(email, emailToken)
{
let transporter = nodemailer.createTransport({
host: "###########",
port: ####,
secture: true,
auth: {
user: process.env.CONTACT_EMAIL,
pass: process.env.EMAIL_PASS
},
tls: {
rejectUnauthorized: false
}
})
const url = `#########/api/confirm/${emailToken}`
let confirmationEmail = await transporter.sendMail({
from: '"######" <######>',
to: email,
subject: "Please verify your email.",
html: `Please confirm your email ${url}`
})
}
async registrationEmail(email)
{
let transporter = nodemailer.createTransport({
host: "####",
port: ####,
secture: true,
auth: {
user: process.env.CONTACT_EMAIL,
pass: process.env.EMAIL_PASS
},
tls: {
rejectUnauthorized: false
}
})
let confirmationEmail = await transporter.sendMail({
from: '"#####" <######>',
to: email,
subject: "Thank you for registering.",
html: `Thank you for registering.`
})
}
}
export default new emailModel
I want to reuse the transporter so I do not have to keep calling it in every function. I tried putting the transporter in a constructor but I wasn't able to get it called by the functions.
Thank you all for your responses.
Edit
import nodemailer from "nodemailer"
import jwt from 'jsonwebtoken'
class emailModel {
constructor()
{
this.transporter = nodemailer.createTransport({
host: "smtp.ionos.co.uk",
port: 587,
secture: true,
auth: {
user: process.env.CONTACT_EMAIL,
pass: process.env.EMAIL_PASS
},
tls: {
rejectUnauthorized: false
}
})
}
async sendEmail(email, emailToken)
{
// let transporter = nodemailer.createTransport({
// host: "smtp.ionos.co.uk",
// port: 587,
// secture: true,
// auth: {
// user: process.env.CONTACT_EMAIL,
// pass: process.env.EMAIL_PASS
// },
// tls: {
// rejectUnauthorized: false
// }
// })
const url = `http://localhost:4003/api/confirm/${emailToken}`
let confirmationEmail = await this.transporter({
from: '"Virginie Vannaxay" <contact#laoenglishschool.com>',
to: email,
subject: "Please verify your email.",
html: `Please confirm your email ${url}`
})
}
async registrationEmail(email)
{
let transporter = nodemailer.createTransport({
host: "smtp.ionos.co.uk",
port: 587,
secture: true,
auth: {
user: process.env.CONTACT_EMAIL,
pass: process.env.EMAIL_PASS
},
tls: {
rejectUnauthorized: false
}
})
let confirmationEmail = await transporter.sendMail({
from: '"Virginie Vannaxay" <contact#laoenglishschool.com>',
to: email,
subject: "Thank you for registering.",
html: `Thank you for registering.`
})
}
}
export default new emailModel
let confirmationEmail = await this.transporter({
^
TypeError: this.transporter is not a function
import nodemailer from "nodemailer"
import jwt from 'jsonwebtoken'
let transporter = nodemailer.createTransport({
host: "smtp.ionos.co.uk",
port: 587,
secture: true,
auth: {
user: process.env.CONTACT_EMAIL,
pass: process.env.EMAIL_PASS
},
tls: {
rejectUnauthorized: false
}
})
class emailModel {
constructor(transporter) {
this.transporter = transporter;
}
async sendEmail(email, emailToken)
{
const url = `http://localhost:4003/api/confirm/${emailToken}`
let confirmationEmail = await this.transporter({
from: '"Virginie Vannaxay" <contact#laoenglishschool.com>',
to: email,
subject: "Please verify your email.",
html: `Please confirm your email ${url}`
})
}
async registrationEmail(email)
{
let confirmationEmail = await this.transporter.sendMail({
from: '"Virginie Vannaxay" <contact#laoenglishschool.com>',
to: email,
subject: "Thank you for registering.",
html: `Thank you for registering.`
})
}
}
export default new emailModel
Example of how to use this:
let email = new emailModel(transporter);
If an object needs an external dependency in order to work, pass that dependency in as an argument to the constructor. Also, be sure you're using nodemailer correctly... I mainly copied the code from your edited example, but you use sendMail() in registrationEmail() but not sendEmail(). I've never used nodemailer so I don't know if that's correct.

Nodemailer not loggin in

I want to send an email from node backend and I am using the nodemailer library for express to achieve that. I have written the following code to configure the transport and other details for nodemailer
let transport = nodemailer.createTransport({
host: 'mail.myrandomhost.in',
port: 587,
tls: {
rejectUnauthorized:false
},
secure: false,
auth: {
user: 'me#myemail.in',
pass: 'Gr3aseMonk3y'
}
});
const message = {
from: 'me#myemail.in',
to: 'youremail#gmail.com',
subject: 'test email',
html: '<h1>Hey</h1><p>This is test <b>Tesla</b> email</p>'
};
transport.sendMail(message, function(err, info) {
if (err) {
console.log('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=');
console.log("FAILED");
console.log('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');
console.log(err)
} else {
console.log('====================================');
console.log("Email sent");
console.log('====================================');
console.log(info);
}
});
When I run this, I get the following error
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
FAILED
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Error: Invalid login: 535 Incorrect authentication data
at SMTPConnection._formatError (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
at SMTPConnection._actionAUTHComplete (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:1523:34)
at SMTPConnection.<anonymous> (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:550:26)
at SMTPConnection._processResponse (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:942:20)
at SMTPConnection._onData (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData (/Users/sarthak/Desktop/CodingEnvironments/NodeJS/templates/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
at TLSSocket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:182:23) {
code: 'EAUTH',
response: '535 Incorrect authentication data',
responseCode: 535,
command: 'AUTH PLAIN'
}
I am using the correct details. How do I solve this?
You entered the wrong data. you must change host, from to real addresses.
Example:
let transport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
tls: {
rejectUnauthorized:true
},
secure: false,
auth: {
user: 'yourRealEmail#gmail.com',
pass: 'yourPassword'
}
});
const message = {
from: 'yourRealEmail#gmail.com',
to: 'RealEmailAddress#gmail.com',
subject: 'test email',
html: '<h1>Hey</h1><p>This is test <b>Tesla</b> email</p>'
};
transport.sendMail(message, function(err, info) {
if (err) {
console.log('-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=');
console.log("FAILED");
console.log('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');
console.log(err)
} else {
console.log('====================================');
console.log("Email sent");
console.log('====================================');
console.log(info);
}
});

Issue with requiring of nodemailer in React.js;

I am trying to send an email after registration to a user. But I am having an issue with requiring of nodemailer module. I am getting the following error:
-The version of my npm is: 6.2.0
-The version of my node is: v8.11.1
-My package.json looks like this:
-My function for sending email looks like this:
sendEmail() {
var nodemailer = require("nodemailer");
nodemailer.createTestAccount((err, account) => {
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'example#gmail.com',
pass: 'example'
}
});
let mailOptions = {
from: '"Example" <example#gmail.com>',
to: this.inputEmail.value,
subject: 'Successful registration!',
text: "Thank you registing with us!"
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
})
})
}

Nodemailer and "SSL23_GET_SERVER_HELLO:unknown protocol" error

Below is my Node.js code. Using the code results in:
Error: 0:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:794
Here is the code:
var express = require('express')
, fs = require("fs")
, app = express()
, path = require('path')
, request = require('request')
, bodyParser = require('body-parser')
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server, {log: true, origins: '*:*'})
;
var smtpTransport = require('nodemailer-smtp-transport');
var options = {
key : fs.readFileSync('server.key'),
cert : fs.readFileSync('server.crt')
};
var nodemailer = require('nodemailer');
var sendmailTransport = require('nodemailer-sendmail-transport');
var emailserver = nodemailer.createTransport(smtpTransport({
service: 'Gmail',
port: 25,
strictSSL: false,
host:'smtp.gmail.com',
SSL Protocol: 'off',
TLS Protocol: ON,
auth: {
user: 'choudhary1707#gmail.com',
pass: 'mypassword'
},
tls: {ciphers: "SSLv3"}
}));
How to solve this error?
I had this error using a third party smtp with the 'nodemailer-smtp-transport' node module.
My problem turned out to be that I was using port 587.
When I switched it to 465 it all started working.
My configuration looks like:
const smtpConfiguration = {
host: '<my smtp host>',
port: 465,
secure: true, // use TLS
auth: {
user: '<user account>',
pass: '<password>'
}
};
And my email function (typescript, bluebird Promise):
export const SendEmail = (from:string,
to:string[],
subject:string,
text:string,
html:string) => {
const transportOptions = smtpConfiguration;
const transporter = nodemailer.createTransport(smtpTransport(transportOptions));
const emailOptions = {
from: from,
to: to.join(','),
subject: subject,
text: text,
html: html
};
return new Promise((resolve, reject) => {
transporter.sendMail(emailOptions, (err, data) => {
if (err) {
return reject(err);
} else {
return resolve(data);
}
});
});
};
I've faced similar problem
solved with this thread
// For port 465
var transporter = nodemailer.createTransport({
host: 'smtp.hostname',
port: 465,
secure: true,
auth: {
user: 'email',
pass: 'password'
}
});
// for port 587 or 25 or 2525 etc.
var transporter = nodemailer.createTransport({
host: 'smtp.hostname',
port: 587,
secure: false,
requireTLS: true, // only use if the server really does support TLS
auth: {
user: 'email',
pass: 'password'
}
});
Use this this is working
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
connectionTimeout : "7000",
greetingTimeout : "7000",
auth: {
XOAuth2: {
user: "email id",
clientId: "client id",
clientSecret: "secret",
refreshToken: "refresh token"
}
}
});
Looks like your making it a little more complicated than it needs to be. I'm successfully using this with version 0.7.0 of Nodemailer.
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "***#gmail.com",
pass: "****"
}
});
var mailOptions = {
from: "****#gmail.com",
to: to,
subject: 'Subject Line!',
text: 'Alternate Text',
html: '<label>Hello!</label>'
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
// if you don't want to use this transport object anymore, uncomment following line
smtpTransport.close(); // shut down the connection pool, no more messages
callback();
});
Your problem is likely SSLv3. Most servers have it disabled.
TLS Protocol: ON,
auth: {
user: 'jdoe#example.com',
pass: 'super-secret-password'
},
tls: {ciphers: "SSLv3"}
You should use TLS 1.0 and above.
You should also use use Server Name Indication or SNI, but I don't know how to tell Node.js to use it.

Categories