无法使用Gmail API发送Gmail邮件

问题描述

使用Gmail Service发送电子邮件,但是我遇到了需要传递给Google::Apis::GmailV1::Message的电子邮件格式的问题,我正在以以下格式将原始参数传递给它

email_raw = "From: <#{@google_account}>
To: <#{send_to}>
Subject: This is the email subject

The email body text goes here"

# raw is: The entire email message in an RFC 2822 formatted and base64url encoded string.

message_to_send = Google::Apis::GmailV1::Message.new(raw: Base64.encode64(email_raw))
response = @service.send_user_message("me",message_to_send)

即使我通过email_raw而不使用base64编码,此操作也失败。我正在提供有效的电子邮件,但失败并出现错误

Google :: Apis :: ClientError(invalidArgument:需要收件人地址)

我已经检查了Sending an email with ruby gmail api v0.9,还发现了this,但是它使用的Mail类在Gmail API Ruby客户端库中找不到。当前,email_raw包含\n个字符,但是我已经测试了没有它的字符,它不起作用。
而且,我也想在邮件中发送附件。

解决方法

请注意,Gmail需要使用base64url编码,而不是base64编码

请参见documentation

原始字符串(字节格式)

以RFC 2822格式和base64url编码的字符串的整个电子邮件。当提供format = RAW参数时,返回messages.get和drafts.get响应。

base64编码的字符串。

我建议您首先使用Try this API进行测试-您可以使用在线base64url编码器对邮件进行编码。

然后,在使用Ruby时,可以使用以下方法:

Base64.urlsafe_encode64(message)

更新

问题似乎出在您的原始邮件正文上。

邮件正文应具有followind结构:

To: masroorh7@gmail.com Content-Type: multipart/alternative; boundary="000000000000f1f8eb05b18e8970"  --000000000000f1f8eb05b18e8970 Content-Type: text/plain; charset="UTF-8"  This is a test email  --000000000000f1f8eb05b18e8970 Content-Type: text/html; charset="UTF-8"  <div dir="ltr">This is a test email</div>  --000000000000f1f8eb05b18e8970--

base64url编码,如下所示:

encodedMessage = "VG86IG1hc3Jvb3JoN0BnbWFpbC5jb20NCkNvbnRlbnQtVHlwZTogbXVsdGlwYXJ0L2FsdGVybmF0aXZlOyBib3VuZGFyeT0iMDAwMDAwMDAwMDAwZjFmOGViMDViMThlODk3MCINCg0KLS0wMDAwMDAwMDAwMDBmMWY4ZWIwNWIxOGU4OTcwDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9IlVURi04Ig0KDQpUaGlzIGlzIGEgdGVzdCBlbWFpbA0KDQotLTAwMDAwMDAwMDAwMGYxZjhlYjA1YjE4ZTg5NzANCkNvbnRlbnQtVHlwZTogdGV4dC9odG1sOyBjaGFyc2V0PSJVVEYtOCINCg0KPGRpdiBkaXI9Imx0ciI-VGhpcyBpcyBhIHRlc3QgZW1haWw8L2Rpdj4NCg0KLS0wMDAwMDAwMDAwMDBmMWY4ZWIwNWIxOGU4OTcwLS0"

因此,您的邮件正文应为:

Google::Apis::GmailV1::Message.new(raw:encodedMessage)
,

我们可以轻松地为此gem分担制作标准化和格式化电子邮件的工作。只需将宝石包含在您的项目中,然后执行

mail = Mail.new
mail.subject = "This is the subject"
mail.to = "someperson@gmail.com"
# to add your html and plain text content,do this
mail.part content_type: 'multipart/alternative' do |part|
  part.html_part = Mail::Part.new(body: email_body,content_type: 'text/html')
  part.text_part = Mail::Part.new(body: email_body)
end
# to add an attachment,do this
mail.add_file(params["file"].tempfile.path)

# when you do mail.to_s it forms a raw email text string which you can supply to the raw argument of Message object
message_to_send = Google::Apis::GmailV1::Message.new(raw: mail.to_s)
# @service is an instance of Google::Apis::GmailV1::GmailService
response = @service.send_user_message("me",message_to_send)