我今天有多处瘀伤,试图一次学习两件事...... Postmark 和 Rails HTTP 请求的 API。
目标:使用 Heroku 的 Postmark 插件发送生产电子邮件。
我正在尝试将这篇关于 HTTP 请求的文章... http://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html ...与 Postmark 的 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
我很感激任何指导!