Sending mails with attachment via NodeJS - email

Is there any library for NodeJS for sending mails with attachment?

Yes, it is pretty simple,
I use nodemailer: npm install nodemailer --save
var mailer = require('nodemailer');
mailer.SMTP = {
host: 'host.com',
port:587,
use_authentication: true,
user: 'you#example.com',
pass: 'xxxxxx'
};
Then read a file and send an email :
fs.readFile("./attachment.txt", function (err, data) {
mailer.send_mail({
sender: 'sender#sender.com',
to: 'dest#dest.com',
subject: 'Attachment!',
body: 'mail content...',
attachments: [{'filename': 'attachment.txt', 'content': data}]
}), function(err, success) {
if (err) {
// Handle error
}
}
});

Try with nodemailer, for example try this:
var nodemailer = require('nodemailer');
nodemailer.SMTP = {
host: 'mail.yourmail.com',
port: 25,
use_authentication: true,
user: 'info#youdomain.com',
pass: 'somepasswd'
};
var message = {
sender: "sender#domain.com",
to:'somemail#somedomain.com',
subject: '',
html: '<h1>test</h1>',
attachments: [
{
filename: "somepicture.jpg",
contents: new Buffer(data, 'base64'),
cid: cid
}
]
};
finally, send the message
nodemailer.send_mail(message,
function(err) {
if (!err) {
console.log('Email send ...');
} else console.log(sys.inspect(err));
});

Personally i use Amazon SES rest API or Sendgrid rest API which is the most consistent way to do it.
If you need a low level approach use https://github.com/Marak/node_mailer and set up your own smtp server (or one you have access too)
http://blog.nodejitsu.com/sending-emails-in-node

Have you tried Nodemailer?
Nodemailer supports
Unicode to use any characters
HTML contents as well as plain text alternative
Attachments
Embedded images in HTML
SSL (but not STARTTLS)

You may use nodejs-phpmailer

You can also use AwsSum's Amazon SES library:
https://github.com/appsattic/node-awssum/
In there, there is an operation called SendEmail and SendRawEmail, the latter of which can send attachments via the service.

use mailer package it is very flexible and easy.

Another alternative library to try is emailjs.
I gave some of the suggestions here a try myself but running code complained that send_mail() and sendMail() is undefined (even though I simply copy & pasted code with minor tweaks). I'm using node 0.12.4 and npm 2.10.1. I had no issues with emailjs, that just worked off the shelf for me. And it has nice wrapper around attachments, so you can attach it various ways to your liking and easily, compared to the nodemailer examples here.

Nodemailer for any nodejs mail needs. It's just the best at the moment :D

I haven't used it but nodemailer(npm install nodemailer) looks like what you want.

Send With express-mailer (https://www.npmjs.com/package/express-mailer)
Send PDF -->
var pdf="data:application/pdf;base64,JVBERi0xLjM..etc"
attachments: [ { filename: 'archive.pdf',
contents: new Buffer(pdf.replace(/^data:application\/(pdf);base64,/,''), 'base64')
}
]
Send Image -->
var img = 'data:image/jpeg;base64,/9j/4AAQ...etc'
attachments: [
{
filename: 'myImage.jpg',
contents: new Buffer(img.replace(/^data:image\/(png|gif|jpeg);base64,/,''), 'base64')
}
]
Send txt -->
attachments: [
{
filename: 'Hello.txt',
contents: 'hello world!'
}
]

you can use official api of google for this.
They have provided package for node for this purpose.
google official api
Ive attached part of my code that did the attachment thing for me
function makeBody(subject, message) {
var boundary = "__myapp__";
var nl = "\n";
var attach = new Buffer(fs.readFileSync(__dirname + "/../"+fileName)) .toString("base64");
// console.dir(attach);
var str = [
"MIME-Version: 1.0",
"Content-Transfer-Encoding: 7bit",
"to: " + receiverId,
"subject: " + subject,
"Content-Type: multipart/alternate; boundary=" + boundary + nl,
"--" + boundary,
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: 7bit" + nl,
message+ nl,
"--" + boundary,
"--" + boundary,
"Content-Type: Application/pdf; name=myPdf.pdf",
'Content-Disposition: attachment; filename=myPdf.pdf',
"Content-Transfer-Encoding: base64" + nl,
attach,
"--" + boundary + "--"
].join("\n");
var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
P.S thanks to himanshu for his intense research on this

The answer is not updated with the last version of nodemailer#6.x
Here an updated example:
const fs = require('fs')
const path = require('path')
const nodemailer = require('nodemailer')
const transport = nodemailer.createTransport({
host: 'smtp.libero.it',
port: 465,
secure: true,
auth: {
user: 'email#libero.it',
pass: 'HelloWorld'
}
})
fs.readFile(path.join(__dirname, 'test22.csv'), function (err, data) {
transport.sendMail({
from: 'email_from#libero.it',
to: 'email_to#libero.it',
subject: 'Attachment',
text: 'mail content...', // or body: field
attachments: [{ filename: 'attachment.txt', content: data }]
}, function (err, success) {
if (err) {
// Handle error
console.log(err)
return
}
console.log({ success })
})
})

Related

How to send mail with attachment in lambda nodeJs using SES service

I am trying to send a mail with attachment.
I have already used SES service for sending simple and HTML content mail. but now I want to send a mail with attachments.
I am using amazon SES service for sending emails and I am using the 'sendRawEmail' method for send mail with attachments.
I am getting an error message like this.InvalidParameterValue: Nested group
I didn't find any Node examples for this type of error.
I am having a very frustrating time trying to send emails with NodeJS SES API.
I found the issue and i fixed that with using mailcomposer npm package.
Now I an able to send a Mails with attachments.
Install AWS SDK
npm i aws-sdk
Now Install manilcomposer
npm i mailcomposer
Full code below
Request body:
if you want to send mail With Base64 content.
{
email: ['jen****#gmail.com', 'Aa****#gmail.com'],
from: 'no-reply#*****.com',
subject: 'Sending emails with attachments',
text: 'please find attachments',
attachments: [{
filename: 'sample.pdf',
content: {{file}}, // file content base64 staring
encoding: 'base64',
}]
}
if you want to send a mail with the file path.
{
email: ['jen****#gmail.com', 'Aa****#gmail.com'],
from: 'no-reply#*****.com',
subject: 'Sending emails with attachments',
text: 'please find attachments',
attachments: [{
filename: 'sample.pdf',
path: './home/sample,pdf'
}]
}
Business logic Code:
const ses = new AWS.SES({ region: 'us-east-1' }); //specify region for the particular see service.
const mailcomposer = require('mailcomposer');
exports.handler = function (event, context) {
console.log('Event: ',JSON.stringify(event));
if (!event.email) {
context.fail('Missing argument: email');
return;
}
if (!event.subject) {
context.fail('Missing argument: subject');
}
if (!event.from) {
context.fail('Missing argument: from');
}
if (!event.html && !event.text) {
context.fail('Missing argument: html|text');
}
const to = event.email;
const from = event.from;
const subject = event.subject;
const htmlBody = event.html;
const textBody = event.text;
const attachments = event.attachments;
const mailOptions = {
from: from,
subject: subject,
text: textBody,
html: htmlBody,
to: to,
attachments: attachments ? attachments : []
};
const mail = mailcomposer(mailOptions);
mail.build(function (err, message) {
const req = ses.sendRawEmail({ RawMessage: { Data: message } });
req.on('build', function () {
req.httpRequest.headers['Force-headers'] = '1';
});
req.send(function (err, data) {
if (err) {
console.log(err, err.stack);
context.fail('Internal Error: The email could not be sent.');
} else {
console.log(message);
console.log('The email was successfully sent')
context.succeed('The email was successfully sent');
}
});
});
};
if you have and any query regarding mailcomposer then check [here][1] this link below
[1]: https://nodemailer.com/extras/mailcomposer/

Nodemailer - email send but not receive

I'm build an API with feathersjs and I need to send an email with an attachment.
The email seems to be send but I receive nothing.
In my mail.service.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'smtp.office365.com',
port: 587,
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'gil.felot#myaccount.com',
pass: 'MyPassWord'
}
});
// Check the connection to the service.
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
Then in my hook
hook => {
const file = hook.params.file;
const email = {
from: 'gil.felot#myaccount.com', // sender address
to: 'mygmailaccount#gmail.com', // list of receivers
subject: 'Test Nodemailer', // Subject line
// text: req.body.text, // plaintext body
html: '<b>Hello world 🐴</b>', // html body
attachments: [
{
filename: file.originalname,
contents: new Buffer(file.buffer, 'base64'),
encoding: 'base64'
}
]
};
return hook.app.service('mail').create(email)
.then(function (result) {
console.log('Sent email', result);
}).catch(err => {
console.log(err);
});
}
then I got
Server is ready to take our messages
Sent email
Object {from: "gil.felot#myaccount.com", to: "mygmailaccount#gmail.com", subject: "Test Nodemailer", html: "Hello world 🐴"}
I have no idea how to check where the problem come from.
I was missing the from part while creating a mail while I was able to send mail via google smtp but my own smtp was failing with the above configuration
Was working with google
var mailOptions = { to: email, subject: 'Forgot Password', html: mailData };
Working with my smtp as well:
var mailOptions = { from: 'serverName.com', to: email, subject: 'Forgot Password', html: mailData };
Consider adding name while defining nodemailer configuration as well
let transporter = nodemailer.createTransport({
name: 'example.com' // <= Add this
host: 'smtp.example.email',
port: 587,
Ok I figure it out !
I needed to add the transporter.sendMail() inside the mail.class.js to trigger this action when I call hook.app.service('mail').create(email)
Working and the attachement file that is 0 byte in the mail but the good size inside my variable.
For me this was what I realized; if the html does not have the html tags, then the email is not sent. i.e.
This template will work
<html>
<body>
Hello and welcome
</body>
</html>
This template will not work:
<body>
Hello and welcome
</body>
This is especially when sending to office365, refer to this other question here:
Nodemailer doesn't send emails to outlook.office365 accounts

Sending images with AngularJS and NodeJS

Hi I am making a service to send images with users' information. For example, name, phone number, and their images to upload.
I am planning to use ng-file-upload, one of AngularJS custom dependency. And then, I am going to use Nodemailer to send all the information and images to somewhere else.
But my question is can I send other text data along with ng-file-upload? And second is can I send images with other text data through nodemailer?
Although OP has found a solution in the end, since I had the same problem I figured I'd post the whole code here for others who might struggle with that.
So here is how I combined ng-file-upload and nodemailer to upload and send attachments by e-mail using Gmail:
HTML form:
<form name="postForm" ng-submit="postArt()">
...
<input type="file" ngf-select ng-model="picFile" name="file" ngf-max-size="20MB">
...
</form>
Controller:
app.controller('ArtCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.postArt = function() {
var file = $scope.picFile;
console.log(file);
file.upload = Upload.upload({
url: '/api/newart/',
data: {
username: $scope.username,
email: $scope.email,
comment: $scope.comment,
file: file
}
});
}
}]);
Server:
var nodemailer = require('nodemailer');
var multipartyMiddleware = require('connect-multiparty')();
// multiparty is required to be able to access req.body.files !
app.mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: ...
pass: ...
},
tls: { rejectUnauthorized: false } // needed or Gmail might block your mails
});
app.post('/api/newart', multipartyMiddleware,function(req,res){
console.log(req.files);
mailOptions = {
from: req.body.email,
to: ...,
subject: ...
text: ...,
attachments: [{
filename: req.files.file.name,
path: req.files.file.path // 'path' will stream from the corresponding path
}]
};
app.mailTransporter.sendMail(mailOptions, function(err) {
if (err) {
console.log(err);
res.status(500).end();
}
console.log('Mail sent successfully');
res.status(200).end()
});
});
The nodemailer examples helped me figure this out!
This works for any file type. The key aspect that some people might miss out is that you need multiparty to access the uploaded file (in req.body.files). Then the most convenient way to attach it is using the path key in the attachment object.
Definitely you can send images as attachment using nodemailer.
Try this for sending image as an attachment :
var mailOptions = {
...
html: 'Embedded image: <img src="cid:unique#kreata.ee"/>',
attachments: [{
filename: 'image.png',
path: '/path/to/file',
cid: 'unique#kreata.ee' //same cid value as in the html img src
}]
}
For more reference on sending image as attachment go through nodemailer's "using Embedded documentation".
For the first part of the question:
Yes! you can send other text data along with image using ng-file-upload. It depends how you want to do it and what you want to achieve.
For example, see the code below:
HTML Template
<form name="form">
<input type="text" ng-model="name" ng-required="true">
<input type="text" ng-model="phoneNo" ng-required="true">
<div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}">Select</div>
<button type="submit" ng-click="submit()">submit</button>
</form>
Controller
$scope.submit = function() {
if ($scope.form.file.$valid && $scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'name': $scope.name, 'phoneNo' : $scope.phoneNo}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
Read ng-file-upload documentation completely to see understand all the things you can do along with file upload. It has many examples to make you understand everything.
I hope it helps, and answer your question.

Getting error sending email in nodejs with emailjs

[error: can't set headers after they are sent.]
createCredentials() is deprecated, use tls.createSecureContext instead
{[Error: bad response on command '-']
code:2
smtp : '550 5.3.4 Requested action not token; To continue sending messages,
please sign in to your account.\n}
I have been trying to send email in nodejs with emailjs and nodemailer but i keep on getting the error above.
transportEmail: email.server.connect({
user: "ghConnectUs#outlook.com",
password:"******",
host: "smtp-mail.outlook.com",
tls: {ciphers: "SSLv3"}
})
note: i have include all modules.
i'm hoping somebody can point me to the right path. i just want to send me using outlook or gmail in node app.
Below is the code for sending email from nodejs app (through Gmail):
Using Nodemailer v1.3.4:
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "email_id_of_gmail_account",
pass: "password_of_gmail_account"
}
});
var mailOptions = {
from: 'sender_email_id', // sender address
to: 'receiver_email_id, some_other_email_if_requierd', // list of receivers
cc: 'cc_email_id'
subject: 'subject text', // Subject line
text: 'body plain text', // plaintext body
html: '<b>body html</b>' // html body
};
var sendEMail = function () {
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log('Message sent: ' + info.response);
}
});
};
sendEmail();
Note: if you are using Nodemailer version 0.7 or lower, then transporter object will created like this:
var transporter = nodemailer.createTransport('SMTP', {
service: "Gmail",
auth: {
user: "email_id_of_gmail_account",
pass: "password_of_gmail_account"
}
});
Using emailJs v0.3.16:
var email = require("/node_modules/emailjs/email.js");
var server = email.server.connect({
user: "emailId_of_gmail_account",
password: "password_of_gmail_account",
host: "smtp.gmail.com",
ssl: true // in case outlook, use "tls: {ciphers: "SSLv3"}"
});
var message = {
text: "body text",
from: "senderName <sender's_email_id>",
to: "receiverName <receiver_email_id>",
subject: "subject text",
attachment: // optional
[
{data: "<html>i <i>hope</i> this works! html </html>", alternative: true},
{path: "path/to/file.zip", type:"application/zip", name:"renamed.zip"}
]
};
var sendEMail = function () {
server.send(message, function (err, message) {
console.log(err || message);
});
};
sendEmail();

node.js send email successful, but mail not found

I am using https://github.com/eleith/emailjs for my node.js application
After setting up the configuration properly, when I send email, I get the successful message in my log, but I do not see any mails either in the inbox or spambox :-(..
I using gmail, smtp.gmail.com, ssl:true, port:465.
email.send({...},function(err, message) {
if (err) {
console.log('Error sending email : ', err);
}
else {
console.log('Email SUCCESSFULLY sent', message);
}
^[[32m[2011-10-13 06:53:28.758] [INFO] console - ^[[39mEmail SUCCESSFULLY sent {
attachments: [],
html: null,
header:
{ 'message-id': '<1318488805460.5532#Abcd-PC>',
from: 'xxxxx#gmail.com',
to: 'yyyyy#gmail.com, ',
cc: 'zzzzz#gmail.com',
subject: 'Test mail from emailjs' },
content: 'text/plain; charset=utf-8',
text: 'Testing sending email' }
I use the following code for my emails in node.js (using emailjs)
var server = email.server.connect({
user: 'your#gmail.com',
password: 'gmailPass',
host: 'smtp.gmail.com',
ssl: true
});
server.send({
text: 'hello world',
from: 'obama#state.gov',
to: 'someone#else.com',
subject: 'just a subject here'
}, function(err, message) {
if (err) {
// err
} else {
// ok
}
});
Problem was comma(,) "yyyyy#gmail.com," in the 'to' email. I was trying to add multiple ids separated by commas(,) and that created the problem..
In the documentation, they have mentioned though
**"someone <someone#gmail.com>, another <another#gmail.com>"**
may be it expects the email format to be in the form they mentioned.