【问题标题】:Sending emails with Bamboo in a mix task在混合任务中使用 Bamboo 发送电子邮件
【发布时间】:2017-01-23 22:28:04
【问题描述】:

我想通过Bamboo 的混合任务发送电子邮件。这是任务的代码:

defmodule Mix.Tasks.SendEmails.Reminder do
  use Mix.Task
  import Mix.Ecto
  import Ecto.Query

  def run(_args) do
    Foobar.welcome_email |> MyApp.Mailer.deliver_now
  end
end

defmodule Foobar do
  import Bamboo.Email

  def welcome_email do
    new_email
    |> to("foo@example.com")
    |> from("me@example.com")
    |> subject("Welcome!!!")
    |> html_body("<strong>Welcome</strong>")
    |> text_body("welcome")
  end
end

当我运行这个混合任务时,我得到以下日志输出:

21:20:26.829 [debug] Sending email with Bamboo.LocalAdapter:

%Bamboo.Email{assigns: %{}, bcc: [], cc: [], from: {nil, 
"me@example.com"}, headers: %{}, html_body: "<strong>Welcome</strong>",
private: %{}, subject: "Welcome!!!", text_body: "welcome", to: 
[nil: "foo@example.com"]}

** (exit) exited in: GenServer.call(Bamboo.SentEmail, {:update, 
    #Function<2.18788267/1 in Bamboo.SentEmail.push/1>}, 5000)
    ** (EXIT) no process: the process is not alive or there's no 
    process currently associated with the given name, possibly 
    because its application isn't started
    (elixir) lib/gen_server.ex:729: GenServer.call/3
    lib/bamboo/sent_email.ex:109: Bamboo.SentEmail.push/1
    lib/bamboo/mailer.ex:121: Bamboo.Mailer.deliver_now/3
    lib/mix/tasks/send_emails.reminder.ex:30: anonymous fn/2 in Mix.Tasks.SendEmails.Reminder.run/1
    (elixir) lib/enum.ex:1755: Enum."-reduce/3-lists^foldl/2-0-"/3
    lib/mix/tasks/send_emails.reminder.ex:20: Mix.Tasks.SendEmails.Reminder.run/1
    (mix) lib/mix/task.ex:294: Mix.Task.run_task/3
    (mix) lib/mix/cli.ex:58: Mix.CLI.run_task/2
    (elixir) lib/code.ex:370: Code.require_file/2

我该如何解决这个问题? Bamboo 在 Phoenix 应用程序中运行良好。我只是无法让它在混合任务中运行。

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    出现此错误是因为 bamboo 未启动。

    启动单个应用程序

    根据您的情况,使用Application.ensure_all_started/2 启动特定应用程序:

    Application.ensure_all_started(:bamboo)
    

    启动所有应用程序

    在某些情况下,您可能希望启动所有应用程序: Mix.Tasks.App.Start 将启动在您的 mix.exs 配置中定义的所有应用程序:

    defmodule Mix.Tasks.SendEmails.Reminder do
      use Mix.Task
      import Mix.Ecto
      import Ecto.Query
    
      def run(_args) do
        Mix.Tasks.App.Start.run([]) # This will start all apps
        Foobar.welcome_email |> MyApp.Mailer.deliver_now
      end
    end
    

    【讨论】:

    • Application.ensure_all_started(:bamboo) 在这种情况下是更好的解决方案,因为您不会启动整个应用程序,只需启动所需的依赖项。
    • @PatNowak 是的,编辑了答案,Application.ensure_all_started 现在是主要解决方案。
    • 警告:你不应该 import Mix.Ecto 因为 Mix.Ecto 被认为是私有 API github.com/elixir-ecto/ecto/issues/1586#issuecomment-233301683
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2013-05-25
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    相关资源
    最近更新 更多