Node js email Invalid sender - node.js

Config : Ubuntu 16.04 LTS / Nginx
I'm trying to send mail with nodemail but I have this error :
{ [Error: Invalid sender "contact#example.com>"] code: 'EENVELOPE', command: 'API' }
Here is my code.
var transporter = nodemailer.createTransport(
smtpTransport('smtps://contact%40example.com:mypassword#smtp.example.com')
);
var text = 'Hello world from \n\n' + req.body.name;
var mailOptions = {
from: 'contact#example.com>', // sender address
to: 'address#gmail.com', // list of receivers
subject: 'Email Example', // Subject line
text: text //, // plaintext body
// html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.json({yo: 'error'});
}else{
console.log('Message sent: ' + info.response);
res.json({yo: info.response});
};
});
With postfix on my server my mail works well I can send an email to an gmail address but with node js I have this error.

Related

wait file to create before send mail

Im having some problems with a function with nodemailer, i need to create a pdf from body req, then attach it to a mail and send it, the problem here is i dont know how to wait to the file to finish saving before send the mail, and im having errors because the mails goes before the system can create the file or even attach the pdf file...
the idea will be: send post req -> get the req.body -> create pdf -> create mail options (nodemailer) -> send the mail.
but the code now is going like: send post req -> get the req.body -> create pdf -> create mail options (nodemailer) -> send the mail -> system
still making the pdf -> error
my current code is:
app.post('/send', function(req, res) {
if (req.body.email == "" || req.body.subject == "") {
res.send("Error: Email & Subject should not blank");
return false;
}
// Sending Emails with SMTP, Configuring SMTP settings
var smtpTransport = nodemailer.createTransport({
host: "mail.vyg.cl", // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
auth: {
user: 'crm#vyg.cl',
pass: '******'
}
});
const pdfArchive = './server/' + req.body.subject + '.pdf';
if (fs.existsSync(pdfArchive)) {
fs.unlinkSync(pdfArchive);
}
pdf.create(req.body.description).toFile('./server/' + req.body.subject + '.pdf', function(err, res) {
if (err) {
console.log(err);
} else {
console.log(res)
}
});
const mailOptions = {
from: req.body.from, // sender address
to: req.body.to, // list of receivers
cc: req.body.cc,
subject: req.body.subject, // Subject line
//text: "Hello world ✔", // plaintext body
// html: req.body.description, // html body,
attachments: [{ // file on disk as an attachment
filename: req.body.subject + '.pdf',
path: './server/' + req.body.subject + '.pdf' // stream this file
}]
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
res.status(400).json({ message: "Email could not sent due to error: " + error });
} else {
res.status(200).json({ message: "Email has been sent successfully" });
}
});
if (fs.existsSync(pdfArchive)) {
fs.unlinkSync(pdfArchive);
}
});
i tryed to send the mail in the conditional when the pdf was created but i dont get the smtpTransport response....
any help will be appreciated
app.post('/send', async function(req, res) {
if (req.body.email == "" || req.body.subject == "") {
res.send("Error: Email & Subject should not blank");
return false;
}
// Sending Emails with SMTP, Configuring SMTP settings
var smtpTransport = nodemailer.createTransport({
host: "mail.vyg.cl", // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
auth: {
user: 'crm#vyg.cl',
pass: '*******'
}
});
const mailOptions = {
from: req.body.from, // sender address
to: req.body.to, // list of receivers
cc: req.body.cc,
subject: req.body.subject, // Subject line
//text: "Hello world ✔", // plaintext body
// html: req.body.description, // html body,
attachments: [{ // file on disk as an attachment
filename: req.body.subject + '.pdf',
path: './server/' + req.body.subject + '.pdf' // stream this file
}]
}
const pdfArchive = './server/' + req.body.subject + '.pdf';
if (fs.existsSync(pdfArchive)) {
await fs.unlinkSync(pdfArchive);// Add wait here
}
try{
var result = await pdf.create(req.body.description).toFile('./server/' + req.body.subject + '.pdf') // capture result if you need to
try{
await smtpTransport.sendMail(mailOptions) // wrap this in a try catch if you want to capture email sending specific erorrs else outer try catch will work
res.status(200).json({ message: "Email has been sent successfully" });
}
catch(error)
{
res.status(400).json({ message: "Email could not sent due to error: " + error });
}
}
catch(error)
{
console.log(err);
res.send(error)
}
});

Error, While Sending mail through nodemailer

I am working on Registration system, I have to authenticate user by sending email using nodemailer. But I am getting error, attached in image. Below is my code.
Please Help to find where i am wrong. Thanks In Advance.
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'password'
}
});
var mailOptions = {
from: 'email in 6th line',
to: 'test#gmail.com',
subject: 'Sending Email using Node.js',
text: 'Tried first time to send email using node js!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});

Node.js Nodemailer Failed to Send Email

I'm unable to send an email in Node.js using Nodemailer. I don't know how to debug it simply because I don't understand the reply from the terminal. I think it is a SSL issue, but as you can see, I've set 'secure' as 'true', so I really don't know where should I start to debug it.
Source Code:
var nodemailer = require('nodemailer');
var mailOptions = {
host: "smtp.mail.me.com",
port: 587,
secure: true,
auth: {
user: "***",
pass: "***"
}
};
var transporter = nodemailer.createTransport(mailOptions);
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
Result from terminal:
{ Error: 140736043987904:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:../deps/openssl/openssl/ssl/s23_clnt.c:827:
code: 'ECONNECTION', command: 'CONN' }
You are using your transport details to send an email. More information can be found https://nodemailer.com/about/.
let mailOptions = {
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
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});

send email via nodemailer

I try to send email via nodemailer but getting error - TypeError: Cannot read property 'method' of undefined. It looks like sendMail function is not defined. Any advise please?
P.S. This code for chatbot hosted on AWS
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
module.exports = function someName() {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '7384093#gmail.com',
pass: '*******'
}
}))
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"nerd studio" <7384093#gmail.com>', // sender address
to: '7384093#gmail.com', // list of receivers
subject: 'Подтверждение запроса \\ разработак чат-ботов \\ nerd studio', // Subject line
text: 'Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер', // plaintext body
html: '<b>Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
console.log(mailOptions);
console.log(info);
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
You don't need to install npm nodemailer-smtp-transport, only nodemailer is enough to send email to gmail. But first, go to the https://myaccount.google.com/security google account and scroll down and check Allow less secure apps: ON and keep ON. you will send your gmail email. Here, is the full code -
var nodemailer = require('nodemailer');
app.post('/contactform', function (req, res) {
var mailOpts, smtpTrans;
//Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport(smtpTransport({
service: 'gmail',
// host:'smtp.gmail.com',
// port:465,
// secure:true,
auth: {
user: "xxxxxx#gmail.com",
pass: "xxxxxx"
}
}));
var mailoutput = "<html>\n\
<body>\n\
<table>\n\
<tr>\n\
<td>Name: </td>" + req.body.form_name + "<td></td>\n\
</tr>\n\
<tr>\n\
<td>Email: </td><td>" + req.body.form_email + "</td>\n\
</tr>\n\
<tr>\n\
<td>MN: </td>" + req.body.form_phone + "<td></td>\n\
</tr>\n\
<tr>\n\
<td>Messge: </td>" + req.body.form_message + "<td></td>\n\
</tr>\n\
</table></body></html>";
//Mail options
mailOpts = {
to: "Your_App_Name <xxxxxxxx#gmail.com>",
subject: req.body.form_subject,
html: mailoutput
};
smtpTrans.sendMail(mailOpts, function (error, res) {
if (error) {
// res.send("Email could not send due to error" +error);
return console.log(error);
}
});
console.log('Message sent successfully!');
res.render('contact.ejs');
});
//console.log(query.sql);
});
I have nodemailer currently working this way: Create a file config/mail.js:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: 'yourHost',
port: 2525, //example
auth: {
user: 'yourUser',
pass: 'yourPass'
}
});
module.exports = function(params) {
this.from = 'yourEmail';
this.send = function(){
var options = {
from : this.from,
to : params.to,
subject : params.subject,
text : params.message
};
transporter.sendMail(options, function(err, suc){
err ? params.errorCallback(err) : params.successCallback(suc);
});
}
}
And then, anytime I want to send an email:
var Mail = require(path.join(__dirname, '..', '..', 'config', 'mail.js'));
var options = {
to: 'example#example.com',
subject: 'subject',
message: 'your message goes here'
}
var mail = new Mail({
to: options.to,
subject: options.subject,
message: options.message,
successCallback: function(suc) {
console.log('success');
},
errorCallback: function(err) {
console.log('error: ' + err);
}
});
mail.send();
Try this code.First you have to create an app in Google Cloud Console and Enable Gmail API from library.Get the credentials of your app.For that click on Credentials and in the place of Authorized redirect URIskeep this link https://developers.google.com/oauthplayground and save it.Next in another tab open this link https://developers.google.com/oauthplayground/ click on settings symbol on right side.And make a tick on check box(i.e,Use your own OAuth credentials) after this You have to give your clientId and clientSecret.And at the sametime on left side there is a text box with placeholder like Input Your Own Scopes there keep this link https://mail.google.com/
and click on Authorize APIs then click on Exchange authorization code for tokens then you will get your refreshToken and accessToken keep these two in your code.Hope this hepls for you.
const nodemailer=require('nodemailer');
const xoauth2=require('xoauth2');
var transporter=nodemailer.createTransport({
service:'gmail',
auth:{
type: 'OAuth2',
user:'Your_Email',
clientId:'Your_clientId',//get this from Google Cloud Console
clientSecret:'Your_clientSecret',
refreshToken:'Your_refreshToken',//get this from https://developers.google.com/oauthplayground/
accessToken:'Your_accessToken'
},
});
var mailOptions={
from:'<Your_email>',
to:'Your firends mail',
subject:'Sample mail',
text:'Hello !!!!!!!!!!!!!'
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
console.log('Error');
}
else{
console.log('Email Sent');
}
})
I find solution for ,
How to send email from="userEmail" to="myEmail"?
THIS IS TRICK
var nodemailer = require('nodemailer'); router.post('/contacts-variant-2', (req, res, next) => { var name=req.body.name; var email=req.body.email; var message=req.body.message; const output=`
<h3>Contact Details</h3>
<ul>
<li>Name is : ${req.body.name}</li>
<li>Email is : ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`; var transporter = nodemailer.createTransport({ service: 'yahoo', auth: { user: 'create_new_email#yahoo.com', pass: 'password' } }); var mailOptions = { from:'create_new_email#yahoo.com', to:'myFriend#gmail.com', subject: name, text: 'Your have a new
contact request', html:output }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log("errors is somthing "+error); res.send(404); } else { console.log('Email sent: ' + info.response); res.send(200); } }); });
Using Gmail
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myemail#gmail.com',
pass: 'myPassword'
}
});
// setup e-mail data
var mailOptions = {
from: '"Our Code World " <myemail#gmail.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html 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);
});
Using Hotmail
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Outlook
// change the user and pass !
var transporter = nodemailer.createTransport({
host: "smtp-mail.outlook.com", // hostname
secureConnection: false, // TLS requires secureConnection to be false
port: 587, // port for secure SMTP
tls: {
ciphers:'SSLv3'
},
auth: {
user: 'mymail#outlook.com',
pass: 'myPassword'
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <mymail#outlook.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html 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);
});
Alternatively, if your account is hotmail instead of outlook, you can use the buil-in hotmail service using the following transport:
var transport = nodemailer.createTransport("SMTP", {
service: "hotmail",
auth: {
user: "user#hotmail.com",
pass: "password"
}
});
Using Zoho
var nodemailer = require('nodemailer');
// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
host: 'smtp.zoho.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'myzoho#zoho.com',
pass: 'myPassword'
}
});
// setup e-mail data, even with unicode symbols
var mailOptions = {
from: '"Our Code World " <myzoho#zoho.com>', // sender address (who sends)
to: 'mymail#mail.com, mymail2#mail.com', // list of receivers (who receives)
subject: 'Hello ', // Subject line
text: 'Hello world ', // plaintext body
html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html 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);
});

Google App Engine tools

Once the email arrives to inbox, your google app engine program will need to read it using IMAP.
I do this with node
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'your_email#gmail.com',//your gmail account
pass: 'password'//password
}
});
var mailOptions = {
from: 'Fred Foo ✔ <your_email#gmail.com>', // sender address
to: 'some#gmail.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Some Example ✔', // plaintext body
html: '<b>Here is a some version ✔</b>' ,// html body
attachments: [
{
filename: file_name,
path: file_name,
cid: 'unique#kreata.ee'
}]
};
// send email with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
Can someone advise something?

Resources