ActionMailer を使ってみた
今まで、ActionMailerを使った事が無かったので、使ってみました・・・・というのは嘘で・・・・
本当は、Macでメールの同報配信するソフトウェアを探していたのですが、適当なものが見つからなくて作る事にしました。
Railsには、ActionMailerというメール送受信を行うモジュールがあるので、使ってみました。
まず、script/generate mailer でメール送信部分のひな型を生成します。
% script/generate mailer Business thanks exists app/models/ create app/views/business exists test/unit/ create test/fixtures/business create app/models/business.rb create test/unit/business_test.rb create app/views/business/thanks.erb create test/fixtures/business/thanks
Business というメールModelとthanksメールを送るメソッドとテンプレートを生成しています。
Business Model には thanksメソッドがあるので、そこをに必要なコードを追加します。
class Business < ActionMailer::Base def thanks(sent_at = Time.now) subject 'Business#thanks' recipients '' from '' sent_on sent_at body :greeting => 'Hi,' end end ↓ 変更 class Business < ActionMailer::Base def thanks(title, customer, sent_at = Time.now) subject "#{title}に参加ありがとうございます" recipients customer.email from 'yy@ey-office.com' sent_on sent_at body :name => customer.name, :company => customer.company, :title => title end end
テンプレート app/views/business/thanks.erb を作成
<%= @company %> <%= @name %>様、 お世話になります。 先日は、<%= @title%>にご参加ありがとうございます。 -- ♪ 吉田 裕美 (Yuumi Yoshida)
メインを作成。ActiveRecord(Rails)を使ったコンソールアプリの作り方に書いたコンソールアプリにMail送信を追加
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/environment' c = Customer.find(1) Business.deliver_thanks('Gaucheセミナー', c)
config/enviroment.rb のメール送信方法やSMTPの設定を書く
Rails::Initializer.run do |config| .... config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => 'XXXXX.com', # <= 自分のSMTPサーバー :port => 25, :domain => 'XXXXX.com', # <= 自分のメールドメイン } end
送信してみる ・・・・ 文字化けしてました orz ・・・ いろろと調べてみる ・・・・
ActionMailerは日本語のメール送信は出来ないようです。 しかし、JpMailerプラグインというのを見つけたのでインストールしてみました。
script/plugin install http://taslam-plugins.googlecode.com/svn/trunk/jp_mailer/
そして、 class Business < ActionMailer::Base を class Business < JpMailer::Base に変更。
無事に、日本語のメールが送信できました ^^)/
id:taslamさんありがとうございます!