【问题标题】:How can I send a email with Phoenix/Bamboo using several smtp configurations?如何使用多种 smtp 配置向 Phoenix/Bamboo 发送电子邮件?
【发布时间】:2018-02-23 20:14:30
【问题描述】:

我正在使用 Elixir/Phoenix 开发一个后端。该后端将被多个前端使用,每个前端都需要使用不同的 smtp 服务器/配置发送电子邮件。

如何使用竹电子邮件实现这一目标?

【问题讨论】:

  • 您是否尝试为每个 SMTP 创建邮件程序?据我所知,您只需要创建一个 Mailer 模块并设置其配置,如下所示:github.com/thoughtbot/bamboo#getting-started.
  • @Dogbert 必须根据数据库记录的执行时间动态设置配置

标签: smtp elixir phoenix-framework


【解决方案1】:

我没有对此进行测试,但我认为它可以工作:

    # In your config/config.exs file
    #
    # There may be other adapter specific configuration you need to add.
    # Be sure to check the adapter's docs. For example, Mailgun requires a `domain` key.
    config :my_app, MyApp.MandrillMailer,
      adapter: Bamboo.MandrillAdapter,
      api_key: "my_api_key"

    # Configure another adapter
    config :my_app, MyApp.SendGridMailer,
      adapter: Bamboo.SendGridAdapter,
      api_key: "my_api_key"

    # Somewhere in your application
    defmodule MyApp.MandrillMailer do
      use Bamboo.Mailer, otp_app: :my_app
    end

    defmodule MyApp.SendGridMailer do
      use Bamboo.Mailer, otp_app: :my_app
    end

    # Define your emails
    defmodule MyApp.Email do
      import Bamboo.Email

      def welcome_email do
        new_email(
          to: "john@gmail.com",
          from: "support@myapp.com",
          subject: "Welcome to the app.",
          html_body: "<strong>Thanks for joining!</strong>",
          text_body: "Thanks for joining!"
        )

        # or pipe using Bamboo.Email functions
        new_email
        |> to("foo@example.com")
        |> from("me@example.com")
        |> subject("Welcome!!!")
        |> html_body("<strong>Welcome</strong>")
        |> text_body("welcome")
      end
    end

    # In a controller or some other module
    # Use the MandrilMailer to send this message
    Email.welcome_email |> MandrillMailer.deliver_now

    # You can also deliver emails in the background with Mailer.deliver_later
    # Use the SendGridMailer to send this message
    Email.welcome_email |> SendGridMailer.deliver_later

按照您的要求,使用不同的适配器进行发送更加动态:

    defmodule MyApp.Mailer do
      # Map all your defined mailers here
      @adapters %{
        mandrill: MyApp.MandrillMailer,
        send_grid: MyApp.SendGridMailer
      }

      def for(adapter \\ :mandrill) do
        Map.fetch!(@adapters, adapter)
      end
    end

    # Mail service can be stored in db record
    mail_service = :send_grid
    Email.welcome_email |> MyApp.Mailer.for(mail_service).deliver_now

【讨论】:

    【解决方案2】:

    您需要在运行时使用当前的 Bamboo 设置执行此操作。有一个用于运行时配置的适配器。我使用它的原因与您使用它的原因相同。我必须从数据存储中获取配置,因为软件用户可以在运行时更改配置。

    https://hexdocs.pm/bamboo_config_adapter/0.2.0/Bamboo.ConfigAdapter.html#content

    我希望这会有所帮助。如果您有任何问题,可以将它们放在库的 GitHub 问题中,我很乐意提供帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      相关资源
      最近更新 更多