Currently on my project I am dealing with a situation and I feel it is a problem of syntax but I am not getting the right answer and kinda feeling stressed and tilt over it for the last three days.
I am using three libraries NodeJs, Html-pdf(phantomJS) and Nodemailer.
this is the block of code in question (everything is inside a major async function that is a resolver of graphQl)
await pdf.create(html, options).toBuffer(async (err, buffer) => {
//i = new ;
//console.log(typeof(buffer))
await buffer;
await transporter.sendMail({
from: '"Example" example#example.com', // sender address
to: `${a1.dataValues.email}`, // list of receivers
subject: `${text2}`, // Subject line
text: `${text}`, // plain text body
html: `<p> ${text} </p>`, // html body
attachments: [
{
filename: `${a1.dataValues.kitID}.pdf`,
content: buffer,
contentType: "application/pdf",
},
],
});
});
The email is sent but I get this in the browser
The attachment is sent but I guess it is "undefined" and I have been struggling with finding a way to fix this. Can someone please help me?
I tried as well to do
attachments: [
{
filename: `${a1.dataValues.kitID}.pdf`,
content: new buffer.from(buffer),
contentType: "application/pdf",
},
],
attachments: [
{
filename: `${a1.dataValues.kitID}.pdf`,
content: new buffer(buffer),
contentType: "application/pdf",
},
],
attachments: [
{
filename: `${a1.dataValues.kitID}.pdf`,
content: new buffer.from(buffer,'base64'),
contentType: "application/pdf",
},
],
but all of those crash the app in Azure. The all thing works perfectly locally, but not when deployed.
Related
I am using mailgun(node js) to send an calendar invite, I am able to send invites but it is not adding to calendar automatically.
How we can automate this calendar invite to gmail, outlook calendar?
How can i achieve Yes, Maybe, No or RSVP or accept or reject options for both gmail and outlook using mailgun(node js) using ical-generator, Ex: var ical = require('ical-generator');?
gmail image
outlook image
Hi Robert,
Thanks for the your time and suggestion.
I have tried using the similar .ics file which gamil gives but it really didn't work to auto sync to calendar or "Yes", "No", "May be" options.
Here is the other example what i have written and trying auto calendar sync and "Yes", "MayBe", "No"options.
Using node module 'ical-generator'.
var ical = require('ical-generator');
var eventObj = {
'start' : '2022-06-02T06:59:52.653Z',
'end' : '2022-06-02T07:59:52.653Z',
'title': "Test mail",
'subject': 'Hey There, Im testing API',
'description': 'Hi User',
"Content-Type": "text/calendar,method=REQUEST",
"method": "REQUEST",
'url': "<domain>",
'id' : '125756xr378',
'organiser' : {'name' : 'Narendra M', 'email':'narendrahd#example.in'},
'location' : 'USA, main',
organizer: { name: 'Narendra M', email: 'narendrahd#example.in' },
attendees: [
{ name: 'Narendra M', email: 'narendrahd#example.in', rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
],
};
var cal = ical();
Creation of an event using ical.
cal.createEvent({
start: eventObj.start,
end: eventObj.end,
summary: eventObj.title,
method: eventObj.method,
uid: eventObj.id, // Some unique identifier
sequence: 0,
subject: eventObj.subject,
description: eventObj.description,
'Content-Type': "text/calendar,method=REQUEST",
location: eventObj.location,
organizer: {
name: eventObj.organiser.name,
email: eventObj.organiser.email
},
attendees: [
{ name: 'Narendra M', email: 'narendrahd#example.in', rsvp: true, partstat: 'ACCEPTED', role: 'REQ-PARTICIPANT' },
],
});
var path = __dirname + eventObj.id + '.ics';
cal.saveSync(path);
craetion of request and rest call to run mailgun API
var request = require('request');
var fs = require('fs');
var options = {
'method': 'POST',
'url': 'https://api.mailgun.net/v3/<domain>/messages',
'headers': {
'Authorization': 'Basic <token>'
},
formData: {
'from': 'noreply#dummy.in',
'to': ['narendrahd#example.in', 'iamnotveda#example.com'],
'subject': 'Hey There, Im testing API',
'text': 'Hi User',
// 'html': '\'<html><body><p>Hi User,</p></body></html>\'',
'attachment': [{
//'value': fs.createReadStream('/Users/invite.ics'),
'value': fs.createReadStream(path),
'options': {
'filename': 'invite.ics',
'contentType': "application/ics,method=REQUEST"
}
},
]
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Thanks in advance.
Narendra
I suspect partstat: 'ACCEPTED' for attendee could be a culprit here, consider changing it to 'NEEDS-ACTION'.
I recommend checking out this answer which doesn't use ical-generator. Export the raw iCal file and compare the output.
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.
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'
}
]
i want to attach zip file. but it doesn't work any attachment.
here is my source code.
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var fs = require('fs');
var mailinfo = require('../config/mail_info').info;
var smtpTransport = nodemailer.createTransport({
host: mailinfo.host,
port: mailinfo.port,
auth: mailinfo.auth,
tls: mailinfo.tls,
debug: true,
});
router.post('/',function(req,res){
var emailsendee = req.body.emailAddress;
console.log(emailsendee);
var emailsubject = "Requested File";
var emailText = "test";
var emailFrom = 'test#test.com';
var mailOptions={
from : "test <test#test.com>",
to : emailsendee,
subject : emailsubject,
html : '<h1>' + emailText+ '</h1>';
attachments : [
{
filename : '',//i just put black make you understand esaily
path : ''//what i did is under this code
}
]
};
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end();
}else{
console.log(response);
res.end();
}
});
});
module.exports = router;
i tried these for attaching a file
enter code here
attachments:[{ fileName: 'test.log', streamSource: fs.createReadStream('./test.log'}]
it still sends a mail without attachment.
when this code can't read a file there is a error.
so i guess this isn't working because of reading a file.
and i read some questions on stackoverflow which has similar error with me.
i fixed path -> filepath
and fixed streamSource -> path
my nodemailer version is 4.0.1.
help me send a mail with zip file.
I'm using exactly the same version of nodemailer(4.0.1 at this moment) and I'm sending emails with attachments successfully.
Your first code snippet looks promising :)
But the second part
i tried these for attaching a file
enter code here
attachments:[{ fileName: 'test.log', streamSource: fs.createReadStream('./test.log'}]
doesn't look right at all ...
Please refer to nodemailer docs
fileName and streamSource are not a valid parameters of mailOptions object
EXAMPLE FROM DOCS
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/nodemailer/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='
},
{
// use pregenerated MIME node
raw: 'Content-Type: text/plain\r\n' +
'Content-Disposition: attachment;\r\n' +
'\r\n' +
'Hello world!'
}
]
}
as you can see you should change fileName to filename and streamSource to content
// WRONG
attachments:[{ fileName: 'test.log', streamSource: fs.createReadStream('./test.log'}]
// RIGHT
attachments:[{ filename: 'test.log', content: fs.createReadStream('./test.log'}]
Good Luck! I hope this was helpful for you :)
I'm using nodemailer to send email with embedded images, but the images doesn't show up in message body in some email client app (eg thunderbird).
I'm suspecting this happened because of Content-Transfer-Encoding is set to quoted-printable. So it add 3D characters (which is encoding for = character) in src property of img element:
<img src=3D"cid:61767c3c-7f99-4f0f-a15b-b5edc0f0c2c4#emailaddress.com">
How to turn off quoted-printable encoding permanently in nodemailer ? I've tried to set textEncoding: 'base64' in message options, but it seems nodemailer ignore it.
let message = {
from: {
name: 'Someone',
address: 'someone#emailaddress.com'
},
to: {
name: sender,
address: emailTo.toLowerCase()
},
subject: 'Purchased Tickets',
html: 'Some text<br><img src="cid:61767c3c-7f99-4f0f-a15b-b5edc0f0c2c4#emailaddress.com"/><br>Some more text<br><img src="cid:1a419f12-1205-49e5-b0f7-fd407c0bfa27#emailaddress.com"/><br>',
attachments: ticketList.map((t, i) => ({
filename: `ticket${i + 1}.png`,
content: t.qrCode,
cid: `${t.ticketNumber}#emailaddress.com`
})),
encoding: 'base64',
textEncoding: 'base64'
}
transporter.sendMail(message, (err, info) => {
if (err) {
console.log(err)
} else {
console.log(info)
}
})
I have the same problem in some of my emails, but it does not appear to be related to Content-Transfert-Encoding.
Indeed, the images are displayed on some of my mails with
Content-Transfer-Encoding: quoted-printable
but not all...