【问题标题】:Is there a way to get ethereal email message ID in node.js through SendGrid?有没有办法通过 SendGrid 在 node.js 中获取空灵的电子邮件消息 ID?
【发布时间】:2021-09-25 03:01:06
【问题描述】:

我目前正在将 SendGrid 用作 Web 应用程序中的电子邮件服务,并且我想设置我的开发环境以将电子邮件发送到 https://ethereal.email/,以便确保它们看起来正确。我目前设置它的方式是我将在启动时使用nodemailer.createTestAccount(),然后记录凭据,然后如果我需要查看电子邮件,我必须手动转到 ethereal 站点登录并查看所有电子邮件。

由于我使用 SendGrid 发送消息,我不能只使用nodemailer.getTestMessageUrl(info),但我真的希望能够在每次在 dev 中发送电子邮件时记录 URL,然后我可以直接去到消息。

我已经尝试过打印 SendGrid 响应,以及通过 IMAP 连接并加载最新消息,但这些都没有在我能看到的任何地方包含消息 ID。

有什么方法可以获取发送到 ethereal.email 的电子邮件的消息 ID 并直接构造一个指向该消息的 URL?

我的环境是 node.js,我使用@sendgrid/mail 来发送消息。

谢谢!

【问题讨论】:

    标签: javascript node.js sendgrid nodemailer


    【解决方案1】:
    推荐的答案 Twilio

    这里是 Twilio SendGrid 开发人员宣传员。

    Nodemailer documentation here 建议您使用 ethereal.email 作为开发中的 SMTP 设置。然后您可以使用nodemailer.getTestMessageUrl(info) 获取正确的网址。

    您说您正在使用@sendgrid/mail 发送消息,因为它不是通过ethereal.email SMTP 服务器发送出去的,所以它不会响应URL。如果您确实需要该 URL,最好的办法是将开发/测试环境中的 SendGrid 替换为 ethereal.email。

    您可以通过使用相同的接口创建自己的电子邮件发送对象来做到这一点,一个用于@sendgrid/mail,另一个用于具有 ethereal.email 凭据的 Nodemailer,并根据环境加载所需的对象。

    例如:

    class SendGridEmail {
      constructor(sgApiKey) {
        // construct SG mail object
      }
    
      sendEmail(options) {
        // use SG mail object to send email
      }
    }
    
    class NodemailerEmail {
      constructor() {
      }
    
      sendEmail(options) {
      }
    }
    
    function getMailer() {
      if (process.env.NODE_ENV === "production") {
        return new SendGridEmail(process.env.SG_API_KEY);
      } else {
        return new NodemailerEmail();
      }
    }
    
    // later
    
    getMailer().sendEmail(options);
    

    【讨论】:

    • 感谢您的回复!问题是我使用的是 SendGrid 的动态模板,所以我没有可以通过 nodemailer 使用的电子邮件对象。我目前只是用一个虚幻的帐户替换接收器,但仍在使用 SendGrid API。
    • 据我从空灵的文档中得知,获取邮件 URL 的唯一方法是通过他们的 SMTP 服务器发送电子邮件。因此,如果您仍然需要从 SendGrid 发送,则无法直接获取该 URL。如果您想设置更多自动化测试,我确实看到 this post on using ethereal and SendGrid with Cypress 自动测试可能有用的电子邮件。
    猜你喜欢
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多