how to send encrypted message via nodejs? - javascript

I am sending emails via postfix mail server.
the code is on node.js using sendmail:
const sendmail = require('sendmail')({
logger: {
debug: console.log,
info: console.info,
warn: console.warn,
error: console.error
},
silent: true,
smtpPort: 25, // Default: 25
dkim: {
privateKey: fs.readFileSync('mail_key.txt', 'utf8'),
keySelector: 'mail'
},
smtpHost: 'mail.mydomain.com' // Default: -1 - extra smtp host after resolveMX
})
const text = 'some text .... ';
var mes=sendmail({
from: ' "some sender" <info#mydomain.com',
to: data.Email,
subject: 'Your Account Data',
html:text,
}, function(err, reply) {
console.log(err && err.stack);
console.dir(reply);
});
messages are send successfully. but still is encrypted.
i want to know how to send emails to be encrypted.
BTW my connection is encrypted using TLS‌ before. I want to encrypt message content.

You can use bcrypt package to encrypt your string value and here is how you can use it:
let text2 = 'some....';
bcrypt.hash(text2, 10, (err, hash) => {
if(err) throw err;
text = hash;
console.log('happy hashing',text);
});

Related

NodeMailer error when sending email. On production only

I'm using the following code to create a SMTPtransporter that will be used to send emails. The code works perfectly fine on my computer. With Yarn version '1.22.17'.
import * as nodemailer from 'nodemailer';
import * as SMTPTransport from "nodemailer/lib/smtp-transport";
const poolOptions = {
pool: true,
maxConnections: 1,
maxMessages: 5
}
const smtpOptions = {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: SMTP_USER,
pass: SMTP_PASSWORD
},
tls:{
ciphers: 'SSLv3',
rejectUnauthorized: false
}
}
const nodemailerOptions: SMTPTransport.Options = {
...poolOptions,
...smtpOptions
}
const transport = nodemailer.createTransport(nodemailerOptions);
The send email function :
export function sendMail(
to: string, subject: string, text: string, html: string) {
const mailOptions = {
from: 'Bobo <no-reply#bobo.bo>', to, subject, text, html
};
return new Promise((resolve, reject) => {
transport.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(
`Failed to send email to ${to} with body [${text}]`, error);
reject(new Error('Email sending failed'));
} else {
console.log(
`Email sent to ${to} with subject [${subject}]`, info.response);
resolve();
}
});
});
}
Meanwhile in the server i got the following error each time i try to send an email :
{ Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
errno: 'ECONNRESET',
code: 'ECONNECTION',
syscall: 'read',
command: 'CONN' }
It's the same app deployed in ubuntu server with same Yarn version.
If anyone can help i would be very grateful.
NOTE :: For the deployment on the server, i used Nginx to forward all the requests on port 80 to 3000 (App running). And the ports for SMTP are open (25,587)
It seems to be some kind of problem related to the TLS node library, there is an already question addressing this problem, you can find it here
The problem was due to the restriction in the network put by the hosting company. I adjusted the smtp host to one they allow trafic with.

Node Mailer does not work even though it says its successful

I have question about the nodemailer that I am working on. The result returns email sent,
but I do not get any email. I am sure I am doing something wrong and I have no idea what that is.
I will post my code below.
let transporter = nodemailer.createTransport({
//pool: true,
host: "*****.net",
port: ****,
secure: false,
auth: {
user: "****.com",
pass: "*****",
},
tls: {
// do not fail on invalid certs
rejectUnauthorized: false,
},
});
var mailOptions = {
from: '"xxx"<info#****.com>;', // sender address
to: result.recordset[0].toEmail, // list of receivers
subject: "NEW USER", // Subject line
html: result.recordset[0].content, // plain text body
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log("Email sent: " + info.response);
}
});
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
AND THIS IS THE MESSAGE I GET FROM THE TERMINAL BELOW
Server is ready to take our messages
Email sent: 250 uPMSkJg8an7bs mail accepted for delivery
If you are using for example a cheap mail service, mails might be sent after some time. I had that problem before. Services use queue system and prioritize the mail requests based on the pricing. Other than that, you can check your spam folder just in case if that might be a problem.

Using nodemailer and smtp send mail without authentication

Below is my code. This works fine with gmail smtp server.
But when I use my office one (which does not require authentication) it fails
May be the syntax I am using is wrong.
below is the code working with gmail smtp:
var mailOptions = {
from: 'xxxx#abcd.com',
to: 'xxxxyy#abcd.com',
subject: 'hello world!',
html: '<img src="cid:logo">',
attachments: [{
filename: 'test.png',
path: 'D:/bbbbb/mmmm/src/test.png',
cid: 'logo' //same cid value as in the html img src
}]
};
transport.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
}
console.log(`Message sent: ${info.response}`);
});
As Our company smtp does not require authentication,
I have tried below code:
var transport = nodemailer.createTransport("smtps://xxxx#abcd.com:"+encodeURIComponent('') + "#xxxx.xxxrxx.com:25");
OR
var transport = nodemailer.createTransport("smtps://xxx.xxx.com:25");
but all resulted error
{ Error: 101057795:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:797:
at Error (native) code: 'ECONNECTION', command: 'CONN' }
My guess is syntax is wrong.
Can some one pls correct me
Thanks and Regards.
You can remove auth option from the example code when creating an SMTP Transport message.
so it should look like the following:
/**
* Initialize transport object
*/
const transporter = nodemailer.createTransport({
host: "", //Host
port: , // Port
secure: true
});
let mailOptions = {
from: , // sender address
to: , // list of receivers
subject: , // Subject line
text: , // plain text body
html: // html body
};
/**
* send mail with defined transport object
*/
transporter.sendMail(mailOptions,
(error, info) => {
});

unable to send html text using nodemailer

I am unable to send html text in mail using nodemailer.
exports.send = function(req, res) {
console.log(req.query);
var mailOptions = {
to: req.query.email,
subject: req.query.sub,
text: 'Date of Interview: ' + req.query.dateOfInterview+ 'Time of Interview: ' + req.query.timeOfInterview + '' + req.query.assignedTechnicalPerson + '' + req.query.typeOfInterview + '' + req.query.interviewLocation
}
smtpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
console.log(error);
res.end("error");
} else {
console.log("Message sent: " + response.message);
res.end("sent");
}
});
};
I am getting mail as continuous text without any line space
How can i send the same text using html tags in it i have also tried keeping html and end up getting lots of errors
Please say me correct syntax
Any help is appreciated
Here is the working code with nodemailer latest version.
var smtpTransport = require('nodemailer-smtp-transport');
var transporter = nodeMailer.createTransport(
smtpTransport({
service: 'gmail',
auth: {
user: <Your gmail>,
pass: '*****'//ur password
}
})
);
transporter.sendMail({
from: 'sender#gmail.com',
to: "recipient#mail.id",
subject: 'hello world!',
//text:"one"
html: '<html><body>Hello World....</body></html>'
}, function(error, response) {
if (error) {
console.log(error);
} else {
console.log('Message sent');
}
});
Note: To give access for smtp do the following:
For Gmail you may need to configure "Allow Less Secure Apps" in your
Gmail account. Click here
You also may need to unlock your account with "Allow access to your
Google account" to use SMTP.
If you are using 2FA in that case you would have to create an
Application specific password.

Send email is not sending email when used nodemailer with protractor

No message is displayed for the error but also for the message for success is also not displayed. Also no email is recieved.
This is the code i had in the config file of protractor. Here there is no error response for the email but also there is no successful message also and no email is received.
this is in the config file
onComplete: function () {
creating reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP", {
host: "smtp.company.com",
port: "110",
auth: {
user: "anuvrat.singh#companyemail.com",
pass: "XXXX#2015"
}
});
setup the email data
var mailOptions = {
from: "anuvrat.singh#Company.com", // sender address
to: "anuvrat.singh#Company.com",
subject: "Hello ✔", // Subject line
text: "Hello world ✔", // plaintext body
html: "<b>Hello world ✔</b>" // html body
}
send mail with defined transport object
smtpTransport.sendMail(mailOptions, function (error, response) {
if there is an error it will display other wise it will send the message
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
shut down the connection pool, no more messages
smtpTransport.close();
});
}

Categories