【问题标题】:How to send zip file using @sendgrid/mail如何使用@sendgrid/mail 发送 zip 文件
【发布时间】:2019-01-22 05:41:41
【问题描述】:

这是我编写的使用@sendgrid 发送带有附件的电子邮件的代码

  const mailOptions = {}
  if(mailOptions){
    mailOptions.from = 'APP NAME'
    mailOptions.to = 'emailId'
    mailOptions.subject = 'Subject' // Subject line
    //mailOptions.attachments = attachments
    mailOptions.text = 'attachments'
  }
  const sendEmail = await sgMail.send(mailOptions)

但它只发送主题为“无附件”的邮件

取消注释 attachment 行时出现的错误

{ Error: Bad Request
    at Request.http [as _callback] (node_modules/@sendgrid/client/src/classes/client.js:124:25)

为什么会发生这种情况,请有人帮助我。

【问题讨论】:

  • 您可能会收到来自 SendGrid 的 API 的 400 Bad Request 响应。尝试关注 SendGrid 的 error troubleshooting guidelines 以获取他们的节点库。
  • 当我不发送附件时,我可以收到电子邮件。

标签: javascript node.js email sendgrid


【解决方案1】:

这个问题已经有一段时间没有提出来了,现在回答一下以供将来参考。

为了修复错误,附件必须具有 Base64 编码 - 并且其文件类型应设置为“应用程序/zip”。要输入的 .js 代码也已大幅更新。今天的示例如下所示

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const fs = require("fs");

pathToAttachment = `${__dirname}/attachment.zip`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");

const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Subject',
  text: 'Sent using Node.js',
  attachments: [{
    content: data.toString('base64'),
    filename: filename,
    type: fileType,
    disposition: 'attachment',
  }, ],
};
sgMail.send(msg).catch(err => {
  console.log(err);
});

编码愉快!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    相关资源
    最近更新 更多