使用Gmail服务发送电子邮件,但我遇到了需要传递给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也会失败。我提供了有效的电子邮件,但失败时出错了
谷歌::Apis::ClientError (invalidArgument:所需收件人地址)
我已经检查了用ruby gmail api v0.9发送电子邮件,也找到了这,但是它使用的是Mail类,我无法在Gmail客户端库中找到这个类。目前,email_raw包含\n字符,但是我已经测试过它,没有它,它不能工作。
此外,我还想在一条消息中发送附件。
发布于 2020-10-14 06:54:09
我们可以轻松地将形成标准化和格式化电子邮件的工作卸到这个创业板上。只需将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)发布于 2020-10-13 13:38:38
请注意,Gmail需要base64url编码,而不是base64编码。
请参阅文档
原始字符串(字节格式) RFC 2822格式化和base64url编码字符串中的整个电子邮件。在提供messages.get参数时,在format=RAW和drafts.get响应中返回。一个基本64编码的字符串。
我建议您首先使用试试这个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)https://stackoverflow.com/questions/64335721
复制相似问题