LoginSignup
15
15

More than 5 years have passed since last update.

PythonでダミーのSMTPサーバ立ててActionMailerからの送信の動作確認まで

Last updated at Posted at 2016-02-02

RailsのActionMailerでの実装を動作確認するにあたってSMTPサーバが必要なんだけど、わざわざサーバ立てるのも大変なのでPythonでダミーのSMTPサーバを立ててみた。

ダミーのSMTPサーバを立てる

参考: Pythonでローカルでテストできる簡易SMTPサーバを立てる方法 - Qiita

上記のページを参考に以下のように起動

$ python -m smtpd -n -c DebuggingServer localhost:8025

telnetでSMTPサーバの動作を確認

とりあえず telnet でローカルのSMTPサーバに繋いで、SMTPサーバと会話してみる。

参考: telnetでメール送信

接続先のホストに localhost ポート番号は先ほど立ち上げたサーバのポート番号を指定

$ telnet localhost 8025
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 localhost.localdomain Python SMTP proxy version 0.2

HELOコマンドを入力しEnter(行頭の">"は入力行を表すもので実際は入力しない)

>HELO localhost
250 localhost.localdomain

送信者(from:)を入力

>MAIL FROM: hoge@example.com
250 Ok

宛先(to:)を入力

>RCPT TO: hoge+recipient@example.com
250 Ok

DATAコマンドを入力しメール本文を入力。"."のみの行を入力すると本文の入力は終了。

>DATA
354 End data with <CR><LF>.<CR><LF>
>Hello world.
>.
250 Ok

QUITコマンドでSMTPサーバから抜ける。

>QUIT
221 Bye
Connection closed by foreign host.

上記の手順を実行して SMTP サーバを起動したターミナルの画面に送信内容のログが表示されたたら疎通OK

Rails側からメール送信してみる

以下のように config/application.rb にActionMailerの設定を記述

config/application.rb
config.action_mailer.smtp_settings = {
   address: "localhost",
   port: 8025,
   domain: "localhost"
}

app/mailer/test_mailer.rb を作って以下のようにテストメール送信メソッドを定義

app/mailer/test_mailer.rb
class TestMailer < ActionMailer::Mailer
  default from: "hoge@example.com",
            to: "fuga@example.com"

  def test
    mail(subject: "test") do |format|
      format.text { render text: "This is test mail." }
    end
  end
end

上記の準備ができたら rails console を立ち上げ、以下のようにテストメールを送信してみる。

> TestMailer.test.deliver_now

上記の入力結果、SMTPサーバのターミナル出力を確認して"This is test mail."とメール本文が読めたらOK

参考

15
15
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
15
15