Creating draft via Google Gmail API

扶醉桌前 提交于 2019-12-17 14:57:34

问题


I am trying to create a draft message for a logged in user but keep getting the error Missing draft message when I run the below

require 'google/api_client'
client = Google::APIClient.new
client.authorization.client_id = ENV['GOOGLE_CLIENT_ID']
client.authorization.client_secret = ENV['GOOGLE_CLIENT_SECRET']
client.authorization.grant_type = 'refresh_token'
client.authorization.refresh_token = User.last.refresh_token
token = client.authorization.fetch_access_token!
gmail = client.discovered_api('gmail', 'v1')
params = { 'userId' => 'me', 'draft' => { 'message' => {'raw' => 'test email' } } }
# { 'userId' => 'me', 'message' => {'raw' => 'test email' } }
result = client.execute(api_method: gmail.users.drafts.create, parameters: params)

In addition I tried the commented out combination for params and still no luck. Any ideas?


回答1:


I had the same issue when I was trying to do this for the first time as well. The solution that I found was to not include the message information as part of the parameters, but rather pass that on in the :body_object as shown below.

@result = client.execute(
  :api_method => gmail.users.drafts.create,
  :parameters => {
    'userId' => "me"      
  },
  :body_object => {
    'message' => {
      'raw' =>  Base64.urlsafe_encode64('Test Email Message')
    }
  }
)



回答2:


raw in message is the full SMTP message.

  • Either you set the content in body_object
  • Or you set the full SMTP message including headers in message

eg:

params = { 'userId' => 'me', 'draft' => { 'message' => {'raw' => 'From: foo@example.com\nSubject:Ignore\n\ntest email' } } }


来源:https://stackoverflow.com/questions/25493213/creating-draft-via-google-gmail-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!