Method: Client#retrieve_emails

Defined in:
lib/client.rb

#retrieve_emails(imap, search_condition, folder, &process_email_block) ⇒ Object

retrieve_emails

retrieve any mail from a folder, followin specified serach condition for any mail retrieved call a specified block



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/client.rb', line 75

def retrieve_emails(imap, search_condition, folder, &process_email_block)

  # examine will read email and sets flags unread
  # https://stackoverflow.com/questions/16516464/read-gmail-xoauth-mails-without-marking-it-read
  imap.examine folder

  message_ids = imap.uid_search(search_condition)

  meta_dir = @download_path + 'meta/'
  message_ids_saved = File.directory?(meta_dir) ? (Dir.entries meta_dir).map { |i| i.split("_").first.to_i } : []

  message_ids = message_ids - message_ids_saved

  if @debug
    if message_ids.empty?
      @logger.info "No new emails found..."
    elsif message_ids_saved.any?
      @logger.info "Found emails saved in your #{@client_type}. Downloading only #{message_ids.count} new emails..."
    else
      @logger.info "Downloading #{message_ids.count} emails."
    end
  end

  message_ids.each_with_index do |message_id, i|
    # fetch all the email contents
    data = imap.uid_fetch(message_id, "RFC822")
    data.each do |d|
      msg = d.attr['RFC822']
      # instantiate a Mail object to avoid further IMAP parameters nightmares
      mail = Mail.read_from_string msg

      # call the block with mail object as param
      process_email_block.call mail, i, i == message_ids.length-1, message_id

      # mark as read
      if @mark_as_read
        imap.store(message_id, "+FLAGS", [:Seen])
      end
    end
  end
end