邮件配置:
在enviroment.rb文件中:
- ActionMailer::Base.server_settings={
- :address=>"smtp.gmail.com",
- :port=>587,
- :authentication=>:plain,
- :user_name=>"gmail_account",
- :password=>"gmail_password"
- }
ActionMailer::Base.server_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:user_name=> "gmail_account",
:password => "gmail_password"
}
如果按照上面的配置,一般邮件发送会不成功,因为gmail需要ssl方式来登录,ruby的lib中Net:SMTP TLS不支持,所以我们必须去下载一个plugin :
cd /my_rails_app/vendor/plugins
svn export https://openrain.com/opensource/public/rails/plugins/action_mailer_tls action_mailer_tls
为什么不用script/plugin install,我也不知道
下载成功之后,在config/initializers文件夹create一个ruby文件:smptp_gmail.rb
- require"smtp_tls"
- mailer_config=File.open("#{RAILS_ROOT}/config/mailer.yml")
- mailer_options=YAML.load(mailer_config)
- ActionMailer::Base.delivery_method=:smtp
- ActionMailer::Base.default_charset="utf-8"
- ActionMailer::Base.smtp_settings=mailer_options
require "smtp_tls" #刚才下载的文件
mailer_config = File.open("#{RAILS_ROOT}/config/mailer.yml")
mailer_options = YAML.load(mailer_config)
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default_charset = "utf-8"
ActionMailer::Base.smtp_settings = mailer_options
然后在config文件夹create一个yml文件:mailer.yml
- :address:smtp.gmail.com
- :port:587
- :user_name:gmail_account
- :password:gmail_password
- :authentication::plain
:address: smtp.gmail.com
:port: 587
:user_name: gmail_account
:password: gmail_password
:authentication: :plain
最后就可以script/generate mailer MyMailer send
- classMyMailer<ActionMailer::Base
- defsend
- recipients='receiveremailaddress'
- from='youremailaddress'
- subject='iloverubyonrails'
- body[:account]='selina'
- end
- end
class MyMailer < ActionMailer::Base
def send
recipients = 'receiver email address' #接收者email地址
from = 'your email address' #发送者email地址
subject = 'i love ruby on rails'
body[:account] = 'selina'
end
end
开始发送: script/console
MyMailer.create_send #建一个email对象
MyMailer.deliver_send #发送email
最最最后:
其实把email stmp的配置文件写成一个yml文件的好处在于,如果你要改变stmp服务器的配置,直接再写一个yml文件就可以,比如A.yml , B.yml , C.yml ......
然后再File.open("#{RAILS_ROOT}/config/X.yml")
或者你觉得麻烦,也可以直接在enviroment.rb文件中:
- require'smtp_tls'
- ActionMailer::Base.delivery_method=:smtp
- ActionMailer::Base.default_charset="utf-8"
- ActionMailer::Base.server_settings={
- :address=>"smtp.gmail.com",
- :port=>587,
- :authentication=>:plain,
- :user_name=>"my_gmail_account",
- :password=>"my_gmail_password"
- }