【发布时间】:2018-01-29 09:02:08
【问题描述】:
我正在尝试使用 gmail API 发送电子邮件。如下所示,我的 Ruby 代码在没有附件的情况下运行良好:
client = google_client user_id
token = Token.find_by_user_id(user_id)
access_token = token.access_token
gmail = Google::Apis::GmailV1::GmailService.new
gmail.authorization = client
message = Mail.new
message.date = Time.now
message.subject = 'Supertram p'
message.body = "<p>Hi Alex, how's life?</p>"
message.content_type = 'text/html'
message.from = self.email
message.to = 'email_name@gmail.com'
msg = message.encoded
message_object = Google::Apis::GmailV1::Message.new(raw:message.to_s)
gmail.send_user_message('me', message_object)
我能够成功发送 html 格式的电子邮件。 我的问题是如何将文件附加到此邮件?
client = google_client user_id
token = Token.find_by_user_id(user_id)
access_token = token.access_token
gmail = Google::Apis::GmailV1::GmailService.new
gmail.authorization = client
message = Mail.new
message.date = Time.now
message.subject = 'Supertramp'
message.body = "<p>Hi Alex, how's life?</p>"
# message.content_type = 'text/html'
message.from = self.email
message.to = 'myemail@gmail.com'
message.add_file("/Users/myname/Downloads/image.png")
msg = message.encoded
message_object = Google::Apis::GmailV1::Message.new(raw:message.to_s)
gmail.send_user_message('me', message_object)
但这是我收到的消息:
-- 内容类型:文本/纯文本; charset=UTF-8 Content-Transfer-Encoding: 7bit Hi Alex,你好吗?
-- 内容类型: image/png; filename=image.png 内容传输编码:base64 内容处置:附件; 文件名=image.png 内容 ID: iVBORw0KGgoAAAANSUhEUgAAAfAAAABMCAYAAACS0+VcAAAX9UlEQVR4Ae2d XWxj1bXH/6lKK+D1VE1oKEa6CPNwpQh4SFBapYOrIoGUuRnN6IRR25HuC1C/ AC8JDMiFGTlP8 [...] == ----
我只收到一个编码字符串,但没有收到附件。 我的问题是如何通过 Gmail API 发送带有附件的电子邮件?
【问题讨论】:
-
你想发送多部分电子邮件,所以不要将内容类型指定为'text/html' ...(去研究你需要使用什么而是。)
-
我尝试过使用“multipart/alternative”,但我的 html 部分丢失了
-
您从哪里获得 Mail 类?我在 google-api-ruby-client 库中找不到它。
标签: ruby-on-rails google-api gmail-api google-api-ruby-client