Ruby IMAP 库:如何显示文件夹中的所有邮件?
Ruby IMAP library: How can I show all messages in a folder?
我需要一个脚本来获取我所有文件夹中的所有电子邮件,并将它们连同附件一起进行本地备份。here but it doesn't bring me further with listing all emails belongig to a folder. Also reading the RFC 不会让我更进一步。
我发的时候
imap.list("", "*")
和
imap.examine("SomeFolder")
如何使用它遍历 SomeFolder
的所有电子邮件?
我将如何进一步发出查询以获取消息和相关附件?
要获取邮箱中所有电子邮件的 UID,请使用 imap.uid_search(["ALL"])
。然后,您可以像这样以 RFC822 (.eml) 格式(包括它们的附件)获取它们:
require "net/imap"
require "mail"
# initialize your imap object here
imap = Net::IMAP.new(...)
imap.login(...)
imap.list("", "*").map(&:name).each do |mailbox|
imap.examine(mailbox)
# Create directory for mailbox backup
Dir.mkdir(mailbox) unless Dir.exist? mailbox
uids = imap.uid_search(["ALL"])
uids.each_with_index do |uid, i|
# fetch the email in RFC822 format
raw_email = imap.uid_fetch(uid, "RFC822").first.attr["RFC822"]
# use the "mail" gem to parse the raw email and extract some useful info
email = Mail.new(raw_email)
puts "[#{i+1}/#{uids.length}] Saving email #{mailbox}/#{uid} (#{email.subject.inspect} from #{email.from.first} at #{email.date})"
# save the email to a file
File.write(File.join(mailbox, "#{uid}.eml"), raw_email)
end
end
我需要一个脚本来获取我所有文件夹中的所有电子邮件,并将它们连同附件一起进行本地备份。here but it doesn't bring me further with listing all emails belongig to a folder. Also reading the RFC 不会让我更进一步。
我发的时候
imap.list("", "*")
和
imap.examine("SomeFolder")
如何使用它遍历 SomeFolder
的所有电子邮件?
我将如何进一步发出查询以获取消息和相关附件?
要获取邮箱中所有电子邮件的 UID,请使用 imap.uid_search(["ALL"])
。然后,您可以像这样以 RFC822 (.eml) 格式(包括它们的附件)获取它们:
require "net/imap"
require "mail"
# initialize your imap object here
imap = Net::IMAP.new(...)
imap.login(...)
imap.list("", "*").map(&:name).each do |mailbox|
imap.examine(mailbox)
# Create directory for mailbox backup
Dir.mkdir(mailbox) unless Dir.exist? mailbox
uids = imap.uid_search(["ALL"])
uids.each_with_index do |uid, i|
# fetch the email in RFC822 format
raw_email = imap.uid_fetch(uid, "RFC822").first.attr["RFC822"]
# use the "mail" gem to parse the raw email and extract some useful info
email = Mail.new(raw_email)
puts "[#{i+1}/#{uids.length}] Saving email #{mailbox}/#{uid} (#{email.subject.inspect} from #{email.from.first} at #{email.date})"
# save the email to a file
File.write(File.join(mailbox, "#{uid}.eml"), raw_email)
end
end