Question

I would like to retrieve the size of each mail's attachment without having to download the file to get it. I'm using the Gmail gem.

EDIT: I'm looking for a way, to get the size only by reading the headers or similar without having to retrieve the whole attachments which is a very long process.

gmail = Gmail.connect(:xoauth, self.email, 
  :token           => self.token,
  :secret          => self.secret,
  :consumer_key    => 'SECRET',
  :consumer_secret => 'SECRET'
)
mails = gmail.mailbox("[Gmail]/All Mail").emails
mails.each do |mail|
  next if mail.message.attachments.blank?
  # How to get the message's size if possible ?
  mail.message.attachments.each do |attachment|
    # How to get the attachment's size ?
  end
end
Was it helpful?

Solution

Here is what I did. I used StringIO to convert the attachment to a file in memory and then took the size:

require 'rubygems'
require 'gmail'
require 'ap' #awesome_print gem

gmail = Gmail.connect("name","password") #simple authorization
mails = gmail.mailbox("[Gmail]/All Mail").emails
mails.each do |mail|
  next if mail.message.attachments.blank?
  mail.message.attachments.each do |attachment|
    file = StringIO.new(attachment.to_s)
    ap file.size
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top