【问题标题】:Attachments from firebase using sendgrid使用 sendgrid 来自 firebase 的附件
【发布时间】:2020-06-04 14:18:43
【问题描述】:

谁能帮我解决这个问题?我正在尝试使用 Firebase 函数中的 SendGrid 将文件从 firebase 存储附加到电子邮件。任何帮助将不胜感激。我已经走到这一步了:

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 };

});

【问题讨论】:

  • 我对我的代码进行了一些更新。仍然不完全在那里,但我想我已经接近了。

标签: firebase function sendgrid


【解决方案1】:

终于解决了! forEach 循环似乎不尊重异步。见下文:

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 };
});

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多