【发布时间】:2015-04-23 12:29:28
【问题描述】:
我今天有多处瘀伤,试图同时学习两件事...... Postmark 和 Rails HTTP 请求的 API。
目标:使用 Heroku 的 Postmark 插件发送生产电子邮件。
我正在尝试结合这篇关于 HTTP 请求的文章... http://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html ...使用此 API 参考邮戳... http://developer.postmarkapp.com/developer-send-api.html
不幸的是,来自 Postmark 的示例是在 curl 中完成的,我没有成功地将它们转换为 HTTP 请求。我怀疑问题集中在标题上——除了正文之外的传输部分。
下面代码中的救援子句捕获了错误“对等方重置连接”。在这一点上,我不知道我是否接近提供邮戳身份验证的标头的正确格式。
我有正确的服务器令牌(在配置条目中)并且发件人电子邮件已获得所需的邮戳签名。
def send_production_email(email_address, subject, email_body)
# Use API to interact with Heroku add-on Postmark
# http://developer.postmarkapp.com/developer-send-api.html
uri = URI('https://api.postmarkapp.com/email')
# Form the request
req = Net::HTTP::Post.new(uri)
# Set request headers -- SUSPECT THIS IS WRONG
req['Accept'] = 'application/json'
req['Content-Type'] = 'application/json'
req['X-Postmark-Server-Token'] = Rails.application.config.postmark_token
rbody ={
'From' => 'Support <michael@mydomain.com>',
'To' => email_address,
'Subject' => subject,
'HtmlBody' => wrap_html(email_body),
'TextBody' => email_body
}.to_json
req.body = rbody
# Send the request, waiting for the response
begin
response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req) }
rescue Exception => e
logthis("http request error: #{e.message}")
return
end
# ...parsing section omitted since I do not get that far...
end
第二次尝试以这种方式格式化,但导致相同的对等重置错误:
rbody ={
'From' => 'Support <michael@disambiguator.com>', # TODO: replace email when domain is live
'To' => email_address,
'Subject' => subject,
'HtmlBody' => wrap_html(email_body),
'TextBody' => email_body
}.to_json
uri = URI('https://api.postmarkapp.com/email')
http = Net::HTTP.new(uri.host, uri.port)
# http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Postmark-Server-Token' => Rails.application.config.postmark_token})
request.body = rbody
# Send the request, waiting for the response
begin
response = http.request(request)
rescue Exception => e
logthis("http request error: #{e.message}")
return
end
感谢您的指导!
【问题讨论】:
标签: ruby-on-rails http heroku postmark