首页 > 解决方案 > 发送电子邮件的最正确方式是什么?

问题描述

我正在学习 TypeOrm,我正在尝试在用户创建帐户后实现电子邮件验证系统。

假设我有两个实体,用户和电子邮件验证。创建用户时,将在数据库中插入与该用户相关的 EmailVerification。下一步是在创建 EmailVerification 后立即向该用户发送电子邮件。

但我不确定使用什么 typeOrm 功能来调用我的电子邮件服务发送功能。

我在想两种方法来实现这一点,

1 - 在数据库中插入用户和电子邮件验证后,作为补充步骤的交易:

await getManager().transaction(async entityManager => {

  await entityManager.save(user);
  await entityManager.save(emailVerification);

  // send the message directly from the transaction right after the user and emailVerification is created
  await emailService.send(message);

})

2 - 在创建 EmailEntity 后立即从 EntitySubscriber :

@EventSubscriber()
export class EmailVerificationSubscriber implements EntitySubscriberInterface<EmailVerification> {
  @AfterInsert()
  sendEmail() {
    // ... //
    // get related user email
    // ... //
    
    // then send the message
    await emailService.send(message);
  }
}

这两种方法对我来说似乎足够了,但我想知道这个用例是否有某种最佳实践?

如果需要,我可以提供更多信息

标签: node.jstypeorm

解决方案


您选择哪个选项并不重要。

话虽如此,您发送的电子邮件是您插入emailVerification对象时开始的工作流程的一部分。因此,将其与该操作相关联是有意义的。

如果您将来使用类似的工作流程进行密码恢复,那么为什么这样做是有道理的就很明显了。


推荐阅读