如何使用几种SMTP配置发送带有凤凰/竹子的电子邮件



我正在使用Elixir/Phoenix开发后端。该后端将由几个前端使用,每个后端都需要使用其他SMTP服务器/配置发送电子邮件。

如何通过竹电子邮件实现这一目标?

我尚未对此进行测试,但我认为它可以起作用:

    # 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

您需要在运行时使用当前的竹设置进行此操作。有一个用于运行时配置的适配器。我使用它的原因是您使用它的原因。由于软件的用户可以在运行时更改配置,因此我必须将配置从数据存储中取出。

https://hexdocs.pm/bamboo_config_adapter/0.2.0/bamboo.configadapter.html#content

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

最新更新