Ran*_*ger 5 ruby google-api-ruby-client gmail-api
在 rails 4 应用程序中使用较新的 google-api-ruby-client 发送 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
Run Code Online (Sandbox Code Playgroud)
这是调用 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">
Run Code Online (Sandbox Code Playgroud)
原始消息从 API Explorer 发送没有问题,但是当从我的应用程序执行时,我的收件箱中收到一封退回电子邮件。在上面的示例中,编辑后的示例是一个有效的 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.
Run Code Online (Sandbox Code Playgroud)
有人有什么想法吗?看起来我的(发件人)电子邮件可能是在原始消息中被接收的,而不是收件人......虽然我认为 API 可能会根据我的 oauth 访问令牌转发退回邮件。
我非常感谢任何帮助。谢谢!
编辑:解决方案是将 RFC 2822 字符串作为原始属性传递,而无需 base64 编码。
史蒂夫·巴兹尔似乎是正确的。截至 (0.9.13),有关 send_user_message 的文档是错误的。对于 raw,它表示:“RFC 2822 格式和 base64url 编码字符串中的整个电子邮件消息。当提供 format=RAW 参数时,在 messages.get 和 Drafts.get 响应中返回。对应于 JSON 属性 raw。” 据我所知,这是完全错误的。
我在从 google-api-client 0.8 更新到 0.9 并删除 base64 编码时遇到了这个问题,解决了这个问题。即调用 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',
}
)
Run Code Online (Sandbox Code Playgroud)
成为
message = { raw: mail.to_s }
res = @service.send_user_message('me', message, {})
Run Code Online (Sandbox Code Playgroud)
在 0.9 中。
报告为https://github.com/google/google-api-ruby-client/issues/474。
| 归档时间: |
|
| 查看次数: |
1048 次 |
| 最近记录: |