【问题标题】:Ruby - IMAP iterate multiple folders / select multiple foldersRuby - IMAP 迭代多个文件夹/选择多个文件夹
【发布时间】:2021-11-01 17:43:22
【问题描述】:

这是我的 IMAP 代码:

imap = Net::IMAP.new('outlook.office365.com', 993, true)
imap.login('USERNAME', 'PASSWORD')
imap.examine("FOLDER1")
imap.search(["SINCE", "17-Dec-2020"]).each do |message_id|
  envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  subject = Mail::Encodings.unquote_and_convert_to( envelope.subject, 'utf-8' )
  next unless subject.include?("SOME TXT")
  body = imap.fetch(message_id, "BODY[]")[0].attr["BODY[]"]
  mail = Mail.new(body)
  mail.attachments.each do |a|
    next unless File.extname(a.filename) == ".pdf"
    File.open("/path/to/file/pdfscript/#{a.filename}", 'wb') do |file|
      file.write(a.body.decoded)
    end
  end
end

现在我只为“FOLDER1”设置了它,但我有很多文件夹需要从中获取文件。可以添加多个文件夹吗?类似的东西

imap.examine("FOLDER1", "FOLDER2", "FOLDER3", "FOLDER4")

【问题讨论】:

  • 不,这是不可能的。您必须在登录后循环所有内容,否则使用多个 TCP 连接。

标签: ruby imap


【解决方案1】:

我通过创建一个数组解决了我的问题

array_of_folders = ["Folder1","Folder2","Folder3","Folder4"]

并发了.each

array_of_folders.each do |folders|
imap.examine(folders) # takes each folder
# Rest of the code
end

【讨论】:

  • 提示:对于单个单词的数组,请使用%w[ Folder1 Folder2 ... ],这样可以避免很多语法噪音。
  • Ruby 也倾向于使用 array_of_folders 命名约定,这与 Python 等不同。
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2013-10-10
  • 2018-08-14
相关资源
最近更新 更多