0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rails8 開発環境でメール送信を設定する方法(Gmail SMTP使用)

Last updated at Posted at 2025-08-24

はじめに

Railsアプリケーションの開発環境でメール送信機能を実装する際、実際にメールを送信してテストしたいことがあります。本記事では、GmailのSMTPサーバーを使用して開発環境でメール送信を設定する方法を紹介します。

前提条件

  • Rails 8.0
  • Ruby 3.2
  • Gmailアカウント(2段階認証が有効)

1. 必要なgemの追加

まず、Gemfileに必要なgemを追加します:

Gemfile
# 既存のgem設定...

group :development do
  # 既存のgem設定...
  
  # メール送信テスト用(オプション)
  gem 'letter_opener'
end

bundle installを実行してgemをインストールします:

bundle install

2. 環境変数の設定

Gmailの認証情報を環境変数として設定します。.envファイルを作成して以下の内容を追加してください:

.env
MAIL_ADDRESS=your-email@gmail.com
MAIL_PASSWORD=your-app-password

注意: MAIL_PASSWORDには、Gmailの通常のパスワードではなく、アプリパスワードを設定する必要があります。

Gmailアプリパスワードの取得方法

  1. Googleアカウントの設定画面にアクセス
  2. セキュリティ → 2段階認証プロセス → アプリパスワード
  3. 新しいアプリパスワードを生成
  4. 生成された16文字のパスワードをコピー

3. 開発環境の設定

config/environments/development.rbにメール送信の設定を追加します:

config/environments/development.rb
Rails.application.configure do
  # 既存の設定...

  # メール送信の設定
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  
  # SMTP設定(Gmail使用)
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: 'smtp.gmail.com',
    port: 587,
    domain: 'gmail.com',
    user_name: ENV['MAIL_ADDRESS'],
    password: ENV['MAIL_PASSWORD'],
    authentication: 'plain',
    enable_starttls_auto: true
  }
end

4. メーラークラスの作成

基本的なメーラークラスを作成します:

app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: 'noreply@example.com'
  layout 'mailer'
end
app/mailers/sample_mailer.rb
class SampleMailer < ApplicationMailer
  def welcome_email(user)
    @user = user
    @url = 'http://localhost:3000/login'
    
    mail(
      to: @user.email,
      subject: 'アプリケーションへようこそ!'
    )
  end
  
  def notification_email(user, message)
    @user = user
    @message = message
    
    mail(
      to: @user.email,
      subject: '新しい通知があります'
    )
  end
end

5. メールテンプレートの作成

対応するビューファイルを作成します:

app/views/sample_mailer/welcome_email.html.erb
<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>ようこそ、<%= @user.name %>さん!</h1>
    <p>
      アプリケーションへの登録が完了しました。<br>
      以下のリンクからログインしてください:
    </p>
    <p><%= link_to 'ログイン', @url %></p>
  </body>
</html>
app/views/sample_mailer/welcome_email.text.erb
ようこそ、<%= @user.name %>さん!

アプリケーションへの登録が完了しました。
以下のリンクからログインしてください:

<%= @url %>

6. メール送信のテスト

Railsコンソールでメール送信をテストできます:

# Railsコンソールを起動
rails console

# ダミーユーザーオブジェクトを作成
user = OpenStruct.new(name: 'テストユーザー', email: 'test@example.com')

# メール送信
SampleMailer.welcome_email(user).deliver_now

# または非同期送信(Active Jobが設定されている場合)
SampleMailer.welcome_email(user).deliver_later

7. 代替案:Letter Opener(開発環境専用)

実際にメールを送信せずに、ブラウザでメールの内容を確認したい場合は、letter_openerを使用できます:

config/environments/development.rb
Rails.application.configure do
  # 既存の設定...

  # Letter Openerを使用(メール送信の代わりにブラウザで表示)
  config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.perform_deliveries = true
end

この設定により、メール送信時にブラウザが自動で開き、メールの内容を確認できます。

8. トラブルシューティング

よくあるエラーと対処法

認証エラー

Net::SMTPAuthenticationError: 535 5.7.8 Username and Password not accepted
  • アプリパスワードが正しく設定されているか確認
  • 2段階認証が有効になっているか確認

接続エラー

Net::SMTPFatalError: 550 5.7.1 Relaying not allowed
  • Gmailの設定で「安全性の低いアプリのアクセス」を許可
  • またはアプリパスワードを使用

ポートエラー

Net::SMTPFatalError: 530 5.7.0 Must issue a STARTTLS command first
  • enable_starttls_auto: trueが設定されているか確認
  • ポート587を使用しているか確認

9. セキュリティのベストプラクティス

  • 認証情報は必ず環境変数で管理
  • .envファイルは.gitignoreに追加
  • 本番環境では異なるSMTP設定を使用
  • アプリパスワードは定期的に更新

まとめ

開発環境でメール送信機能を設定することで、ユーザー登録や通知機能などのテストが効率的に行えるようになります。GmailのSMTPサーバーを使用することで、無料でメール送信のテストが可能です。

本番環境では、SendGridやMailgunなどの専用サービスや、AWS SESなどのクラウドサービスを使用することをお勧めします。

参考リンク

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?