4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swooshを使ってメール送信

Last updated at Posted at 2024-09-11
  • Elixirでできるだけ簡単にメール送信します
  • Swoosh.Adapters.Localを使ってローカル内でテストします

プロジェクト作成

$ mix phx.new mail_experiment --no-ecto
$ cd mail_experiment

ソースを書く

送信画面

lib/mail_experiment_web/live/mail_live/index.ex
defmodule MailExperimentWeb.MailLive.Index do
  use MailExperimentWeb, :live_view
  alias MailExperiment.Email
  alias MailExperiment.Mailer

  @impl true
  def mount(_params, _session, socket) do
    socket
    |> assign(:logs, [])
    |> then(&{:ok, &1})
  end

  @impl true
  def handle_event("send", _params, %{assigns: %{logs: logs}} = socket) do
    send_mail()

    socket
    |> assign(:logs, logs ++ ["送信しました #{DateTime.utc_now()}"])
    |> then(&{:noreply, &1})
  end

  def send_mail do
    Email.create_email()
    |> Mailer.deliver()
  end
end
lib/mail_experiment_web/live/mail_live/index.html.heex
<p class="text-2xl mb-10">メール送信</p>

<div class="flex flex-row">
  <button phx-click="send" class="rounded-lg bg-violet-600 w-12 px-2 text-white mr-3">送信</button>
  <a href="/dev/mailbox" target="_blank" class="rounded-lg bg-red-600 w-32 px-2 text-white">
    メールボックス
  </a>
</div>
<hr class="mt-10" />
<div class="">
  <%= for log <- @logs do %>
    <p><%= log %></p>
  <% end %>
</div>

ルーターの設定

lib/mail_experiment_web/router.ex
defmodule MailExperimentWeb.Router do
  # 〜省略〜
  scope "/", MailExperimentWeb do
    pipe_through :browser

+    live "/", MailLive.Index, :index

-     get "/", PageController, :home
+    # get "/", PageController, :home
  end
  # 〜省略〜
end

メール送信部分

lib/mail_experiment/email.ex
defmodule MailExperiment.Email do
  import Swoosh.Email

  def create_email() do
    new()
    |> to({"hoge", "hoge@local.local"})
    |> from({"YMN test", "ymn@local.local"})
    |> subject("Test mail")
    |> html_body("<h1>こんにちはhogeさん</h1>")
    |> text_body("こんにちはhogeさん\n")
  end
end

メールadapterの確認(今回は変更しません)

Swoosh.Adapters.Localであることを確認しました

config/config.exs
import Config
# 〜省略〜
config :mail_experiment, MailExperiment.Mailer, adapter: Swoosh.Adapters.Local
# 〜省略〜

実行

$ mix phx.server

http://localhost:4000にアクセス

  • 「送信」をクリック
  • 「メールボックス」をクリック

image.png

image.png

メール送信が確認でました

ソース(github)

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?