首页 > 解决方案 > 发送电子邮件时 Gmail API 不包含附件

问题描述

我想通过 Gmail Api 发送邮件。这是我的代码:

@client = Google::APIClient.new
@client.authorization.access_token = access_token
@service = @client.discovered_api('gmail')

mail = Mail.new
mail.subject = subject
mail.from= from_email
mail.to= to_email
mail.part content_type: 'multipart/alternative' do |part|
   part.html_part = Mail::Part.new(body: message_html, content_type: 'text/html; charset=UTF-8')
   part.text_part = Mail::Part.new(body: message_text)
end

open('https://example.com/image.png') do |file| 
   mail.attachments['image.png'] = { mime_type: 'image/png', content:  file.read  }
end
results = @client.execute(
            api_method: @service.users.messages.to_h['gmail.users.messages.send'],
            parameters: { userId: 'me' },
            body_object: {
              raw: Base64.urlsafe_encode64(mail.to_s)
            },
          )

当我使用上述代码发送邮件时,我只接收带有 message_htmt 的内容,没有附件。

请指导我发送带有附件的邮件。

标签: ruby-on-railsgoogle-client

解决方案


使用下面的代码 -

open('https://example.com/image.png') do |file| 
  mail.attachments['image.jpg'] = file.read 
end

有关更多信息,请查看此问题


推荐阅读