bav ko ten
bav ko ten

Reputation: 532

Gmail API does not include attachment when sending an email

I want to send mail through Gmail Api. This my code:

@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)
            },
          )

when i send mail with above code, i only recipient content with message_htmt without attachments.

Please guide me send mail with attachments.

Upvotes: 2

Views: 296

Answers (1)

fidato
fidato

Reputation: 719

Use below code -

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

For more info, check out this question.

Upvotes: 1

Related Questions