Skip to content

Instantly share code, notes, and snippets.

@Pomeha
Last active June 21, 2019 21:29
Show Gist options
  • Save Pomeha/7b1c0c52a550742d4c0545548a6555fc to your computer and use it in GitHub Desktop.
Save Pomeha/7b1c0c52a550742d4c0545548a6555fc to your computer and use it in GitHub Desktop.
Simple new emails parcer with IMAP for rails with gem 'mail'
# frozen_string_literal: true
class Mails::ReceiveRecent
def call
client = Mails::SetClient.new.call
receive_messages(client)
end
private
def receive_messages(client)
client.select('inbox')
messages = []
client.search(['not', 'seen']).each do |message_id|
msg = client.fetch(message_id, 'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string(msg)
messages << create_message(mail, message_id)
set_message_to_seen(client, message_id)
end
messages
end
def create_message(mail, message_id)
body = form_body_message(mail)
author_name = set_author_name(mail)
subject = mail.subject
Message.create!(
author_name: author_name,
body: body,
subject: subject,
email: mail.from.first,
message_id: message_id
)
end
def form_body_message(mail)
body = mail.body.encoding == 'base64' ? Base64.decode64(mail.body.encoded) : mail.body.encoded
Nokogiri::HTML(body).text
end
def set_author_name(mail)
mail[:from].display_names.first || mail.from.first.split('@').first
end
def set_message_to_seen(client, message_id)
client.store(message_id, '+FLAGS', [:seen])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment