使用 google-api-ruby-client '0.9.pre3' 发送 gmail 邮件

Send gmail messages with google-api-ruby-client '0.9.pre3'

在 rails 4 应用程序中使用较新的 google-api-ruby-客户端发送 gmail。

require 'google/apis/gmail_v1'

Gmail = Google::Apis::GmailV1

class MailService

  def initialize(params)
    @params = params
  end

  def call
    message = Gmail::Message.new
    service = Gmail::GmailService.new
    message.raw = (redacted)
    service.request_options.authorization = current_user.token.fresh_token
    result = service.send_user_message(current_user.email, message)
  end

end

这是调用 API 的结果:

Sending HTTP post https://www.googleapis.com/gmail/v1/users/me/messages/send?
200
#<Hurley::Response POST https://www.googleapis.com/gmail/v1/users/me/messages/send == 200 (63 bytes) 858ms>
Success - #<Google::Apis::GmailV1::Message:0x007fc9cf9b52dd
 @id="15096369c05cdb1d",
 @thread_id="15096369c05cdb1d">

原始消息从 API 资源管理器发送时没有问题,但是当从我的应用程序执行时,我的收件箱中收到退回电子邮件。在上面的示例中,经过编辑的示例是一个有效的 RFC 2822 格式的 base-64 url 安全字符串,fresh_token 表示当前用户的 oauth2 访问令牌。

查看退回的邮件

Bounce <nobody@gmail.com>
2:43 PM (19 minutes ago)
to me

An error occurred. Your message was not sent.

有人有什么想法吗?似乎我的(发件人)电子邮件可能在原始邮件中被提取,而不是收件人......虽然我认为 API 可能会根据我的 oauth 访问令牌转发退回邮件。

非常感谢任何帮助。谢谢!

编辑:解决方案是在没有 base64 编码的情况下将 RFC 2822 字符串作为原始 属性 传递。

Steve Bazyl 似乎是正确的。从 (0.9.13) 开始,关于 send_user_message 的文档是错误的。对于 raw,它说: "The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied. Corresponds to the JSON property raw." 据我所知,这只是 不正确

我在从 google-api-client 0.8 更新到 0.9 并删除 base64 编码时遇到了这个问题。 IE。调用 0.8:

response = @service.execute(
  api_method: api.users.messages.to_h['gmail.users.messages.send'],
  body_object: {
    raw: Base64.urlsafe_encode64(mail.to_s)
  },
  parameters: {
    userId: 'me',
  }
)

成为

message = { raw: mail.to_s }
res = @service.send_user_message('me', message, {})

在 0.9 中。

报告为https://github.com/google/google-api-ruby-client/issues/474