Receive emails from gmail or any other email provider ( IMAP Ruby On Rails )


Configure your gmail for sending emails to other mail clients 

You can retrieve your Gmail messages with a client or device that supports IMAP, like Microsoft Outlook or Apple Mail.

Enable IMAP in your Gmail settings

1. Sign in to Gmail.
2. Click the gear in the top right .
3. Select Settings.
4. Click Forwarding and POP/IMAP.
5. Select Enable IMAP.
6. Click Save Changes.

If you're using a client that's not listed above, you can also use the following information to configure your IMAP. If you have problems, contact your mail client's customer support department for further instructions.

Incoming Mail (IMAP) Server - Requires SSL
imap.gmail.com
Port: 993
Requires SSL:Yes

For more information about imap you can refer that link
https://support.google.com/mail/troubleshooter/1668960?hl=en#ts=1665018%2C1665144

After that go to this url and you will find lots of information for allowing access by device or any mail client:
https://support.google.com/mail/accounts/answer/78754
=> You can find out the screenshot of same thing below that I have followed to get access for my ruby on rails application

1. Allow access to your Google account: 
https://accounts.google.com/b/0/DisplayUnlockCaptcha



2. Access for less secure apps:
https://www.google.com/settings/security/lesssecureapps



After doing all these configurations and setting, we can access the gmail emails using IMAP : 

We are using ruby libraries to fetching emails from gmail  using :
An IMAP client connects to a server, and then authenticates itself using either authenticate() or login().

List sender and subject of all recent messages in the default mailbox

require "net/imap.rb"
imap = Net::IMAP.new('imap.gmail.com',993,true)
# We are using gmail as a mail provider so below mentioned method can be differ as per mail provider
imap.login('test@gmail.com', 'password')
imap.examine('INBOX')
imap.search(["All"]) // Shows all ids of inbox message
imap.search(["All"]) /
imap.search(["RECENT"]).each do |message_id|
  envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  body = imap.fetch(message_id,'BODY[TEXT]')[0].attr['BODY[TEXT]']
  puts "#{envelope.from[0].name}: \t#{envelope.subject}"
end


For more information about using imap with ruby you can refer below mentioned link
http://ruby-doc.org/stdlib-1.9.3/libdoc/net/imap/rdoc/Net/IMAP.html


Example: Imap service that fetch the new updated emails from gmail. We are saving id of last gmail mail in database
    
class ImapService
  require "net/imap.rb"

  def initialize(params={})
    @email = params[:email] || 'example@gmail.com'
    @password = params[:password] ||  'testpassword'
    @imap_server = params[:imap_server] ||  'imap.gmail.com'
    @port = params[:port] || 993
    @ssl = params[:ssl] || true
  end

  def save_emails_in_database
    imap = select_inbox
    latest_email = LatestEmail.last
    ## Check that in database we have stored an id of last fetched email or not
    last_email_id = latest_email.email_id rescue nil
    if last_email_id
      ## We will fetch all emails greater than the saved id in database
      new_email_ids = fetch_latest_emails(imap, last_email_id)
      fetch_body_and_save(imap, new_email_ids)
      last_email_id = new_email_ids.last
    else
      last_email_id = fetch_last_email(imap)
    end
    true
    ## Save last_email_id in database 
    if latest_email.blank?
     latest_email = LatestEmail.new(email_id: last_email_id)
    else
     latest_email.email_id=last_email_id
    end
    latest_email.save
  end

  def save_latest_emails_in_database
    begin
     save_emails_in_database
    rescue
      false
    end
  end

  private
    attr_reader :email, :password, :imap_server, :password, :port, :ssl

  # attr_reader :address

  def external_imap_service
    Net::IMAP
  end

  def fetch_latest_emails(imap, last_email_id)
    imap.search("#{last_email_id}:*")
  end

  def fetch_all_emails(imap)
    imap.search("all").last
  end

  def connect_to_imap
    external_imap_service.new(imap_server,port,ssl)
  end

  def select_inbox
    imap = connect_to_imap
    imap.login(email, password)
    imap.examine('INBOX')
    return imap
  end

  def fetch_body_and_save(imap, new_email_ids)
    new_email_ids.each do |email_id|
      body_text = fetch_email_body(imap, email_id)
      ## Save your emails from here :-)
    end
  end

  def fetch_email_body(imap, email_id)
     imap.fetch(email_id,'BODY[TEXT]')[0].attr['BODY[TEXT]']
  end

end





Post a Comment

2 comments:

  1. Site Traffic: As talked about above, it is hard to see how individuals are drawing in with your image through disconnected promoting.ExcelR Digital Marketing Course in Sydney

    ReplyDelete
  2. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. Haga clic aqui

    ReplyDelete