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

59 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
  3. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. Buy Old Gmail Accounts

    ReplyDelete
  4. Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. windows iso

    ReplyDelete
  5. thank you for this awesome and informative post www.hotmail.com

    ReplyDelete
  6. This is a fantastic website and I can not recommend you guys enough. Buy Gmail Accounts

    ReplyDelete
  7. I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. Buy Old Gmail Accounts

    ReplyDelete
  8. you may still get services popping-up and, any attempts to re-install it or install other security software may be denied. If that is what happens in your case, windows 10

    ReplyDelete
  9. He needs to have a comprehension of the business, items and its utilization. He is relied upon to make a format and structure the site. For future extensions, Digital Market service

    ReplyDelete
  10. lines including promoting, visual depiction, website composition and improvement, Advanced organization administrations cross such a large number of the customary assistance

    ReplyDelete
  11. lines including promoting, visual depiction, website composition and improvement, blog comment service

    ReplyDelete
  12. Portable promoting, radio, TV, electronic boards and significantly more are accessible as showcasing outlets. blog comments service in 1$

    ReplyDelete
  13. that your data is unmistakable to the potential client at the fitting time. In the computerized advertising world, Stationary Design

    ReplyDelete
  14. Experience - What sort of aptitudes and experience does the organization have? To what extent has it been working together? Business Card Design

    ReplyDelete
  15. The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought you have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention. hotmail-inicio-sesion.com/

    ReplyDelete
  16. I would like to say that this blog really convinced me to do it! Thanks, very good post. purple gemstone

    ReplyDelete
  17. This post is very simple to read and appreciate without leaving any details out. Great work! Buy Social Bookmarking

    ReplyDelete
  18. Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. garnet ring

    ReplyDelete
  19. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!! hotmail.com

    ReplyDelete
  20. I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!! I definitely really liked every part of it and i also have you saved to fav to look at new information in your site. hotmail.com

    ReplyDelete
  21. Incredible post yet I was contemplating whether you could make somewhat more with respect to this issue? I'd be grateful for the remote possibility that you could clarify fairly further. Worth it Click Here

    ReplyDelete
  22. Unprecedented article. I believe you will continue having numerous such incredible articles to bestow to us. I acknowledge numerous people will be shocked to scrutinize this article. thank you. Visit Us

    ReplyDelete
  23. I am thankful to you for sharing this plethora of useful information. I found this resource utmost beneficial for me. Thanks a lot for hard work. aprenda acessar o Hotmail login agora

    ReplyDelete
  24. Thanks for an interesting blog. What else may I get that sort of info written in such a perfect approach? I have an undertaking that I am just now operating on, and I have been on the lookout for such info.
    Best Data Science training in Mumbai

    Data Science training in Mumbai


    ReplyDelete
  25. Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards, buy instagram likes uk

    ReplyDelete
  26. The craving to bring in cash online using social stages is totally typical. So as to accomplish this journey, an ideal blogging framework is required. A sound blogging framework would permit its client to embrace a deliberate way to deal with extinguish his blogging attempts Read More

    ReplyDelete
  27. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work entrar hotmail

    ReplyDelete
  28. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
    https://360digitmg.com/tableau-training-in-hyderabad

    ReplyDelete
  29. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. email bulk mail

    ReplyDelete
  30. With an best email extractor software you will be able to build your list much quicker as it will spider its way through various search engines and gather URL's that meet the search based on keywords.

    ReplyDelete
  31. Data Analytics Course Pune wow... what a great blog, this writter who wrote this article it's realy a great blogger, this article so inspiring me to be a better person in some of them hope you will give more information on this topics in your next articles.
    I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!

    ReplyDelete
  32. Royal photo Booths Australia At Royal Booths,we want to make a good impression with you, hence we go above & beyond when it comes to forming that initial relationship with our customers.

    ReplyDelete
  33. Our store offers many styles of advanced tpe sex dolls, soft skin made of tpe material, realistic tpe sex dolls to achieve your desire for sex.Buy real realistic tpe ... realistic sex doll

    ReplyDelete
  34. In the realm of web advertising, an email list is a very significant resource. In the event that a web advertiser can persuade you to give him your email, at that point he can send arrangements and items to you constantly and possibly rake in boatloads of cash off of you. CBT Mass Email Sender Software

    ReplyDelete
  35. Journey to San Diego: ups and downs


    The day when I planned to move to San Diego, due to my endeavors and job issues. It was the day, where I knew how things would go after we would travel. I’ve been reading about the city before I finally decided to move to San Diego. The first thing that fascinated me about San Diego was the different climate seasons San Diego has.

    ReplyDelete
  36. hiring movers in California

    So, you have decided to take a step ahead and make the very difficult decision of your life that is to relocate or plan a move. This will be the most stressful time you will ever have if you haven’t planned it properly. If you’re planning to move your house or business to an entirely new state or place then you must be cautious about how you will take the things and most importantly, how will you carry them? Right, if yes then choosing the right moving company is what you have to do.

    ReplyDelete
  37. Latest News Dental Success Blo

    Townie News Wire. Events. Upcoming Events Townie Webinars. More. Free e-Books Townie Poll Townie Perks Student Membership · Download .Most Active Blogs. Skip Navigation ... Dentaltown Learning Online. By Howard ... 11/6/2018 · Dental Success Blog ... The Best Practices Show with Kirk Behrendt.

    ReplyDelete
  38. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. facebook email extractor address

    ReplyDelete
  39. Outstanding article! I want people to know just how good this information is in your article. Your views are much like my own concerning this subject. I will visit daily your blog because I know. It may be very beneficial for me. send 500 emails at once

    ReplyDelete
  40. Superslot

    ซุปเปอร์สล็อต เราคือผู้ให้บริการสล็อตออนไลน์มีตัวเกมสล็อตให้เลือกเล่นจำนวนมากบนมือถืออันดับ 1 ทั้งฟรีเครดิต 50 ,100 , 150 , 200 ที่สามารถ

    ReplyDelete
  41. spperslot

    Superslot หรือ ภาษาไทย บ้านๆ เรียกว่า ซุปเปอร์สล็อต เราคือผู้ให้บริการสล็อตออนไลน์มีตัวเกมสล็อตให้เลือกเล่นจำนวนมากบนมือถืออันดับ 1 ทั้งฟรี

    ReplyDelete
  42. jandamovies Bokep Indo, Bokep Barat, Bokep Asia, Bokep Gay, Bokep Semi.

    ReplyDelete
  43. If you desire to grow your knowledge just keep visiting this web page and be updated with the latest posted here
    12 volt 100 ah LFP battery

    ReplyDelete
  44. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!. Buy Gmail Accounts

    ReplyDelete
  45. voyance telephone espoir. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.

    ReplyDelete
  46. The online andar bahar game is a thrilling digital adaptation of the classic Indian card game, offering players an exciting and accessible way to enjoy this traditional pastime from the comfort of their homes.

    ReplyDelete
  47. play roulette online in India offers a convenient and exciting way to enjoy this classic casino game from the comfort of your home

    ReplyDelete
  48. Click here is rapidly gaining popularity, offering players an immersive gaming experience with real-time interaction and authentic casino ambiance from the comfort of their homes.

    ReplyDelete
  49. The Online Rummy Games provide an exhilarating blend of skill and strategy. They're not just about entertainment but also sharpening cognitive abilities. The convenience of playing anytime, anywhere adds to their appeal. It's a great way to unwind and challenge oneself mentally.

    ReplyDelete
  50. Effortlessly access your account with the TC Lottery login to check your lottery results and manage your tickets online.

    ReplyDelete
  51. Live roulette games offer an authentic and immersive casino experience, allowing players to enjoy the excitement of a real roulette wheel with the convenience of playing online. The live interaction with professional dealers and real-time gameplay makes it a top choice for anyone looking to experience the thrill of roulette from the comfort of their home.

    ReplyDelete
  52. Casino games for money offer an exciting mix of entertainment and the potential for winnings, but it's essential to play responsibly and within your budget.

    ReplyDelete
  53. Psychological Benefits of Standing Work: Focus, Mood, and Small Calorie Changes
    Switching between sitting and standing at work affects more than just your back — it changes how you think, feel and sustain energy throughout the day. A growing body of research and practical workplace experience shows that standing work can sharpen focus, lift mood, and produce subtle metabolic shifts that add up over time. This article explains the psychological mechanisms behind those benefits, summarizes the small-but-meaningful calorie differences, and gives actionable tips to design a standing workstation that protects cognition and wellbeing.
    Executive Standing Desks: signaling status and encouraging movement
    Large, well-equipped workstations — often represented by executive standing desks — do more than provide space for multiple monitors and paperwork. They act as a visual and tacit signal that work matters, which can heighten engagement and ownership. When an office invests in a commanding, adjustable desk for a team lead or executive, it sends a message that comfort and productivity are priorities. From a psychological angle, the improved environment reduces contextual distractions (clutter, awkward postures) so the brain can allocate more resources to focused tasks. More importantly, executive-grade desks typically include memory presets that make transitions between sitting and standing frictionless; fewer interruptions to workflow means longer, deeper periods of concentration.
    Standing Corner Desk: zoning work to improve task focus
    Standing corner desks are particularly useful for users who split attention across different tasks. The L-shaped footprint creates natural zones — one wing for deep work and another for collaborative or administrative tasks. This physical separation aids cognitive switching: by shifting stance and subtly moving to a different zone, workers cue their brains to change modes. The movement itself (standing, taking a small step along the corner) acts as a micro ritual that improves task recall and reduces cognitive fatigue. Over days and weeks these small behavioral triggers help build disciplined attention habits.
    Standing Desk White: visual clarity and reduced visual fatigue
    A bright, light-reflective surface like a standing desk white can help reduce perceived clutter and visual noise. When visual stimuli are less distracting, working memory performs better and sustained attention improves. The lighter surface also makes ambient lighting more effective — reducing squinting and eye strain, which are common causes of mental fatigue. These seemingly small visual improvements contribute to steadier moods and fewer mid-afternoon slumps.
    Standing Desk Wood: tactile comfort and mood enhancement
    Natural materials such as wood provide tactile and aesthetic cues that influence mood. A standing desk wood top can create a more calming environment than sterile laminates, decreasing stress markers and making long work sessions feel less draining. The psychological benefit comes from biophilic design principles: natural textures and tones subconsciously reduce cortisol and increase the sense of wellbeing. When people feel calmer, they are more resilient to interruptions and better able to maintain a positive, focused mindset.

    ReplyDelete
  54. Hand Crank Standing Desk: agency, routine, and small bursts of activity
    Manual adjustment mechanisms like those on a hand crank standing desk introduce a brief, self-directed physical activity into the workday. Turning a crank for a few seconds creates a small burst of intentional movement that signals a ritual change of state — from seated to standing. These micro-activities promote a feeling of agency and control, which improves mood and reduces learned helplessness common in sedentary roles. Because the adjustment requires effort, it also encourages planned transitions rather than constant, distracting repositioning.
    Glass Top Standing Desk: perceived lightness and modern work identity
    A glass top standing desk conveys modernity and precision. Psychologically, the material encourages a sense of cleanliness and order, which reduces mental clutter. For roles requiring design acuity or visual judgment, the reflective surface subtly reinforces a professional identity and focus. When workers feel that their environment matches the task — neat, modern, and efficient — they experience a cognitive alignment that supports better concentration and pride in output.
    Bamboo Standing Desk: sustainability cues and wellbeing
    Choosing a bamboo standing desk can influence wellbeing beyond aesthetics: sustainability is a value cue. When employees perceive their equipment as eco-friendly, it boosts morale and purpose — two psychological factors that improve engagement and reduce burnout. A desk that aligns with personal or organizational values supports intrinsic motivation, which leads to better task immersion and a more positive mood during the workday.
    Standing Desk with Keyboard Tray: ergonomic alignment and cognitive load
    A standing desk with keyboard tray separates monitor height from typing height, allowing optimal arm and wrist alignment while keeping the screen at eye level. This ergonomic precision reduces micro-discomfort and the cognitive load associated with constant postural corrections. When the body is comfortable, the brain devotes fewer resources to pain signals and posture monitoring, leaving more capacity for complex thinking and creativity.
    Cheapest Standing Desk: accessibility and behavior change
    Affordable options — the cheapest standing desk models — lower the barrier to experimentation. Psychological benefits often begin with testing: once workers try standing and notice improved alertness, they are more likely to adopt the habit. The key is accessibility. If a budget model provides adequate stability and a straightforward height range, it can kickstart standing routines and the positive feedback loop of improved focus and mood, even without premium features.
    Ergonomic Office Chair: the seated complement that supports standing success
    Good chairs remain essential. An ergonomic office chair complements standing work by offering restorative seated intervals that sustain attention over a full day. Alternating between a well-fitted chair and standing reduces fatigue and supports consistent cognitive performance. The psychological impact of knowing you have a comfortable recovery option also reduces anxiety about trying standing; people will adopt new behaviors faster if they trust their seats will support them when needed.

    ReplyDelete
  55. Stand Up Executive Desk and Wood Standing Desk: when style matters
    If presentation or a premium feel matters, consider a Stand Up Executive Desk or a Wood Standing Desk. Executive-style tops provide ample real estate for multiple monitors, cameras, and lighting rigs — useful if you host frequent video meetings. A wood desktop adds warmth and permanence to a home office, making it feel like a true piece of furniture rather than a temporary setup. The key is to select a stable frame with sufficient load capacity so stylish tops remain functional and wobble-free.
    Why investing saves money long term: health and productivity wins
    Costs and benefits should always be weighed. A standing desk can be seen as an investment in reduced discomfort, fewer sick days, and improved concentration — outcomes that add up. Users who adopt a balanced sit–stand routine often report less back pain, fewer interruptions for stretch breaks, and better daytime energy. The cumulative effect of small improvements in movement and posture can reduce costly healthcare visits and improve sustained productivity over months and years.
    Vernal Standing Desk & Vernal Space Reviews: what buyers say
    Before you buy, check real-user evaluations. For example, some buyers search for a Vernal Standing Desk and read Vernal Space Reviews to learn about build quality, stability, and after-sales support. Reviews often highlight practical points that specs don’t show — how quiet the motor is, whether the desktop resists scratches, and how easy assembly turns out to be. Compare multiple sources of feedback to form a balanced view and choose a model that fits your priorities.
    Quick setup and usage tips to make the switch work
    Buying the right desk is only the first step. To make standing feel natural and sustainable, try these practical tips:
    Set ergonomic reference points: When standing, your elbows should be near a 90° angle and the top of your screen at eye level.
    Create a schedule: Alternate between 30–45 minutes sitting and 15–30 minutes standing, adjusting to how your body feels.
    Support your feet: Use an anti-fatigue mat and wear supportive shoes to reduce lower-limb discomfort.
    Add small movements: Walk to refill water, do gentle calf raises, or take a 2-minute stretch every hour.
    Keep accessories in reach: A supportive keyboard tray and a monitor arm help maintain ergonomic alignment across positions.
    Choosing the right model for your home
    Your ideal standing desk depends on work style, space and budget. Choose a Sit Stand Desk if you value quick posture switches; prefer an Electric Height Adjustable Desk if you want frictionless transitions and programmable heights. If your room is compact, an Adjustable L Shaped Desk can increase usable surface area. For a more classic look, a Wood Standing Desk or a larger Stand Up Executive Desk can upgrade your office aesthetics while supporting healthy movement. And if you want to learn from others, consult recent Vernal Space Reviews or other buyer feedback before committing.
    Conclusion — small change, big payoff
    Switching to a standing-friendly setup is not a panacea, but it is one of the most practical, evidence-informed changes you can make for your home office. Standing Desks and their variations — from sit–stand converters to full electric systems — help you break the cycle of long, uninterrupted sitting and build healthier habits into everyday workflows. With the right desk, a simple schedule and a few supportive accessories, you can protect your posture, sharpen focus, and make remote work feel better day after day.

    ReplyDelete