I've created a Firebase Function that, upon click, will get a PDF from Firebase Storage, attach it to an email and send it via SendGrid.
I have no problem getting the PDF Storage URLs and sending the email, but I'm not able to attach the PDFs. I've tried referencing the SendGrid documentation and it seems like the fs.readFileSync function doesn't work on URLs.
How can I get the data from Firebase to be able to stringify it to base64? I've tried reading the Firebase documentation as well but can't seem to be able to figure out a solution. Any help would be greatly appreciated!
Function that successfully grabs all Document URLs from Firebase Storage
const getDocumentURLs = () => {
firebase
.storage()
.ref("Tenant Resumes/" + tenantID)
.listAll()
.then((res) => {
res.items.forEach((result) => {
result.getDownloadURL().then((docURL) => {
setDocumentData((newURLs) => [...newURLs, docURL]);
console.log(docURL);
});
});
}); };
And the firebase function (the console.log gives an error that says "Not an object" - assuming this is because I'm passing a string URL not an actual file)
exports.sendTenantMail = functions.https.onCall((data, res) => {
const name = data.name;
const email = data.email;
const documents = data.documents;
const documentOne = fs.readFileSync(data.documentOne).toString("base64");
const documentTwo = fs.readFileSync(data.documentTwo).toString("base64");
const documentThree = fs.readFileSync(data.documentThree).toString("base64");
const documentFour = fs.readFileSync(data.documentFour).toString("base64");
const documentFive = fs.readFileSync(data.documentFive).toString("base64");
const documentSix = fs.readFileSync(data.documentSix).toString("base64");
const realtorEmail = data.realtorEmail;
console.log(fs.readFileSync(data.documentOne).toString("base64"));
const msg = {
to: "concierge#chexy.co",
from: "concierge#chexy.co",
templateId: "d-1aec2e98c1af44fdb0e1f97d540c6973",
dynamicTemplateData: {
subject:
"A new tenant resume has been submitted by " +
email +
" for " +
realtorEmail,
name: name,
},
attachments: [
{
content: documentOne,
filename: "Doc1.pdf",
type: "application/pdf",
disposition: "attachment",
},
],
};
sgMail.send(msg).catch((err) => {
console.log(err);
});
});
Any help would be huge!
Related
I am able to get the files as mail attachments from office 365 mail, I am able to then create the files on one drive. However all of the files are corrupt and cannot be opened. I can console log the files being created and I see the information - I am not sure what the problem is. Someone please help. I attached the function below.
using cloud functions we invoke the office graph api. this works, all of it works as expected but the files are all corrupt. They do show up on one drive and are the correct size.
export const getAttachmentsSaveOneDrive = functions.https.onCall(async (data, context)=>{
if(context?.auth){
// user id
const uid = data.id as string;
// folder id
const folderId = data.folderId as string;
// folder name
const folderName = data.folderName as string;
return await client
.api('/users/' + uid as string +'/mailFolders/'+folderId as string+'/messages').filter("hasAttachments eq true&$select=id").get()
.then(async(res)=>{
const messagefilter = Promise.resolve([res.value]);
// return messagefilter
(await
// return messagefilter
messagefilter).forEach(element => {
element.forEach(async (item:any) => {
console.log(item.id)
await client.api('/users/' + uid as string +'/mailFolders/'+folderId as string+'/messages/'+item.id as string+'/attachments').expand('microsoft.graph.itemattachment/item').get().then(async (res_item)=>{
(await res_item.value).forEach(async (aitem:any) => {
let driveItem = {
"name": aitem.name as string,
"contentType": "text/plain",
"isInline": aitem.isInline,
"contentBytes": aitem.contentBytes as string,
file: {
},
'#microsoft.graph.conflictBehavior': 'rename',
}
console.log('DRIVE ITEM', driveItem)
await client.api('/users/' + uid as string +'/drive/root:/'+folderName+'/'+aitem.name+':/content').put(driveItem).then(async (res_create)=>{
console.log('RES_CREATE', res_create)
})
});
})
});
});
});
}
});
I am trying to show an image inside my e-mail. But that image is not getting displayed. I am using base64 string, which I am fetching from S3 bucket.
I am able to get email in inbox, but only thing image is not working when passing url, if directly using base64 hard coded string in html its working.
I need to fetch image from s3 and that image should be inline with email.
"use strict";
const fs = require("fs");
const path = require("path")
const Handlebars = require('handlebars');
const {SESClient, sendEmailCommand} = require("#aws-sdk/client-ses");
const {S3Client, GetObjectCommand} = require("#aws-sdk/client-s3");
let S3=null, SES=null;
const streamToBuffer = async(stream) =>{
return new Promise((resolve, reject) =>{
const chunks = [];
stream.on("data", (chunk) =>{chunks.push(chunk)});
stream.on("error", reject);
stream.on("end", () =>{resolve(Buffer.conact(chunks))});
})
}
export.handler = async(event) =>{
if(S3 === null){
S3 = new S3Client ({region: MY_REGION})
}
if(SES === null){
SES = new SESClient ({region: MY_REGION})
}
try{
let deatils = event.detail.fullDocument;
let imageKey = `${deatils.dir}/myimage.png`;
let imageFileFromS3 = await S3.send(
new GetObjectCommand({
Bucket: MY_BUCKET_NAME, key: imageKey
}))
let imageFileBuffer = await streamToBuffer(imageFileFromS3.Body)
let bufferToBase64 = imageFileBuffer.toString("base64");
const emailSubject = "Hey!! Test mail with image";
const emailData = {
Name: "Email Tester"
ImageSrc: `data:image/png;base64, ${bufferToBase64}`
}
let htmlTemplate = Handlebars.complie(fs.readFileSync(path.join(__dirname, 'templateSrc', email.html)).toString())
let textTemplate = Handlebars.complie(fs.readFileSync(path.join(__dirname, 'templateSrc', email.txt)).toString())
let emailResult = await SES.send( new SendEmailCommand({
Source: "Source_test#email.com", //dummy email for now
Destination :{
ToAddress: ["to_test#email.com"] // dummy address
},
Message: {
Subject: {
Charset: 'UTF-8',
Data: emailSubject
},
Body: {
Text: {
Charset: 'UTF-8',
Data: textTemplate(emailData)
},
Html:{
Charset: 'UTF-8',
Data: htmlTemplate(emailData)
}
}
}
}))
return emailResult
}catch(error){
console.log(error)
}
}
email.txt
Dear {{Name}}
Thanks for asking images on email.
Please find your requested images below
Face image
Bus image
-----Thanks
Email.html
<h1>Dear {{Name}}</h1>
<p>Thanks for asking images on email.</p>
<p>Please find your requested image below</p>
<p>face Image</p>
<img src={{ImageSrc}} />
<p>Bus Image</p>
<img src="data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNS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yADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==">
//This image is working
<p>-------Thanks</p>
I have just resolved this issue...
So I thought, about posting answer for others help.
The root cause of this was- large size of my buffer response form S3, and email only supports 128MB data, as I found in cloud watch logs ( I can comment about AWS SES only, not sure about other email clients)
So the ultimate solution for my problem is just to resize the buffer response, which we are getting from S2.
So I have used sharp https://www.npmjs.com/package/sharp
And add these line in index.js
//Here I will resize the image
const resizedImageFileBuffer =
await sharp(imageFileBuffer)
.resize ({
width:200,
height:200,
fit: 'contain'
})
.toFormat('png')
.png({
quality:100,
compressionLevel: 6
})
.toBuffer()
//Now we will convert resized buffer to base64
let bufferToBase64 =
resizedImageFileBuffer.toString("base64");
I have created a Firebase cloud function that will trigger on update of the data. When I go into Firebase console and change the node to either true or false, it triggers and I receive an email from my SendGrid set up. The problem is I am not able to obtain the users e-mail information.
I have spent over a week pouring over the documentation and it says I should be able to use context.auth, however, that is always "undefined" when printed out in console.
I have been trying to get the user data from the users actual info in Firebase as well as in /users/{uid}/email. I can't seem to figure out how to get the e-mail since the snapshot is in a different spot.
I need to somehow extract the users first name and email, which are in in:
/users/uid/first_name and /users/uid/email
I want those two things put into this function, so then I can tell SendGrid to use the email and name. The Sendgrid portion is working fine.
context.params.uid gives me the users firebase ID, but does nothing for me. I can't seem to use that to get the data I need
I tried authVar = context.auth and when I print it out it says 'undefined' and my function stops working.
exports.myFunctionPending =
functions.database.ref('/users/{uid}/profile/isPending')
.onUpdate(async (change, context) => {
const snapshot = change.after;
const val = snapshot.val();
const userid = context.params.uid; //shows userid but is useless
const authVar = context.auth; //says undefined and does nothing
console.log(val);
console.log(userid);
const msg = {
to: 'myemail#mydomain.com',
from: 'noreply#mydomain.com',
// custom templates
templateId: 'd-b7aakjsdgwq7d798wq7d8',
substitutionWrappers: ['{{', '}}'],
//substitutions: {
dynamic_template_data: {
//name: user.displayName
name: 'My Name'
}
};
try {
await sgMail.send(msg);
console.log('This was sucessful');
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return null;
});
I had the code in the incorrect spot, I changed the logic and now it's working as intended.
exports.myFunction = functions.database.ref('/users/{uid}/user_area/pending')
.onUpdate(async (change, context) => {
const triggersnapshot = change.after;
const val = triggersnapshot.val();
const userid = context.params.uid;
console.log(val);
console.log(userid);
return admin.database().ref('users/' + userid).once('value').then(function (snapshot) {
var email = snapshot.child('email');
var name = snapshot.child('first_name');
console.log(snapshot.val());
console.log(email.val());
const msg = {
to: [email],
from: {
email: 'noreply#noreply.com',
name: 'No Name'
},
// custom templates
templateId: 'd-8347983274983u483242',
substitutionWrappers: ['{{', '}}'],
dynamic_template_data: {
name: name
}
};
return sgMail.send(msg);
});
I have been trying to get this to work, but am new to NodeJS. I suspect the issue is due to async, but am not familiar with how it works.
The idea behind this code is that it monitors a firebase database change and sends an email to the users. I am getting everything from the change snapshot, and using the values to check another table for user data. The request is not returning before the email gets sent and I am unsure why.
Edit I should specify that the email function sgMail is firing off before I get the results from the requests. I've tried putting a delay, but I am still not getting the result to return in time.
Here's my index.js
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
var requestify = require('requestify');
//SendGrid
const SENDGRID_API_KEY = functions.config().sendgrid.key;
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.packingListEmail = functions.database.ref('Order/{orderID}')
.onUpdate(event => {
// Grab the current value of what was written to the Realtime Database.
const eventSnapshot = event.data;
//Here You can get value through key
var shipperInfo = eventSnapshot.child("fk_shipper_id").val();
var travelerInfo = eventSnapshot.child("fk_traveler_id").val();
//Print value of string
console.log(shipperInfo);
//Get Shipper Info
const shipperPath = 'https://shlep-me-f516e.firebaseio.com/User/'+shipperInfo+'.json';
requestify.get(shipperPath)
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
shipperResult = response.getBody();
console.log(shipperResult.email);
return shipperResult;
});
function getTravelerData() {
return new Promise(resolve => {
requestify.get('https://shlep-me-f516e.firebaseio.com/User/' + travelerInfo + '.json')
.then(function (response) {
resolve(response.getBody())
});
});
}
var TravelD = getTravelerData();
//Send an email
const msg = {
to: 'andrew#shlepme.com',
from: 'support#shlepme.com',
subject: 'New Follower',
// text: `Hey ${toName}. You have a new follower!!! `,
// html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
// custom templates
templateId: 'd1ccfeb9-2e2d-4979-a3ca-c53975fe486e',
substitutionWrappers: ['%', '%'],
substitutions: {
'%shipper_name%': "Test",
'traveler_name': TravelD.name
// and other custom properties here
}
};
console.log('Sending email');
console.log(TravelD);
return sgMail.send(msg)
});
Any ideas? I have been trying to figure this out.
It seems that you need to understand about Promises first.
When you start using promises you will need to ALWAYS use them and chain one with the other.
So I would rewrite your code like this: (not tested)
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require("firebase-functions");
var requestify = require("requestify");
//SendGrid
const SENDGRID_API_KEY = functions.config().sendgrid.key;
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(SENDGRID_API_KEY);
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.packingListEmail = functions.database
.ref("Order/{orderID}")
.onUpdate(event => {
// Grab the current value of what was written to the Realtime Database.
const eventSnapshot = event.data;
//Here You can get value through key
var shipperInfo = eventSnapshot.child("fk_shipper_id").val();
var travelerInfo = eventSnapshot.child("fk_traveler_id").val();
//Print value of string
console.log(shipperInfo);
//Get Shipper Info
const shipperPath = "https://shlep-me-f516e.firebaseio.com/User/" + shipperInfo + ".json";
requestify.get(shipperPath)
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
var shipperResult = response.getBody();
console.log(shipperResult.email);
return shipperResult;
})
.then(function (shipperResult) {
//Send an email
const msg = {
to: "andrew#shlepme.com",
from: "support#shlepme.com",
subject: "New Follower",
// text: `Hey ${toName}. You have a new follower!!! `,
// html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
// custom templates
templateId: "d1ccfeb9-2e2d-4979-a3ca-c53975fe486e",
substitutionWrappers: ["%", "%"],
substitutions: {
"%shipper_name%": "Test",
traveler_name: shipperResult.name
// and other custom properties here
}
};
console.log("Sending email");
console.log(shipperResult);
return sgMail.send(msg);
});
});
I'm developing a Firebase Function, which is triggered when a new order is added to the Realtime Database. The first thing it does is to creat a pdf and pipe it to a google cloud storage bucket.
On the .on("finish") event of the bucket stream, the next function gets started, which should send the piped pdf via email to the customer.
Everything seems to work, at least a bit.
First I had the problem, that the attached pdf always was empty. (Not just blank. I also opened it in notepad++ and it really was all empty). When I checked the doc and bucketFileSream vars inside the bucketFileStream.on("finished") function both had a length of 0. A check of the doc var directly after doc.end showed a length of somewhat 612.
I then changed the flow, that in the sendOrderEmail function I also open a new Read Stream from the newly created File in the bucket.
Now I get at least some stuff of the PDF in the attachement, but never the whole content.
When I check the PDF uploaded to the bucket, it looks like it should.
I googled alot and found some answers that were also targeting this topic, but as also seen in comments on these questions, they were not completly helpful.
PDF Attachment NodeMailer
Where to generate a PDF of Firebase Database data - mobile app, or Firebase Hosting web app
How to attach file to an email with nodemailer
I also checked with the nodemailer documentation how to pass the attachement correctly and implemented it as documented. But no success.
I think that the mail gets sent before the Read Stream has finished.
Here the Package Versions I use:
"#google-cloud/storage": "1.5.2"
"#types/pdfkit": "^0.7.35",
"firebase-admin": "5.8.0",
"firebase-functions": "^0.7.3"
"nodemailer": "4.4.1",
Can anyone tell me what I'm doing wrong or provide a working example, which uses current package versions, for this usecase?
Here is the code which drives me crazy...
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const nodemailer = require("nodemailer");
const pdfkit = require("pdfkit");
const storage = require("#google-cloud/storage")({projectId: `${PROJECT_ID}`})
const mailTransport = nodemailer.createTransport({
host: "smtp.office365.com",
port: 587,
secureConnection: false,
auth: {
user: "userName",
pass: "userPassword"
},
tls: {
ciphers: "SSLv3",
}
});
exports.added = function(event) {
const order = event.data.val();
const userId = event.params.userId;
// Load User Data by userId
return admin
.database()
.ref("/users/" +userId)
.once("value")
.then(function (snapshot) {
return generateOrderPDF(snapshot.val(), userId);
});
};
function generateOrderPDF(user, userId) {
const doc = new pdfkit();
const bucket = storage.bucket(functions.config().bucket);
const filename = `/${userId}/test-` + Date.now() + ".pdf";
const file = bucket.file(filename);
const bucketFileStream = file.createWriteStream();
// Pipe its output to the bucket
doc.pipe(bucketFileStream);
// Do creation Stuff....
doc.end();
bucketFileStream.on("finish", function () {
return sendOrderEmail(user, filename);
});
bucketFileStream.on("error", function(err) {
console.error(err);
});
}
function sendOrderEmail(user, filename) {
const email = user.email;
const firstname = user.firstName;
const mailOptions = {
from: "test#test.test",
to: email,
subject: "Order"
};
const bucket = storage.bucket(functions.config().bucket);
const file = bucket.file(filename);
mailOptions.html = mailTemplate;
mailOptions.attachments = [{
filename: "test.pdf",
content: file.createReadStream()
}];
return mailTransport.sendMail(mailOptions).then(() => {
console.log("New order email sent to:", email);
}).catch(error => {
console.error(error);
});
}
The problem in my appraoch was inside the pdfkit library and not inside nodemailer or firebase. The lines below seem to trigger the end event. So the pdf got sent after these lines. After out commenting them everything worked as it should. It was not that finish was never reached like Hari mentioned.
/* doc.lineCap("underline")
.moveTo(72, 321)
.lineTo(570, 321)
.stroke();*/
After finishing the MVP I will take a root cause analysis and post the final answer as comment below this answer.
This is a working sample of Source-Code for this UseCase. It also ensures, that the firebase function won't finish before all work is done. That is handled by wrapping the event driven doc.on() function into a promise, that is resolved when doc.on("end") is called.
exports.added = function(event) {
const order = event.data.val();
const userId = event.params.userId;
// Load User Data by userId
return admin.database().ref("/users/" + userId).once("value").then(function (snapshot) {
return generatePDF(snapshot.val(), userId);
});
};
function generatePDF(user, userId) {
const doc = new pdfkit();
const bucket = admin.storage().bucket(functions.config().moost.orderbucket);
const filename = "/${userId}/attachement.pdf";
const file = bucket.file(filename);
const bucketFileStream = file.createWriteStream();
var buffers = [];
let p = new Promise((resolve, reject) => {
doc.on("end", function() {
resolve(buffers);
});
doc.on("error", function () {
reject();
});
});
doc.pipe(bucketFileStream);
doc.on('data', buffers.push.bind(buffers));
//Add Document Text and stuff
doc.end();
return p.then(function(buffers) {
return sendMail(buffers);
});
}
function sendMail(buffers) {
const pdfData = Buffer.concat(buffers);
const mailOptions = {
from: "FromName <from#example.com>",
to: "to#example.com",
subject: "Subject",
html: mailTemplate,
attachments: [{
filename: 'attachment.pdf',
content: pdfData
}]
};
return mailTransport.sendMail(mailOptions).then(() => {
console.log("New email sent to:", "to#example.com");
}).catch(error => {
console.error(error);
});
}
The main problem in your code is that the stream.on('finish') never completes. I've also encountered the same issue.
Instead of streaming, convert the pdf into buffer and send the same as attachment.
The following works fine for me,
const doc = new pdfkit()
const filename = '/${userId}/test-' + Date.now() + ".pdf"
const file = bucket.file(filename);
const bucketFileStream = file.createWriteStream();
doc.pipe(bucketFileStream);
doc.end();
var buffers = []
doc.on('data', buffers.push.bind(buffers));
doc.on('end',function(){
let pdfData = Buffer.concat(buffers);
'<<nodemailer stuffs goes here>
'attach the doc as content
});