Class: Mail::IMAP

### Home Classes Methods

### In Files

- lib/mail/network/retriever_methods/imap.rb

### Parent

Mail::Retriever

### Methods

- ::new
- #connection
- #delete_all
- #find

### Files

- CHANGELOG.rdoc
- TODO.rdoc
- VERSION

### Class/Module Index

Quicksearch

- Mail
- Mail::Address
- Mail::AddressContainer
- Mail::AddressLists
- Mail::AddressLists::PrimaryAddress0
- Mail::AddressLists::PrimaryAddress1
- Mail::AddressListsParser
- Mail::AttachmentsList
- Mail::BccField
- Mail::Body
- Mail::CcField
- Mail::CheckDeliveryParams
- Mail::CommentsField
- Mail::Configuration
- Mail::ContentDescriptionField
- Mail::ContentDisposition
- Mail::ContentDisposition::ContentDisposition0
- Mail::ContentDisposition::ContentDisposition1
- Mail::ContentDisposition::ContentDisposition2
- Mail::ContentDisposition::DispositionType0
- Mail::ContentDisposition::DispositionType1
- Mail::ContentDisposition::Parameter0
- Mail::ContentDisposition::Parameter1
- Mail::ContentDisposition::Value0
- Mail::ContentDispositionField
- Mail::ContentDispositionParser
- Mail::ContentIdField
- Mail::ContentLocation
- Mail::ContentLocation::Location0
- Mail::ContentLocation::Primary0
- Mail::ContentLocationField
- Mail::ContentLocationParser
- Mail::ContentTransferEncoding
- Mail::ContentTransferEncoding::Primary0
- Mail::ContentTransferEncodingElement
- Mail::ContentTransferEncodingField
- Mail::ContentTransferEncodingParser
- Mail::ContentType
- Mail::ContentType::CompositeType0
- Mail::ContentType::CompositeType1
- Mail::ContentType::ContentType0
- Mail::ContentType::ContentType1
- Mail::ContentType::ContentType2
- Mail::ContentType::DiscreteType0
- Mail::ContentType::DiscreteType1
- Mail::ContentType::DiscreteType2
- Mail::ContentType::DiscreteType3
- Mail::ContentType::DiscreteType4
- Mail::ContentType::Parameter0
- Mail::ContentType::Parameter1
- Mail::ContentType::Value0
- Mail::ContentTypeField
- Mail::ContentTypeParser
- Mail::DateField
- Mail::DateTime
- Mail::DateTime::Primary0
- Mail::DateTime::Primary1
- Mail::DateTimeParser
- Mail::Encodings
- Mail::Encodings::Base64
- Mail::Encodings::Binary
- Mail::Encodings::EightBit
- Mail::Encodings::QuotedPrintable
- Mail::Encodings::SevenBit
- Mail::Encodings::TransferEncoding
- Mail::Envelope
- Mail::EnvelopeFrom
- Mail::EnvelopeFrom::CtimeDate0
- Mail::EnvelopeFrom::Primary0
- Mail::EnvelopeFromElement
- Mail::EnvelopeFromParser
- Mail::Exim
- Mail::Field
- Mail::Field::FieldError
- Mail::FieldList
- Mail::FileDelivery
- Mail::FromField
- Mail::Header
- Mail::IMAP
- Mail::InReplyToField
- Mail::IndifferentHash
- Mail::KeywordsField
- Mail::Matchers
- Mail::Matchers::HasSentEmailMatcher
- Mail::Message
- Mail::MessageIdField
- Mail::MessageIds
- Mail::MessageIds::Primary0
- Mail::MessageIdsElement
- Mail::MessageIdsParser
- Mail::MimeVersion
- Mail::MimeVersion::Version0
- Mail::MimeVersion::Version1
- Mail::MimeVersionElement
- Mail::MimeVersionField
- Mail::MimeVersionParser
- Mail::Multibyte
- Mail::Multibyte::Chars
- Mail::Multibyte::EncodingError
- Mail::Multibyte::Unicode
- Mail::Multibyte::Unicode::Codepoint
- Mail::Multibyte::Unicode::UnicodeDatabase
- Mail::OptionalField
- Mail::POP3
- Mail::ParameterHash
- Mail::Part
- Mail::PartsList
- Mail::Patterns
- Mail::PhraseList
- Mail::PhraseLists
- Mail::PhraseLists::PrimaryPhrase0
- Mail::PhraseListsParser
- Mail::RFC2045
- Mail::RFC2045::CustomXToken0
- Mail::RFC2045Parser
- Mail::RFC2822
- Mail::RFC2822::AddrSpec0
- Mail::RFC2822::Address0
- Mail::RFC2822::AddressList0
- Mail::RFC2822::AddressList1
- Mail::RFC2822::AngleAddr0
- Mail::RFC2822::Atom0
- Mail::RFC2822::CFWS0
- Mail::RFC2822::CFWS1
- Mail::RFC2822::Comment0
- Mail::RFC2822::Comment1
- Mail::RFC2822::Date0
- Mail::RFC2822::DateTime0
- Mail::RFC2822::DateTime1
- Mail::RFC2822::Day0
- Mail::RFC2822::DayOfWeek0
- Mail::RFC2822::DomainLiteral0
- Mail::RFC2822::DomainLiteral1
- Mail::RFC2822::DomainText0
- Mail::RFC2822::DomainText1
- Mail::RFC2822::DotAtom0
- Mail::RFC2822::DotAtomText0
- Mail::RFC2822::FWS0
- Mail::RFC2822::FWS1
- Mail::RFC2822::Group0
- Mail::RFC2822::Hour0
- Mail::RFC2822::ItemName0
- Mail::RFC2822::ItemName1
- Mail::RFC2822::LocalDotAtom0
- Mail::RFC2822::LocalDotAtomText0
- Mail::RFC2822::Mailbox0
- Mail::RFC2822::MailboxList0
- Mail::RFC2822::MailboxList1
- Mail::RFC2822::MailboxListGroup0
- Mail::RFC2822::MessageIds0
- Mail::RFC2822::MessageIds1
- Mail::RFC2822::Minute0
- Mail::RFC2822::Month0
- Mail::RFC2822::MsgId0
- Mail::RFC2822::MsgIdDomainText0
- Mail::RFC2822::MsgIdDomainText1
- Mail::RFC2822::MsgIdDotAtomText0
- Mail::RFC2822::MsgIdValue0
- Mail::RFC2822::NameAddr0
- Mail::RFC2822::NameValList0
- Mail::RFC2822::NameValList1
- Mail::RFC2822::NameValList2
- Mail::RFC2822::NameValPair0
- Mail::RFC2822::NoFoldLiteral0
- Mail::RFC2822::NoFoldQuote0
- Mail::RFC2822::Path0
- Mail::RFC2822::PhraseList0
- Mail::RFC2822::PhraseList1
- Mail::RFC2822::QuotedDomain0
- Mail::RFC2822::QuotedPair0
- Mail::RFC2822::QuotedString0
- Mail::RFC2822::QuotedString1
- Mail::RFC2822::Received0
- Mail::RFC2822::Return0
- Mail::RFC2822::Second0
- Mail::RFC2822::Time0
- Mail::RFC2822::TimeOfDay0
- Mail::RFC2822::TimeOfDay1
- Mail::RFC2822::Year0
- Mail::RFC2822::Zone0
- Mail::RFC2822Obsolete
- Mail::RFC2822Obsolete::ObsAddrList0
- Mail::RFC2822Obsolete::ObsAddrList1
- Mail::RFC2822Obsolete::ObsAngleAddr0
- Mail::RFC2822Obsolete::ObsBcc0
- Mail::RFC2822Obsolete::ObsCc0
- Mail::RFC2822Obsolete::ObsComments0
- Mail::RFC2822Obsolete::ObsDay0
- Mail::RFC2822Obsolete::ObsDay1
- Mail::RFC2822Obsolete::ObsDayOfWeek0
- Mail::RFC2822Obsolete::ObsDomain0
- Mail::RFC2822Obsolete::ObsDomain1
- Mail::RFC2822Obsolete::ObsDomainList0
- Mail::RFC2822Obsolete::ObsDomainList1
- Mail::RFC2822Obsolete::ObsFWS0
- Mail::RFC2822Obsolete::ObsFWS1
- Mail::RFC2822Obsolete::ObsFrom0
- Mail::RFC2822Obsolete::ObsHour0
- Mail::RFC2822Obsolete::ObsHour1
- Mail::RFC2822Obsolete::ObsInReplyTo0
- Mail::RFC2822Obsolete::ObsKeywords0
- Mail::RFC2822Obsolete::ObsLocalPart0
- Mail::RFC2822Obsolete::ObsLocalPart1
- Mail::RFC2822Obsolete::ObsMboxList0
- Mail::RFC2822Obsolete::ObsMboxList1
- Mail::RFC2822Obsolete::ObsMessageId0
- Mail::RFC2822Obsolete::ObsMinute0
- Mail::RFC2822Obsolete::ObsMinute1
- Mail::RFC2822Obsolete::ObsMonth0
- Mail::RFC2822Obsolete::ObsOptional0
- Mail::RFC2822Obsolete::ObsOrigDate0
- Mail::RFC2822Obsolete::ObsPhraseList0
- Mail::RFC2822Obsolete::ObsPhraseList1
- Mail::RFC2822Obsolete::ObsQp0
- Mail::RFC2822Obsolete::ObsReceived0
- Mail::RFC2822Obsolete::ObsReferences0
- Mail::RFC2822Obsolete::ObsReplyTo0
- Mail::RFC2822Obsolete::ObsResentBcc0
- Mail::RFC2822Obsolete::ObsResentCc0
- Mail::RFC2822Obsolete::ObsResentDate0
- Mail::RFC2822Obsolete::ObsResentFrom0
- Mail::RFC2822Obsolete::ObsResentMid0
- Mail::RFC2822Obsolete::ObsResentRply0
- Mail::RFC2822Obsolete::ObsResentSend0
- Mail::RFC2822Obsolete::ObsResentTo0
- Mail::RFC2822Obsolete::ObsReturn0
- Mail::RFC2822Obsolete::ObsRoute0
- Mail::RFC2822Obsolete::ObsSecond0
- Mail::RFC2822Obsolete::ObsSecond1
- Mail::RFC2822Obsolete::ObsSender0
- Mail::RFC2822Obsolete::ObsSubject0
- Mail::RFC2822Obsolete::ObsText0
- Mail::RFC2822Obsolete::ObsText1
- Mail::RFC2822Obsolete::ObsTo0
- Mail::RFC2822Obsolete::ObsYear0
- Mail::RFC2822Obsolete::ObsYear1
- Mail::RFC2822ObsoleteParser
- Mail::RFC2822Parser
- Mail::Received
- Mail::Received::Primary0
- Mail::ReceivedElement
- Mail::ReceivedField
- Mail::ReceivedParser
- Mail::ReferencesField
- Mail::ReplyToField
- Mail::ResentBccField
- Mail::ResentCcField
- Mail::ResentDateField
- Mail::ResentFromField
- Mail::ResentMessageIdField
- Mail::ResentSenderField
- Mail::ResentToField
- Mail::Retriever
- Mail::ReturnPathField
- Mail::Ruby18
- Mail::Ruby19
- Mail::RubyVer
- Mail::SMTP
- Mail::SMTPConnection
- Mail::SenderField
- Mail::Sendmail
- Mail::StructuredField
- Mail::SubjectField
- Mail::TestMailer
- Mail::TestRetriever
- Mail::ToField
- Mail::UnstructuredField
- Mail::Utilities
- Mail::VERSION
- ActiveSupport
- ActiveSupport::Multibyte
- Net
- Net::SMTP
- Object
- String

No matching classes.

# Mail::IMAP

The IMAP retriever allows to get the last, first or all emails from a IMAP server. Each email retrieved (RFC2822) is given as an instance of `Message`.

While being retrieved, emails can be yielded if a block is given.

### Example of retrieving Emails from GMail:

    Mail.defaults do
      retriever_method :imap, { :address             => "imap.googlemail.com",
                                :port                => 993,
                                :user_name           => '<username>',
                                :password            => '<password>',
                                :enable_ssl          => true }
    end

    Mail.all    #=> Returns an array of all emails
    Mail.first  #=> Returns the first unread email
    Mail.last   #=> Returns the last unread email

You can also pass options into Mail.find to locate an email in your imap mailbox with the following options:

    mailbox: name of the mailbox used for email retrieval. The default is 'INBOX'.
    what:    last or first emails. The default is :first.
    order:   order of emails returned. Possible values are :asc or :desc. Default value is :asc.
    count:   number of emails to retrieve. The default value is 10. A value of 1 returns an
             instance of Message, not an array of Message instances.
    keys:    are passed as criteria to the SEARCH command.  They can either be a string holding the entire search string,
             or a single-dimension array of search keywords and arguments.  Refer to  [IMAP] section 6.4.4 for a full list
             The default is 'ALL'

    Mail.find(:what => :first, :count => 10, :order => :asc, :keys=>'ALL')
    #=> Returns the first 10 emails in ascending order

### Attributes

settings[RW]

### Public Class Methods

new(values) click to toggle source

    # File lib/mail/network/retriever_methods/imap.rb, line 40
    def initialize(values)
      self.settings = { :address              => "localhost",
                        :port                 => 143,
                        :user_name            => nil,
                        :password             => nil,
                        :authentication       => nil,
                        :enable_ssl           => false }.merge!(values)
    end

### Public Instance Methods

connection(&block) click to toggle source

Returns the connection object of the retrievable (IMAP or POP3)

    # File lib/mail/network/retriever_methods/imap.rb, line 121
    def connection(&block)
      raise ArgumentError.new('Mail::Retrievable#connection takes a block') unless block_given?

      start do |imap|
        yield imap
      end
    end

delete_all(mailbox='INBOX') click to toggle source

Delete all emails from a IMAP mailbox

    # File lib/mail/network/retriever_methods/imap.rb, line 108
    def delete_all(mailbox='INBOX')
      mailbox ||= 'INBOX'
      mailbox = Net::IMAP.encode_utf7(mailbox)

      start do |imap|
        imap.uid_search(['ALL']).each do |message_id|
          imap.uid_store(message_id, "+FLAGS", [Net::IMAP::DELETED])
        end
        imap.expunge
      end
    end

find(options={}, &block) click to toggle source

Find emails in a IMAP mailbox. Without any options, the 10 last received emails are returned.

Possible options:

    mailbox: mailbox to search the email(s) in. The default is 'INBOX'.
    what:    last or first emails. The default is :first.
    order:   order of emails returned. Possible values are :asc or :desc. Default value is :asc.
    count:   number of emails to retrieve. The default value is 10. A value of 1 returns an
             instance of Message, not an array of Message instances.
    read_only: will ensure that no writes are made to the inbox during the session.  Specifically, if this is
               set to true, the code will use the EXAMINE command to retrieve the mail.  If set to false, which
               is the default, a SELECT command will be used to retrieve the mail
               This is helpful when you don't want your messages to be set to read automatically. Default is false.
    delete_after_find: flag for whether to delete each retreived email after find. Default
            is false. Use #find_and_delete if you would like this to default to true.
    keys:   are passed as criteria to the SEARCH command.  They can either be a string holding the entire search string,
            or a single-dimension array of search keywords and arguments.  Refer to  [IMAP] section 6.4.4 for a full list
            The default is 'ALL'

    # File lib/mail/network/retriever_methods/imap.rb, line 69
    def find(options={}, &block)
      options = validate_options(options)

      start do |imap|
        options[:read_only] ? imap.examine(options[:mailbox]) : imap.select(options[:mailbox])

        message_ids = imap.uid_search(options[:keys])
        message_ids.reverse! if options[:what].to_sym == :last
        message_ids = message_ids.first(options[:count]) if options[:count].is_a?(Integer)
        message_ids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
                                (options[:what].to_sym != :last && options[:order].to_sym == :desc)

        if block_given?
          message_ids.each do |message_id|
            fetchdata = imap.uid_fetch(message_id, ['RFC822'])[0]
            new_message = Mail.new(fetchdata.attr['RFC822'])
            new_message.mark_for_delete = true if options[:delete_after_find]
            if block.arity == 3
              yield new_message, imap, message_id
            else
              yield new_message
            end
            imap.uid_store(message_id, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find] && new_message.is_marked_for_delete?
          end
          imap.expunge if options[:delete_after_find]
        else
          emails = []
          message_ids.each do |message_id|
            fetchdata = imap.uid_fetch(message_id, ['RFC822'])[0]
            emails << Mail.new(fetchdata.attr['RFC822'])
            imap.uid_store(message_id, "+FLAGS", [Net::IMAP::DELETED]) if options[:delete_after_find]
          end
          imap.expunge if options[:delete_after_find]
          emails.size == 1 && options[:count] == 1 ? emails.first : emails
        end
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.