We're facing an issue while sending an attachment to a mail. Our scenario is something like, we're having a button "Send to My Email" which collects the logged-in user email and sends the filled form as a pdf to an email attachment. Everything is working fine on our local machine, but we're getting an error on the live testing site.
Our backend expressjs controller code:
const sendFormToEmail = async (req, res, next) => {
try {
const { formDetails } = req.body;
const to = formDetails?.email;
const from = "Our App Name here";
const subject = `Form Attachment`;
const html = emailTemplate({ formDetails });
let options = { format: "A4" };
let file = { content: html };
const pdfBuffer = await html_to_pdf.generatePdf(file, options);
await sendEmail({
to,
subject,
from,
html,
pdfBuffer,
filename: "form.pdf",
});
res.status(200).send({
status: true,
message: "Form sent to email successfully",
});
} catch (err) {
console.log("Error is ", err);
res.status(500).send({
status: false,
message: "Failed to send Form on an email",
});
}
};
sendEmail function code:
async function sendEmail({
to,
from,
subject,
text,
html,
pdfBuffer,
filename,
}) {
try {
const sendEmailResponse = await SENDGRID.send({
from,
to,
text,
html,
subject,
attachments: [
{
content: pdfBuffer.toString("base64"),
filename: filename,
type: "application/pdf",
disposition: "attachment",
},
],
});
console.log("EMAIL_SUCCESSFULLY_SEND: ", sendEmailResponse);
return true;
} catch (err) {
console.log(err.response.body.errors);
throw err;
}
}
The error we're facing:
Error is Error: Failed to launch the browser process!
/root/application-name/node_modules/html-pdf-node/node_modules/puppeteer/.local-chromium/linux-901912/chrome-linux/chrome: error while loading shared libraries: libatk-1.0.so.0: cannot open shared object file: No such file or directory
Please, help us in getting rid of this issue
So, basically, I found the solution for this here.
I'm using Sendgrid to send a transactional Email with Firebase Cloud Functions using Nodejs.
const attachment = file.createReadStream();
const msg = {
to: email,
from: "test#test.com",
subject: "print order",
templateId: "templateid",
dynamic_template_data: {
dashboardurl: `/order#${orderId}`,
downloadurl: orderData.downloadurl
},
attachments: [{
content: attachment,
filename: "order.pdf",
type: "application/pdf",
disposition: "attachment"
}]
};
await sgMail.send(msg);
The Email won't send, because of the following bug:
TypeError: Converting circular structure to JSON
Solution for Firebase Storage
const tempFilePath = path.join(os.tmpdir(), "tmp.pdf");
await file.download({ destination: tempFilePath });
const attachment = fs.readFileSync(tempFilePath, { encoding: "base64" });
According to doc:
For content you send base64 encoded version of the file.
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'recipient#example.org',
from: 'sender#example.org',
subject: 'Hello attachment',
html: '<p>Here’s an attachment for you!</p>',
attachments: [
{
content: 'Some base 64 encoded attachment content',
filename: 'some-attachment.txt',
type: 'plain/text',
disposition: 'attachment',
contentId: 'mytext'
},
],
};
So in your case below conversion would suffice:
const attachment = fs.readFileSync('filepath', { encoding: 'base64' });
My website careers page, User need to send their profile and then profile(doc or pdf) need to send as an attachment to the email on clicking submit button. Technologies I am using Angular6, NodeJs, Express, and Nodemailer to send the email.
Here is my peace of HTML code(careers.html),
<form (ngSubmit)="sendData()" >
<textarea [(ngModel)]="user.message"></textarea>
<input type="file" (change)="userProfile($event)" >
<small>Upload .docx or pdf file</small>
<button >Submit</button>
</form>
a bit of ts code (careers.ts),
user = {
message: '',
fileContent :''
};
userProfile(event: any) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.user.fileContent = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
sendData() {
this.careersService.sendWithAttachment(this.user);
}
here is service class(service.ts),
sendWithAttachment(userData) {
this.http.post("http://localhost:3000/uploadfile", userData
)
.subscribe(
data => {
console.log("Sent Request is successful ", data);
},
error => {
console.log("Error", error);
}
);
}
finally js file (app.js)
var mailOptions = {
from: '"User" <mail#gmail.com>', // sender address
to: "mail#mail.com", // list of receivers
subject: "Mail from Careers",
text: text,
html: html, // html body
attachments: [ {
filename: 'profile.pdf',
content: req.body.fileContent,
contentType: 'application/pdf'
}]
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
Now I am able to receive email with attachement but that attachement is empty or corrupted. Any help is much appreciated.
You need to upload the file on the server, Maybe you can do it though multer and then you can pass the server file path to the Nodemailer Function.
Here are some code snippet for your reference,
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/uploadfile', upload.single('profile'), function (req, res) {
var mailOptions = {
....
attachments: [{
filename: req.file.filename,
path: req.file.path
}]
};
...
})
Note : Attachment can be done in various methods in Nodemailer, Refer the documentation
I want to attach url to Email I used some solutions such as getting pdf url by request or read it as file but it didn't work.
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
var array = [],
temp = [];
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-
link_1.pdf');
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-
link_1.pdf');
array.forEach(function(data) {
temp.push({
path: data,
filename: 'hello.pdf'
});
const msg = {
to: 'example#example.com',
from: 'example#example.com',
subject: 'Test',
text: 'this is test',
html: '<strong>Hello World</strong>',
attachments: temp,
};
if ( temp.length == array.length )
sgMail.send(msg);
});
This is working solution for me. you can use request npm module to read your pdf file from any source but dont miss { encoding: null }.
const sgMail = require('#sendgrid/mail');
var request = require('request');
request.get('https://someurl/output.pdf',{ encoding: null },(err,res) => {
console.log(res);
var base64File = new Buffer(res.body).toString('base64');
sgMail.setApiKey('yourSendgridApiKey');
const msg = {
to: 'to#mail.com',
from: 'from#mail.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
attachments: [
{
content: base64File,
filename: 'some.pdf',
ContentType: 'application/pdf',
disposition: 'attachment',
contentId: 'mytext'
},
]
}
sgMail.send(msg, (error, data) => {
if (error) {
console.log('error', error)
} else {
console.log('successfully sent email' + data);
}
});
})
const sgMail = require('#sendgrid/mail');
const pdf2base64 = require('pdf-to-base64');
sgMail.setApiKey(apiKey);
const body = await sgMail.send({
to: email,
from,
subject: "subject",
html: "hello welcome",
...(
attachments && attachments.length && {
attachments:attachments.map(attachment=>({
content: attachment,
filename: "attachment.pdf",
type: "application/pdf",
disposition: "attachment"
}))
}
)
});
return body;
We have example from sendgird github. Noted: content must be string base64 encoded
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'recipient#example.org',
from: 'sender#example.org',
subject: 'Hello attachment',
html: '<p>Here’s an attachment for you!</p>',
attachments: [
{
content: 'Some base 64 encoded attachment content',
filename: 'some-attachment.pdf',
type: 'application/pdf',
disposition: 'attachment',
contentId: 'mytext'
},
],
};
I have code that send email with nodemailer in nodejs but I want to attach file to an email but I can't find way to do that I search on net but I could't find something useful.Is there any way that I can attach files to with that or any resource that can help me to attach file with nodemailer?
var nodemailer = require('nodemailer');
var events = require('events');
var check =1;
var events = new events.EventEmitter();
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "gmail",
auth: {
user: "example#gmail.com",
pass: "pass"
}
});
function inputmail(){
///////Email
const from = 'example<example#gmail.com>';
const to = 'example#yahoo.com';
const subject = 'example';
const text = 'example email';
const html = '<b>example email</b>';
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html
}
return mailOption;
}
function send(){
smtpTransport.sendMail(inputmail(),function(err,success){
if(err){
events.emit('error', err);
}
if(success){
events.emit('success', success);
}
});
}
///////////////////////////////////
send();
events.on("error", function(err){
console.log("Mail not send");
if(check<10)
send();
check++;
});
events.on("success", function(success){
console.log("Mail send");
});
Include in the var mailOption the key attachments, as follow:
var mailOptions = {
...
attachments: [
{ // utf-8 string as an attachment
filename: 'text1.txt',
content: 'hello world!'
},
{ // binary buffer as an attachment
filename: 'text2.txt',
content: new Buffer('hello world!','utf-8')
},
{ // file on disk as an attachment
filename: 'text3.txt',
path: '/path/to/file.txt' // stream this file
},
{ // filename and content type is derived from path
path: '/path/to/file.txt'
},
{ // stream as an attachment
filename: 'text4.txt',
content: fs.createReadStream('file.txt')
},
{ // define custom content type for the attachment
filename: 'text.bin',
content: 'hello world!',
contentType: 'text/plain'
},
{ // use URL as an attachment
filename: 'license.txt',
path: 'https://raw.github.com/andris9/Nodemailer/master/LICENSE'
},
{ // encoded string as an attachment
filename: 'text1.txt',
content: 'aGVsbG8gd29ybGQh',
encoding: 'base64'
},
{ // data uri as an attachment
path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
}
]}
Choose the option that adjust to your needs.
Link:Nodemailer Repository GitHub
Good Luck!!
Your code is almost right, just need to add, "attachments" property for attaching the files in your mail,
YOUR mailOption:
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html
}
Just add attachments like
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html,
attachments: [{
filename: change with filename,
path: change with file path
}]
}
attachments also provide some other way to attach file for more information check nodemailer community's documentation HERE
If you are passing options object in mail composer constructor and attachment is on http server then it should look like:
const options = {
attachments = [
{ // use URL as an attachment
filename: 'xxx.jpg',
path: 'http:something.com/xxx.jpg'
}
]
}
var express = require('express');
var router = express(),
multer = require('multer'),
upload = multer(),
fs = require('fs'),
path = require('path');
nodemailer = require('nodemailer'),
directory = path.dirname("");
var parent = path.resolve(directory, '..');
// your path to store the files
var uploaddir = parent + (path.sep) + 'emailprj' + (path.sep) + 'public' + (path.sep) + 'images' + (path.sep);
/* GET home page. */
router.get('/', function(req, res) {
res.render('index.ejs', {
title: 'Express'
});
});
router.post('/sendemail', upload.any(), function(req, res) {
var file = req.files;
console.log(file[0].originalname)
fs.writeFile(uploaddir + file[0].originalname, file[0].buffer, function(err) {
//console.log("filewrited")
//console.log(err)
})
var filepath = path.join(uploaddir, file[0].originalname);
console.log(filepath)
//return false;
nodemailer.mail({
from: "yourgmail.com",
to: req.body.emailId, // list of receivers
subject: req.body.subject + " ✔", // Subject line
html: "<b>" + req.body.description + "</b>", // html body
attachments: [{
filename: file[0].originalname,
streamSource: fs.createReadStream(filepath)
}]
});
res.send("Email has been sent successfully");
})
module.exports = router;
attachments: [
{
filename: "inovices_1.pdf", // the file name
path: "https://*************************/invoice/10_9_RMKUns.pdf",// link your file
contentType: "application/pdf", //type of file
},
{
filename: "inovices_2.pdf",
path: "https://**************************/invoice/10_9_RMKUns.pdf",
contentType: "application/pdf",
},
];
var nodemailer = require("nodemailer");
var all_transporter = nodemailer.createTransport({
host: process.env.MAIL_SERVICE,
port: 587,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
},
maxConnections: 3,
pool: true,
});
exports.send_email = function (email, subject, html, extra_cc = [], attachments = []) {
return new Promise(async (resolve, reject) => {
var mailOptions = {
from: process.env.MAIL_FROM_ADDRESS,
to: email,
subject: subject,
html: html,
cc: [],
};
mailOptions["cc"] = mailOptions["cc"].concat(extra_cc);
if (attachments.length > 0) mailOptions["attachments"] = attachments;
all_transporter.sendMail(mailOptions, function (error, info) {
// console.log(error);
// console.log(info);
if (error) {
resolve({ failed: true, err: error });
} else {
resolve({ failed: false, data: info.response });
}
});
});
};
The alternative solution is to host your images online using a CDN and link to the online image source in your HTML, eg. <img src="list_image_url_here">.
(I had problems with nodemailer's image embedding using nodemailer version 2.6.0, which is why I figured out this workaround.)
An added benefit of this solution is that you're sending no attachments to nodemailer, so the sending process is more streamlined.
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
}
}
});
Just look at here. Nodemailer > Message configuration > Attachments
The code snippet is below (pdfkit gets the stream):
// in async func
pdf.end();
const stream = pdf;
const attachments = [{ filename: 'fromFile.pdf', path: './output.pdf',
contentType: 'application/pdf' }, { filename: 'fromStream.pdf', content: stream, contentType: 'application/pdf' }];
await sendMail('"Sender" <sender#test.com>', 'reciver#test.com', 'Test Send Files', '<h1>Hello</h1>', attachments);
Stream uses content not streamSource This bothered me before, share with everyone :)
Reference = https://nodemailer.com/message/attachments/
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html,
attachments: [
{
filename: filename,
path: filePath
},
]
}