1

我的目标是在这个gmail gem自述文件示例中找到调用 save_attachments_to 的地方:

folder = "/where/ever"
gmail.mailbox("Faxes").emails do |email|
  if !email.message.attachments.empty?
    email.message.save_attachments_to(folder)
  end
end

我在循环中运行“puts email.message.attachments.methods”和“email.message.attachments.class”:

Mail::AttachmentsList
guess_encoding
set_mime_type
inspect

然后我运行了一个“puts email.message.methods”和一个“puts email.message.class”来衡量。示例方法调用不在列表中。

所以我潜入https://github.com/nu7hatch/gmail/blob/master/lib/gmail/message.rb

那里也没有定义任何方法,但我注意到定义了 mime/message,所以我去那里查看它的方法:http ://rubydoc.info/gems/mime/0.1/MIME/Message

这里也没有 save_attachments_to 方法。

这种方法到底好在哪里?gmail gem 没有定义附件方法,所以整个东西必须从某个地方继承。在哪里?继承它的调用在哪里?

4

2 回答 2

2

你找不到它的原因是因为它不存在。我不确定为什么。我下载了 gem 并在其中玩了一段时间irb

1.9.3-p194 :066 > x.message.attachments
 => [#<Mail::Part:70234804200840, Multipart: false, Headers: <Content-Type: application/vnd.ms-excel; name="MVBINGO.xls">, <Content-Transfer-Encoding: base64>, <Content-Disposition: attachment; filename="MVBINGO.xls">, <Content-Description: MVBINGO.xls>>] 
1.9.3-p194 :063 > x.message.save_attachments_to(folder)
NoMethodError: undefined method `save_attachments_to' for #<Mail::Message:0x007fc1a3875818>
    from /Users/Qsario/.rvm/gems/ruby-1.9.3-p194/gems/mail-2.4.4/lib/mail/message.rb:1289:in `method_missing'
    from (irb):63
    from /Users/Qsario/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

不是很有帮助。通常,您可以执行类似的操作

puts my_obj.method(:some_method_name).source_location

但是当有问题的方法不存在时,那对你没有多大帮助。编辑:现在我看,这个确切的错误已经在他们的问题跟踪器上。一些人发布了代码来实现不存在的功能,例如ab的这段代码:

folder = Dir.pwd # for example
email.message.attachments.each do |f|
  File.write(File.join(folder, f.filename), f.body.decoded)
end
于 2012-08-05T08:46:24.107 回答
2

感谢 Qsario 的健全性检查。:-)

这是适用于 Ruby 1.9.3 (1.9.3-p194) 的代码:

gmail = Gmail.connect('username@gmail.com', 'pass') 
gmail.inbox.emails.each do |email|
  email.message.attachments.each do |f|
    File.write(File.join(local_path, f.filename), f.body.decoded)
  end
end

这是适用于 1.9.2 (1.9.2-p320) 和 1.9.3 (1.9.3-p194) 的代码:

gmail = Gmail.connect('username@gmail.com', 'pass') 
gmail.inbox.emails.each do |email|
  email.message.attachments.each do |file|
    File.open(File.join(local_path, "name-of-file.doc or use file.filename"), "w+b", 0644 ) { |f| f.write file.body.decoded }
  end
end
于 2012-08-05T16:10:07.427 回答