在GMAIL上使用IMAP获取附件的大小

时间:2012-03-13 22:45:38

标签: ruby ruby-on-rails-3 gmail gmail-imap

我想检索每个邮件附件的大小,而不必下载文件来获取它。我正在使用Gmail gem

编辑:我正在寻找一种方法,只需通过阅读标题或类似内容来获取大小,而无需检索整个附件,这是一个非常漫长的过程。

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

1 个答案:

答案 0 :(得分:1)

这就是我所做的。我使用StringIO将附件转换为内存中的文件,然后使用大小:

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