jhk753 / gmail-ruby-api

Ruby interface for Gmail API
Other
26 stars 20 forks source link

Can i get message attachments ? #33

Closed khanrazee closed 6 years ago

khanrazee commented 6 years ago

Hi Is there any way to get message attachment currently i am doing something like Gmail::Message.get (id) to get message and it works for me.

Carpela commented 6 years ago

Yes, you can retrieve the attachment.

This should allow you to get the attachment ids.

 email = Gmail.get id
    parts = email.dig("payload","parts")
    if parts.present?
      parts = parts.map{|p| p.dig("parts").present? ? p.dig("parts") : p }.flatten || []
      attachments = parts.select { |part| part['filename'].present? }
    else
      parts = []
    end

The attachment id is available under

attachment.body.attachmentId

This is an example controller which, when passed the gmail_id and attachment_id as parameters will enable you to download the attachment.

def attachment
    attachment = Gmail.client.get_user_message_attachment("me", params[:gmail_id], 
    params[:attachment_id])
    data = attachment.data
    send_data(data, filename: params.fetch(:filename, 'attachment'))
end