Chatwoot/app/jobs/inboxes/fetch_imap_emails_job.rb

53 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

require 'net/imap'
class Inboxes::FetchImapEmailsJob < ApplicationJob
queue_as :low
def perform(channel)
return unless should_fetch_email?(channel)
process_mail_for_channel(channel)
# clearing old failures like timeouts since the mail is now successfully processed
channel.reauthorized!
rescue Errno::ECONNREFUSED, Net::OpenTimeout, Net::IMAP::NoResponseError
channel.authorization_error!
rescue StandardError => e
2022-05-31 14:50:07 +00:00
# channel.authorization_error!
ChatwootExceptionTracker.new(e, account: channel.account).capture_exception
end
private
def should_fetch_email?(channel)
2022-05-30 06:50:10 +00:00
channel.imap_enabled?
end
def process_mail_for_channel(channel)
# TODO: rather than setting this as default method for all mail objects, lets if can do new mail object
# using Mail.retriever_method.new(params)
Mail.defaults do
retriever_method :imap, address: channel.imap_address,
port: channel.imap_port,
user_name: channel.imap_login,
password: channel.imap_password,
enable_ssl: channel.imap_enable_ssl
end
new_mails = false
Mail.find(what: :last, count: 10, order: :desc).each do |inbound_mail|
2022-05-31 14:50:07 +00:00
next unless inbound_mail.date.utc >= channel.imap_inbox_synced_at
begin
Imap::ImapMailbox.new.process(inbound_mail, channel)
2022-05-31 14:50:07 +00:00
rescue StandardError => e
Sentry.capture_exception(e)
end
2022-05-31 14:50:07 +00:00
new_mails = true
end
channel.update(imap_inbox_synced_at: Time.now.utc) if new_mails
2022-05-25 16:07:11 +00:00
channel.reauthorized!
end
end