# frozen_string_literal: true
# Copyright (C) 2000 Shugo Maeda <shugo@ruby-lang.org>
# This library is distributed under the terms of the Ruby license.
# You can freely distribute/modify this library.
# Documentation: Shugo Maeda, with RDoc conversion and overview by William
# See Net::IMAP for documentation.
require_relative 'protocol'
# Net::IMAP implements Internet Message Access Protocol (IMAP) client
# functionality. The protocol is described in [IMAP].
# An IMAP client connects to a server, and then authenticates
# itself using either #authenticate() or #login(). Having
# authenticated itself, there is a range of commands
# available to it. Most work with mailboxes, which may be
# arranged in an hierarchical namespace, and each of which
# contains zero or more messages. How this is implemented on
# the server is implementation-dependent; on a UNIX server, it
# will frequently be implemented as files in mailbox format
# within a hierarchy of directories.
# To work on the messages within a mailbox, the client must
# first select that mailbox, using either #select() or (for
# read-only access) #examine(). Once the client has successfully
# selected a mailbox, they enter _selected_ state, and that
# mailbox becomes the _current_ mailbox, on which mail-item
# related commands implicitly operate.
# Messages have two sorts of identifiers: message sequence
# Message sequence numbers number messages within a mailbox
# from 1 up to the number of items in the mailbox. If a new
# message arrives during a session, it receives a sequence
# number equal to the new size of the mailbox. If messages
# are expunged from the mailbox, remaining messages have their
# sequence numbers "shuffled down" to fill the gaps.
# UIDs, on the other hand, are permanently guaranteed not to
# identify another message within the same mailbox, even if
# the existing message is deleted. UIDs are required to
# be assigned in ascending (but not necessarily sequential)
# order within a mailbox; this means that if a non-IMAP client
# rearranges the order of mailitems within a mailbox, the
# UIDs have to be reassigned. An IMAP client thus cannot
# rearrange message orders.
# === List sender and subject of all recent messages in the default mailbox
# imap = Net::IMAP.new('mail.example.com')
# imap.authenticate('LOGIN', 'joe_user', 'joes_password')
# imap.search(["RECENT"]).each do |message_id|
# envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
# puts "#{envelope.from[0].name}: \t#{envelope.subject}"
# === Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
# imap = Net::IMAP.new('mail.example.com')
# imap.authenticate('LOGIN', 'joe_user', 'joes_password')
# imap.select('Mail/sent-mail')
# if not imap.list('Mail/', 'sent-apr03')
# imap.create('Mail/sent-apr03')
# imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
# imap.copy(message_id, "Mail/sent-apr03")
# imap.store(message_id, "+FLAGS", [:Deleted])
# Net::IMAP supports concurrent threads. For example,
# imap = Net::IMAP.new("imap.foo.net", "imap2")
# imap.authenticate("cram-md5", "bar", "password")
# fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
# search_result = imap.search(["BODY", "hello"])
# fetch_result = fetch_thread.value
# This script invokes the FETCH command and the SEARCH command concurrently.
# An IMAP server can send three different types of responses to indicate
# NO:: the attempted command could not be successfully completed. For
# instance, the username/password used for logging in are incorrect;
# the selected mailbox does not exist; etc.
# BAD:: the request from the client does not follow the server's
# understanding of the IMAP protocol. This includes attempting
# commands from the wrong client state; for instance, attempting
# to perform a SEARCH command without having SELECTed a current
# mailbox. It can also signal an internal server
# failure (such as a disk crash) has occurred.
# BYE:: the server is saying goodbye. This can be part of a normal
# logout sequence, and can be used as part of a login sequence
# to indicate that the server is (for some reason) unwilling
# to accept your connection. As a response to any other command,
# it indicates either that the server is shutting down, or that
# the server is timing out the client connection due to inactivity.
# These three error response are represented by the errors
# Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and
# Net::IMAP::ByeResponseError, all of which are subclasses of
# Net::IMAP::ResponseError. Essentially, all methods that involve
# sending a request to the server can generate one of these errors.
# Only the most pertinent instances have been documented below.
# Because the IMAP class uses Sockets for communication, its methods
# are also susceptible to the various errors that can occur when
# working with sockets. These are generally represented as
# Errno errors. For instance, any method that involves sending a
# request to the server and/or receiving a response from it could
# raise an Errno::EPIPE error if the network connection unexpectedly
# goes down. See the socket(7), ip(7), tcp(7), socket(2), connect(2),
# and associated man pages.
# Finally, a Net::IMAP::DataFormatError is thrown if low-level data
# is found to be in an incorrect format (for instance, when converting
# between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is
# thrown if a server response is non-parseable.
# M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
# RFC 2060, December 1996. (Note: since obsoleted by RFC 3501)
# Alvestrand, H., "Tags for the Identification of
# Languages", RFC 1766, March 1995.
# Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
# Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
# Mail Extensions) Part One: Format of Internet Message Bodies", RFC
# Crocker, D., "Standard for the Format of ARPA Internet Text
# Messages", STD 11, RFC 822, University of Delaware, August 1982.
# Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
# Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
# Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension
# for Simple Challenge/Response", RFC 2195, September 1997.
# Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD
# Extensions", draft-ietf-imapext-sort, May 2003.
# http://savannah.gnu.org/projects/rubypki
# Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of
# Unicode", RFC 2152, May 1997.
if defined?(OpenSSL::SSL)
# Returns an initial greeting response from the server.
# Returns recorded untagged responses. For example:
# p imap.responses["EXISTS"][-1]
# p imap.responses["UIDVALIDITY"][-1]
# Returns all response handlers.
attr_reader :response_handlers
# Seconds to wait until a connection is opened.
# If the IMAP object cannot open a connection within this time,
# it raises a Net::OpenTimeout exception. The default value is 30 seconds.
attr_reader :open_timeout
# The thread to receive exceptions.
attr_accessor :client_thread
# Flag indicating a message has been seen.
# Flag indicating a message has been answered.
# Flag indicating a message has been flagged for special or urgent
# Flag indicating a message has been marked for deletion. This
# will occur when the mailbox is closed or expunged.
# Flag indicating a message is only a draft or work-in-progress version.
# Flag indicating that the message is "recent," meaning that this
# session is the first session in which the client has been notified
# Flag indicating that a mailbox context name cannot contain
NOINFERIORS = :Noinferiors
# Flag indicating that a mailbox is not selected.
# Flag indicating that a mailbox has been marked "interesting" by
# the server; this commonly indicates that the mailbox contains
# Flag indicating that the mailbox does not contains new messages.
# Returns the debug mode.
# Returns the max number of flags interned to symbols.
# Sets the max number of flags interned to symbols.
def self.max_flag_count=(count)
# Adds an authenticator for Net::IMAP#authenticate. +auth_type+
# is the type of authentication this authenticator supports
# (for instance, "LOGIN"). The +authenticator+ is an object
# which defines a process() method to handle authentication with
# the server. See Net::IMAP::LoginAuthenticator,
# Net::IMAP::CramMD5Authenticator, and Net::IMAP::DigestMD5Authenticator
# If +auth_type+ refers to an existing authenticator, it will be
# replaced by the new one.
def self.add_authenticator(auth_type, authenticator)
@@authenticators[auth_type] = authenticator
# The default port for IMAP connections, port 143
# The default port for IMAPS connections, port 993
def self.default_tls_port
alias default_imap_port default_port
alias default_imaps_port default_tls_port
alias default_ssl_port default_tls_port
# Disconnects from the server.
# try to call SSL::SSLSocket#io.
# @sock is not an SSL::SSLSocket.
# ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
@receiver_thread.raise(e)
# Returns true if disconnected from the server.
# Sends a CAPABILITY command, and returns an array of
# capabilities that the server supports. Each capability
# is a string. See [IMAP] for a list of possible
# Note that the Net::IMAP class does not modify its
# behaviour according to the capabilities of the server;
# it is up to the user of the class to ensure that
# a certain capability is supported by a server before
send_command("CAPABILITY")
return @responses.delete("CAPABILITY")[-1]
# Sends a NOOP command to the server. It does nothing.
# Sends a LOGOUT command to inform the server that the client is
# done with the connection.
# Sends a STARTTLS command to start TLS session.
def starttls(options = {}, verify = true)
send_command("STARTTLS") do |resp|
if resp.kind_of?(TaggedResponse) && resp.name == "OK"
# for backward compatibility
options = create_ssl_params(certs, verify)
start_tls_session(options)
# Sends an AUTHENTICATE command to authenticate the client.
# The +auth_type+ parameter is a string that represents
# the authentication mechanism to be used. Currently Net::IMAP
# supports the authentication mechanisms:
# LOGIN:: login using cleartext user and password.
# CRAM-MD5:: login with cleartext user and encrypted password
# (see [RFC-2195] for a full description). This
# mechanism requires that the server have the user's
# password stored in clear-text password.
# For both of these mechanisms, there should be two +args+: username
# and (cleartext) password. A server may not support one or the other
# of these mechanisms; check #capability() for a capability of
# the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
# Authentication is done using the appropriate authenticator object:
# see @@authenticators for more information on plugging in your own
# imap.authenticate('LOGIN', user, password)
# A Net::IMAP::NoResponseError is raised if authentication fails.
def authenticate(auth_type, *args)
auth_type = auth_type.upcase
unless @@authenticators.has_key?(auth_type)
format('unknown auth type - "%s"', auth_type)
authenticator = @@authenticators[auth_type].new(*args)
send_command("AUTHENTICATE", auth_type) do |resp|
if resp.instance_of?(ContinuationRequest)
data = authenticator.process(resp.data.text.unpack("m")[0])
# Sends a LOGIN command to identify the client and carries
# the plaintext +password+ authenticating this +user+. Note
# that, unlike calling #authenticate() with an +auth_type+
# of "LOGIN", #login() does *not* use the login authenticator.
# A Net::IMAP::NoResponseError is raised if authentication fails.
def login(user, password)
send_command("LOGIN", user, password)
# Sends a SELECT command to select a +mailbox+ so that messages
# in the +mailbox+ can be accessed.
# After you have selected a mailbox, you may retrieve the
# number of items in that mailbox from @responses["EXISTS"][-1],
# and the number of recent messages from @responses["RECENT"][-1].
# Note that these values can change if new messages arrive
# during a session; see #add_response_handler() for a way of
# A Net::IMAP::NoResponseError is raised if the mailbox does not
# exist or is for some reason non-selectable.
send_command("SELECT", mailbox)
# Sends a EXAMINE command to select a +mailbox+ so that messages
# in the +mailbox+ can be accessed. Behaves the same as #select(),
# except that the selected +mailbox+ is identified as read-only.
# A Net::IMAP::NoResponseError is raised if the mailbox does not
# exist or is for some reason non-examinable.
send_command("EXAMINE", mailbox)
# Sends a CREATE command to create a new +mailbox+.
# A Net::IMAP::NoResponseError is raised if a mailbox with that name
send_command("CREATE", mailbox)
# Sends a DELETE command to remove the +mailbox+.
# A Net::IMAP::NoResponseError is raised if a mailbox with that name
# cannot be deleted, either because it does not exist or because the
# client does not have permission to delete it.
send_command("DELETE", mailbox)
# Sends a RENAME command to change the name of the +mailbox+ to
# A Net::IMAP::NoResponseError is raised if a mailbox with the
# name +mailbox+ cannot be renamed to +newname+ for whatever
# reason; for instance, because +mailbox+ does not exist, or
# because there is already a mailbox with the name +newname+.
def rename(mailbox, newname)