Sending an array of attachments with node.js - node.js

I need to send an email using nodemailer with several attachments, but the number of those attachments must be defined by the size of an array. I know that nodemailer can send more than one attachment, but I have no idea how to send a variable number of attachments.
Here my code:
const files = get(req, "body.data.files");
files.forEach(file => {
senderMail.send(file, {
name: get(req, "body.data.files.name"),
url: get(req, "body.data.files.url")
});
});
let mailOptions = {
from: "Me", //
sender address
to: data.personal.user_email, // list of receivers
subject:
"An email with attachments"
text: "someText",
html: "",
attachments: [
{
filename: name,
path: url
}
]
};
Some data is obtained from a JSON.

Prepare an array in the Nodemailer format and then attach it to the mail object.
const files = get(req, "body.data.files");
const attachments = files.map((file)=>{
return { filename: file.name, path: file.url };
});
let mailOptions = {
from: "Me", //
sender address
to: data.personal.user_email, // list of receivers
subject:
"An email with attachments"
text: "someText",
html: "",
attachments: attachments
};

Related

How to pass a value from form submit to pug email template

I have a form posting to /submit-form route and I need to pass req.body.revenue value to be used in the email template that goes out after the form submit.
const email = req.body.email;
const revenue = req.body.revenue;
// Prepare the nodemailer
let transporter = nodemailer.createTransport({
host: 'smtp.mailgun.org',
port: 587,
secure: false,
tls: { cipers: 'SSLv3' },
auth: {
user: 'postmaster#sandbox.mailgun.org',
pass: 'xyz',
}
});
// Prepare the email data
const data = {
from: 'Excited User <me#samples.mailgun.org>',
to: email,
subject: 'Hello Pixel, Where those cookies at?',
text: 'Gonna load the pixel next in the HTML',
html: { path: 'pixel-tracker-email.html' }
};
// Send the mail via Nodemailer
transporter.sendMail(data)
.then(msg => console.log(msg))
.catch(err => console.log(err));
console.log('Email sent via Nodemailer!');
I have pug set up for my email template and have tried changing the html value to something like this:
// Prepare the email data
const data = {
from: 'Excited User <me#samples.mailgun.org>',
to: email,
subject: 'Hello Pixel, Where those cookies at?',
text: 'Gonna load the pixel next in the HTML',
html: var html = pug.renderFile('path/to/email-template.pug', {revenue});
};
And then I'm using #{revenue} in the actual email-template.pug file but the value isn't coming through.
I ended up figuring it out like this
html: pug.renderFile(__dirname + '/views/tracking.pug', { email: email, revenue: revenue })

cannot send pdf attachement using nodemailler

I am using nodemailer to send email with pdf attachment, the email is sent successfully, but the pdf attachment is broken when downloaded through the email. Following is my mailOptions:
let mailOptions = {
from: 'writingtest#email.xxx.com', // sender address mailfrom must be same with the user
to: receiveEmail, // list of receivers,use , to split
cc:'service#xxx.com', // copy for receivers
subject: 'writing test from xxx.com', // Subject line
text: 'Hello world', // plaintext body
replyTo: 'service#xxx.com', //send reply email address
attachments: [
{
filename: 'test.pdf',
filePath: '../../files/test.pdf',
contentType: 'application/pdf',
}
],
};
And the info received from callback is:
message sent: 250 Data Ok: queued as freedom ###envid=19950767140

Sending base64 encoded PDF through Nodemailer using PDFkit

I have a function that returns me a base64 encode PDF, and I would like to send this as an attachement PDF file using nodemailer.
Regarding the nodemailer documentation, I found this example:
const mailOptions = {
from: 'email1#gmail.com', // sender address
to: 'email2#gmail.com', // list of receivers
subject: 'Simulation', // Subject line
html: '<p>SALUT</p>', // plain text body
filename: 'file.pdf',
attachments: [
content: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
'//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
'base64'
),
cid: 'note#example.com' // should be as unique as possible
},
However, this did not work for me. Am i missing something ?
Ok, it was all a formatting issue.
Here is how to use B64 on Nodemailer:
const mailOptions = {
from: 'email1#gmail.com', // sender address
to: 'email2#gmail.com', // list of receivers
subject: "Hey this is a subject example", //subject
attachments: [
{
filename: `myfile.pdf`,
content: 'THISISAB64STRING',
encoding: 'base64',
},
],
};
then just send it the classic way.

Send attachment with PDF extension but its not working

I am trying to create a dynamic file and send that to the user in the attachment but after downloading it's not opening.
Showing an error saying "Failed to load PDF
In content, I am sending the required data.
Here is my code
router.get('/file',function(req, res){
var filename1='invoice.pdf';
filename1 = encodeURIComponent(filename1);
var mailOptions={
to: 'userMail#gmail.com',
subject: 'Speaker Added',
from: "admin#gmail.com",
headers: {
"X-Laziness-level": 1000,
"charset" : 'UTF-8'
},
html: '<p style="color:#0079c1;">Hello'+' '+'My Name'+'</p></br>'
+'<p style="color:#0079c1;">Thank you for choosing HOWDY.<p></br>'
+'<p>Click on the link below to activate your account and get redirected to HOWDY</p></br>',
attachments: [
{
'filename':filename1,
'content': 'data',
'contentType':'application/pdf',
'contentDisposition':'attachment'
}
]
}
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'admin#gmail.com',
pass: 'admin56789'
}
});
transporter.sendMail(mailOptions, function(error, response){
if(error){
return res.send(error);
}
else{
res.send({
state:'success',
message:"Send"
});
}
});
})
"
You are sending "data" as content of the file. If you right-click your file, and choose open with notepad (or basic text editor) you'll see.
Nodemailer's attachments expect to receive the data of the file if you use the content option. You might prefer to use path which can be either the filepath or a URL.
Read more here.
Your attachment:
attachments: [
{
'filename':filename1,
'content': 'data',
'contentType':'application/pdf',
'contentDisposition':'attachment'
}
]
Should be closer to:
attachments: [
{
'filename':filename1,
//Either get filecontent
'content': filecontent,
//Or the file full path
'path':filepath,
'contentType':'application/pdf',
'contentDisposition':'attachment'
}
]

Nodemailer.js Data URI attachment

I am trying to send a DataURI attachment via nodemailer
This is my code:
var mailOptions = {
from: 'Testing' <test#test.com>',
to: recipient,
bcc: 'test2#test.com',
subject: 'Testing Attachment functionality',
attachments: [
{
filename: 'attachment',
filePath: dataURI
},
],
html: '<p> Check the attachment</p>'
}
I receive a mail with the attachment, but it is a blank file the size of some bytes. For example, if I send the DataURI of a PNG file, I get a DAT file in my mailbox.
Has anybody encountered this issue?
It seems that my code was wrong. I updated to the most recent version of Nodemailer (v1+) and used the following code:
attachments: [
{
path: dataURI
}
]

Resources