Search code examples
ruby-on-railsrubygmailgmail-imap

Read Gmail XOAUTH mails without marking it read


I'm trying to read email from GMail using gmail-xoauth Gem. I want to read the email and leave its unread status.

First, I tried reading just the header. Works.

imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', email, access_token)
imap.select('INBOX')
imap.search(["SINCE", since]).each do |message_id|

    msg = imap.fetch(message_id,'RFC822.HEADER')[0].attr['RFC822.HEADER']
    mail = Mail.read_from_string msg
    puts mail.subject
end

Now, I want to read the body/text of the Email without marking it read.


Solution

  • Based on the documentation you need to use the store method. The documentation mentions:

    store(set, attr, flags)

    Sends a STORE command to alter data associated with messages in the mailbox, in particular their flags. The set parameter is a number or an array of numbers or a Range object. Each number is a message sequence number. attr is the name of a data item to store: ‘FLAGS’ means to replace the message’s flag list with the provided one; ‘+FLAGS’ means to add the provided flags; and ‘-FLAGS’ means to remove them. flags is a list of flags.

    The return value is an array of Net::IMAP::FetchData. For example:

    p imap.store(6..8, "+FLAGS", [:Deleted])
    #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
    #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
    #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
    

    So you have to remove the :Seen flag

    imap.store(message_id, "-FLAGS", [:Seen])