使用Gmail Smtp 发送email (rails2.0)

ActionMailer是一个简单的Rails组件,应用程序可以借助它来收发电子邮件。
Gmail--你必须有一个账号和密码,没有的话快去申请[url]http://mail.google.com/mail/signup[/url]

邮件配置:
在enviroment.rb文件中:

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,我也不知道 :x

下载成功之后,在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

然后在config文件夹create一个yml文件:mailer.yml

:address: smtp.gmail.com
:port: 587
:user_name: gmail­_account
:password: gmail_password
:authentication: :plain

最后就可以script/generate mailer MyMailer send

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"
}


去看看原文吧:[url]http://www.danielfischer.com/2008/01/09/how-to-use-gmail-as-your-mail-server-for-rails/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值