nodemailer attachment is not working - node.js

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 :)

Related

Convert spread sheet to excel using App script

I'm trying to send a spreadsheet file as Excel via mail. The mail is sent successfully but the file can't be opened due to incorrect format (I need an xlsx file.)
The code I used is below.
var folders = DriveApp.getFolderById('folder_id')
var files = folders.getFiles();
if (files.hasNext())
{
file = files.next();
url = file.getUrl();
var params = {
method: "get",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setContentType(MimeType.MICROSOFT_EXCEL).setName(fileName + ".xlsx");
MailApp.sendEmail(email_ids, 'Sample Subject', 'Mail with attachment', {
attachments: [blob],
name: 'Automatic Emailer Script',
cc:email_id
})
replace
url = file.getUrl();
with
url = SpreadsheetApp.openById(id).getUrl().replace(/edit$/, 'export?format=xlsx')

NodeJs Buffer is not attached to Nodemailer file

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.

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'
}
]

How to upload assets to a github release from node.js

I am trying to automatically post some assets on a Github release I programmatically create.
Here is my upload function:
function uploadFile(fileName, uploadUrl, callback){
var uploadEndPoint = url.parse(uploadUrl.substring(0,uploadUrl.indexOf('{')));
options.host = uploadEndPoint.hostname;
options.path = uploadEndPoint.pathname+'?name=' + fileName;
options.method = 'POST';
options.headers['content-type'] = 'application/zip';
var uploadRequest = https.request(options, callback);
uploadRequest.on('error', function(e) {
console.log('release.js - problem with uploadRequest request: ' + e.message);
});
var readStream = fs.ReadStream(path.resolve(__dirname,'builds',fileName));
readStream.pipe(uploadRequest);
readStream.on('close', function () {
req.end();
console.log('release.js - ' + fileName + ' sent to the server');
});
}
At the end of this I get a 404 not found
I tried auth from token and user/password
I checked the url
I though it might be because of SNI, but I don't know how to check that.
Any clue ? Thanks !
I found a solution to that problem by NOT using the low level node.js modules and using instead restler which is a library that handles SNI.
Here is how is used it:
rest = require('restler'),
path = require('path'),
fs = require('fs');
fs.stat(path.resolve(__dirname,'builds',fileName), function(err, stats){
rest.post(uploadEndPoint.href+'?name=' + fileName, {
multipart: true,
username: GITHUB_OAUTH_TOKEN,
password: '',
data: rest.file(path.resolve(__dirname,'builds',fileName), null, stats.size, null, 'application/zip')
}).on('complete', callback);
});
Hope that will help someone :)
EDIT on 27/02/2015: We recently switched from restler to request.
var
request = require('request'),
fs = require('fs');
var stats = fs.statSync(filePath);
var options = {
url: upload_url.replace('{?name}', ''),
port: 443,
auth: {
pass: 'x-oauth-basic',
user: GITHUB_OAUTH_TOKEN
},
json:true,
headers: {
'User-Agent': 'Release-Agent',
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/zip',
'Content-Length': stats.size
},
qs: {
name: assetName
}
};
// Better as a stream
fs.createReadStream(filePath).pipe(request.post(options, function(err, res){
// Do whatever you will like with the result
}));
The upload_uri can be retrieved through a get request on an existing release or in the response directly after the release creation.

Resources