Reputation: 61
Can anyone help me with this? I am trying to attach files from firebase storage to an email using SendGrid from within firebase functions. Any help would be very much appreciated. I have got this far:
export const sendEmail2 = functions.https.onCall(async (data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'You must be logged in!');
}
const toEmail = data.toEmail;
const fromEmail = data.fromEmail;
const subject = data.subject;
const body = data.body;
const msg: any = {
to: toEmail,
from: fromEmail,
subject: subject,
html: body,
};
if (data.cc) {
msg.cc = data.cc;
}
if (data.attachments) {
msg.attachments = [];
let content;
data.attachments.forEach(
async (att: any) => {
const download = bucket.file(att.filepath);
const contents = await download.download();
content = contents[0].toString('base64');
msg.attachments.push({
content: content,
filename: att.filename,
type: att.type,
disposition: 'attachment',
content_id: att.content_id,
});
}
);
}
try {
await sgMail.send(msg);
} catch (e) {
return { error: e };
}
return { success: true };
});
Upvotes: 1
Views: 696
Reputation: 61
Finally solved it! The forEach loop doesn't appear to respect async. See below:
export const sendEmail2 = functions.https.onCall(async (data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'You must be logged in!');
}
const toEmail = data.toEmail;
const fromEmail = data.fromEmail;
const subject = data.subject;
const body = data.body;
const msg: any = {
to: toEmail,
from: fromEmail,
subject: subject,
html: body,
};
if (data.cc) {
msg.cc = data.cc;
}
if (data.attachments) {
msg.attachments = [];
let content;
let download;
let contents;
for (const att of data.attachments) {
download = bucket.file(att.filepath);
contents = await download.download();
content = contents[0].toString('base64');
msg.attachments.push({
content: content,
filename: att.filename,
type: att.type,
disposition: 'attachment',
content_id: att.content_id,
});
}
}
try {
await sgMail.send(msg);
} catch (e) {
return { error: e };
}
return { success: true };
});
Upvotes: 5