Rails 使用SendCloud发送邮件
(1)首先,SendCloud(https://sendcloud.sohu.com/)
SendCloud平台发送设置比较简单,不需要有自己的域名,可以不进行DNS配置,每天可以免费发送邮件10到50封,进入官网注册之后,看一下SendCloud平台提供的开发文档代码示例,打开链接http://www.sendcloud.net/doc/email_v2/downloads/ruby/ruby_common.rb,会把示例代码ruby_common.rb下载下来,如图:

require 'rest-client'
加载rest-client插件,这个gem我们还没有安装,下面我们会安装
:apiUser、:apiKey、:from
这三个参数我们需要在SendCloud平台中找到并替换文件中的代码。
:to、:subject、:html
分别代表收件人、邮件主题、邮件内容,我们会将这三个参数设为变量。
在GemfIle文件中添加:
(2)添加rest-client
gem "rest-client"
然后运行:
bundle install
(3)获取参数:apiUser、:apiKey、:from
打开SendCloud平台(https://sendcloud.sohu.com/email/)
记住这三个值,具体生成方法不细说,
(4)创建lib/send_mail.rb,如下代码复制进去
require 'rubygems'
require 'rest-client'
class SendMail
#定义一个类方法,之后可以通过SendMail.send_mail(to,subject,html)来调用这个方法
def self.send_mail(to,subject,html)
response = RestClient.post "http://api.sendcloud.net/apiv2/mail/send",
#使用api_user和api_key进行验证
:apiUser => '...',
#点击左侧菜单API User,点击生成新的API_KEY
:apiKey => '...',
#发信人,用正确邮件地址替代
:from => "sendcloud@cxSVVBe4BAIvKZwWyHjm4HuvmQld0FRO.sendcloud.org",
:fromName => "SendCloud",
#收件人地址,用正确邮件地址替代,多个地址用';'分隔
:to => "#{to}",
:subject => "#{subject}",
:html => "#{html}"
return response
end
end
将apiUser、apiKey和from的值换成自己的就可以了,再到发送邮件的ctroller文件中调用就行了,可能要在第一行引入
require 'send_mail'
class UserController <ApplicationController
....
....
def send_mail
subject = "#{current_user.name} 您好,欢迎使用啥啥啥"
html = "http://ip地址 您好,点击链接激活邮箱"
response = SendMail.send_mail(current_user.email,subject,html)
pp "======#{response}"
end
end
其实这样就可以了,如果你的apiUser、apiKey正确的话。
SendCloud开发文档:
http://www.sendcloud.net/doc/email_v2/

浙公网安备 33010602011771号