(ActionMailerとgmailを併用する場合)
前提知識
- 送信はSMTP(Simple Mail Transfer Protcol)を利用 - 25番ポート
- 受信はPOP - 100番ポート
- SMTPに関しては、25番でなく587番を利用して、送信時にSMTP-AUTHというユーザID/パスワードを要求するのが現在の主流らしい
送信版のコード
config/enviroments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings =
{
:user_name => ENV['MAILER_USER_ID'],
:password => ENV['MAILER_PASSWORD'],
:domain => "example.com",
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
config/enviroments/production.rb
config.action_mailer.default_url_options = { host: 'example.herokuapp.com' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings =
{
:user_name => ENV['MAILER_USER_ID'],
:password => ENV['MAILER_PASSWORD'],
:domain => "example.com",
:address => "smtp.gmail.com",
:port => 587,
:authentication => 'login',
:enable_starttls_auto => true
}
Mailer.rb
def send_email(mailer)
@mailer = mailer
mail(
from: @mailer.email,
to: ENV['MAILER_USER_ID'],
subject: 'Appの問い合わせ'
)
end
# mailメソッドで送信するメソッドにemailを渡してdeliverする
# email以外はmailメソッドがよしなに取得してくれる
Mailer.send_email(@mailer).deliver
受信版のコード
Mailer.rb
# Action Mailerに大本が存在
# Action Mailerによって生のEmailデータを解析->emailオブジェクトに変換されてデコード->Mailerインスタンス化->Mailer.receiveインスタンスメソッドに渡されるというプロセスを踏む
def receive(email)
page = Page.find_by_address(email.from.first) ||
Page.create(:address => email.from.first)
tmp = email.body
if tmp.multipart?
logger.debug "マルチパートだよ"
# エンコードが必要なケースもある?
# .kconv(Kconv::UTF8, Kconv::JIS) JIS から UTF8 に変換
tmp = email.parts[0].body.to_s
end
page.emails.create(
:subject => email.subject,
:body => tmp,
:header => email.header,
:messageid => email.message_id,
:receivedate => email.date
)
# 添付ファイルは必要に応じて保存
# if email.has_attachments?
# for attachment in email.attachments
# str = attachment.filename
# page.attachments.create({
# :file => attachment,
# :description => email.subject,
# :filename => str
# })
# end
# end
end
# メールを受信するトリガーメソッド
# RailsGuideでは、rails runner 'UserMailer.receive(STDIN.read)'を推奨
def receive_trigger
@address = 'pop.gmail.com'
@port = 995
@id = ENV['MAILER_USER_ID']
@pass = ENV['MAILER_PASSWORD']
# gmailはsslじゃないと接続できない模様
Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE)
pop = Net::POP3.new(@address, @port)
pop.start(@id, @pass)
unless pop.mails.empty?
pop.each_mail do |m|
InquiryMailer.receive(m.pop) # 受信したメールを、「処理」する(DBへ登録)
m.delete # 受信したメールをサーバから削除
end
end
pop.finish
end
mailer_controller.rb
# triggerもdeliverしてあげる
Mailer.receive_trigger.deliver
環境変数の設定
ローカル環境
dotenvを利用する
参考記事heroku
$ heroku config:add RAILS_ACHIEVE_MAILER_USER_ID='hoge@gmail.com'
Gmail設定
アカウント->2段階認証を有効にする->アプリパスワード->アプリの登録->発行されたアプリパスワードを上記環境変数に設定