Class: Nuntius::RetrieveInboundMailService

Inherits:
ApplicationService show all
Defined in:
app/services/nuntius/retrieve_inbound_mail_service.rb

Instance Method Summary collapse

Instance Method Details

#performObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/services/nuntius/retrieve_inbound_mail_service.rb', line 9

def perform
  Mail::IMAP.new(context.settings).all do |message, imap, uid|
    inbound_message = Nuntius::InboundMessage.find_or_create_by!(transport: 'mail', provider: 'imap', provider_id: message.message_id,
                                                                 digest: Digest::SHA256.hexdigest(message.to_s), status: 'pending')
    inbound_message.from = message.from
    inbound_message.to = message.to
    inbound_message.text = message.body
    # inbound_message.metadata = params
    inbound_message.save!

    if inbound_message.raw_message.attached?
      if Digest::SHA256.hexdigest(message.to_s) == Digest::SHA256.hexdigest(inbound_message.raw_message.download)
        # Only if we have an attachment and it's digest is the same as we find in the mailbox, delete!
        # This never happens on the first round of fetching it.
        imap.store(uid, '+FLAGS', [Net::IMAP::DELETED])
        imap.expunge
      end
    else
      si = StringIO.new
      si.write(message.to_s)
      si.rewind
      inbound_message.raw_message.attach(io: si, filename: message.message_id)
      Nuntius::ProcessInboundMessageJob.perform_later(inbound_message)
    end
  end
end