无法使用 Gmail 发送 Gmail 邮件 API

Unable to send Gmail Message with Gmail API

使用 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)

即使我在没有使用 base64 编码的情况下通过 email_raw,也会失败。我正在提供有效的电子邮件,但它因错误而失败

Google::Apis::ClientError (invalidArgument: Recipient address required)

我已经检查过 and I also found ,但它使用了 Mail class,我无法在 Gmail API Ruby 客户端库中找到它。目前,email_raw 包含 \n 个字符,但我已经在没有它的情况下对其进行了测试,但它不起作用。
另外,我也想在消息中发送附件

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

参见documentation

raw string (bytes format)

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.

A base64-encoded string.

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

那么,在使用Ruby时,可以使用方法:

Base64.urlsafe_encode64(message).

更新

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

邮件正文应具有以下结构:

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。只需在您的项目中包含 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)