如何在 Strapi v4 的生命周期挂钩(beforeCreate/afterCreate)中访问并附加文件以使用 Nodemailer 发送电子邮件?

问题描述 投票:0回答:2

我使用 Strapi v4 作为后端,我想在内容类型的 beforeCreate 或 afterCreate 生命周期挂钩中使用 Nodemailer 发送电子邮件。我需要访问在创建内容期间上传的文件并将其附加到电子邮件中。这是我的代码示例:

beforeCreate: async (event) => {
  const ctx = strapi.requestContext.get();
  const { full_name, email } = JSON.parse(ctx.request.body.data);
  const file = ctx.request.files;
  const trackingCode = await strapi.config.helperFunction.generateRandomItn(event);
  
  try {
    const emailOptions = {
      to: email,
      subject: subject,
      html: content,
      attachments: [
        {
          filename: file.name,
          path: file.path,
        },
      ],
    };
    
    await strapi.plugins['email'].services.email.send(emailOptions);
    strapi.log.debug(`Email sent`);
  } catch (err) {
    strapi.log.error(`Error sending email`, err);
    throw new ApplicationError(`Error sending email: ${err}`);
  }
},

但是,我不确定如何在生命周期挂钩中正确访问该文件并将其附加到电子邮件中。我将不胜感激任何关于如何实现这一目标的指导或代码示例。

谢谢!

strapi nodemailer
2个回答
0
投票

您问题的简短回答是

you can’t anymore

这是由于关系没有填充到生命周期中,在某人拥有 100k 关系并且有 bug 的 Strapi 速度变慢之后。

无论如何可以部分回答:

所以你必须使用

afterUpdare
afterCreate

要获取数据,您必须使用额外的查询:

const data = await strapi.db.query('api:..').find({ where: { id: event.result.id }, populate { media: true } })

请注意,如果您使用 ts,您可能需要 ts-ignore (因为 Strapi 类型未对齐)

因此,您需要弄清楚自己的下一部分是实际读取文件的部分。我想你可以尝试这样的事情:

https://www.npmjs.com/package/fs-extra

const file = await fs.readFile(`${__dirname}/public/${media.url}`)

祝你好运!


0
投票

遇到了同样的问题,经过一番研究找到了解决方案。关系(如媒体)是同时建立的。因此,当实体创建时,您无法检索它们,但稍后可以获取它们。它对我有用。 不要忘记填充您的媒体数据。在我的示例中是“文件”

module.exports = {
    async afterCreate(event) {
        const {result} = event;

        const existingData = await strapi.entityService.findOne("api::job.job", result.id, {populate: ['file']});
        const mediaFileIsNullHere = existingData.file

        setTimeout(async () => {
            const existingData = await strapi.entityService.findOne("api::job.job", result.id, {populate: ['file']});
            const mediaFileIsAvailableHere = existingData.file
            
        // here send email with attached file

        }, 5000)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.