问题描述
我已经使用我的 Ruby on Rails 项目配置了 Google Api。另外,我为传入的电子邮件设置了 webhook。 我已成功实现通过 Google 登录并获取用户的收件箱消息。
现在,我正在实施消息回复,但收到“BadRequest”作为响应。
我的代码。
uri = URI.parse("https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=#{access_token}")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
request.body = JSON.dump({
"References" => "\u003cCAAY2B8p2CjEjDKz+sXVBQBrda5i5Lz=Dd4fVC21kfx8fhLLCdg@mail.gmail.com\u003e","In-Reply-To" => "\u003cCAAY2B8p2CjEjDKz+sXVBQBrda5i5Lz=Dd4fVC21kfx8fhLLCdg@mail.gmail.com\u003e","Subject" => "Re: Test02","From" => "[email protected]","To" => "[email protected]","threadId"=> "1764cc4c5efa6855",# "body" => "This is where the response text will go"
})
req_options = {
use_ssl: uri.scheme == "https",}
response = Net::HTTP.start(uri.hostname,uri.port,req_options) do |http|
http.request(request)
end
API 调用响应。
response => #<Net::HTTPBadRequest 400 Bad Request readbody=true>
我需要使用 Google Api 发送回复。
提前致谢。
解决方法
为了使用 Google API 回复消息,我使用了这种方法。
client_secrets = Google::APIClient::ClientSecrets.load("#{Rails.root}/config/client_secrets.json")
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://mail.google.com/ https://www.googleapis.com/auth/gmail.modify https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/pubsub',:redirect_uri => 'http://localhost:3000/google_code',:additional_parameters => {
"access_type" => "offline",# offline access
"include_granted_scopes" => "true" # incremental auth
}
)
auth_client.code = auth_code
gmail = Google::Apis::GmailV1::GmailService.new
gmail.authorization = auth_client
message = Mail.new
message.date = Time.now
message.subject = "Re: Test02"
message.from = "[email protected]"
message.to = "[email protected]"
message.message_id = "\u003cCAFVVPDvD-zK6Akj8djj+uam35ZxFTf2EW4AefW1Ri7OV7AxFVA@mail.gmail.com\u003e"
message.part content_type: 'multipart/alternative' do |part|
part.html_part = Mail::Part.new(body: "Using service Account.",content_type: 'text/html; charset=UTF-8')
end
msg = message.encoded
message_object = Google::Apis::GmailV1::Message.new(raw:message.to_s,thread_id: "1764cc4c5efa6855",content_type: 'message/rfc822')
gmail.send_user_message('me',message_object)