Python uses imap to implement false "no trace" to retrieve messages

Source: Internet
Author: User
Tags imap old mailbox rfc822 search mailbox

The so-called "no trace" means that the mailbox status does not change after receiving emails from the mailbox. The status here mainly refers to two parts. One part is that the mail status remains unchanged, that is, the read and unread statuses remain unchanged, and the other part is that the login IP address of the mailbox record does not change. In this article, the false "no trace" refers to the first part of the implementation.

1. Imaplib

IMAP4.append (mailbox, flags, date_time, message): Append message to named mailbox.

Mechanism (mechanic, authobject): Authenticate command-requires response processing. Mechanic specifies which authentication mechanism is to be used-it shoshould appear in the instance variable capabilities in the form AUTH = mechanic.

IMAP4.check (): Checkpoint mailbox on server.

IMAP4.close (): Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before LOGOUT.

IMAP4.copy (message_set, new_mailbox): Copy message_set messages onto end of new_mailbox.

IMAP4.create (mailbox): Create new mailbox named mailbox.

IMAP4.delete (mailbox): Delete old mailbox named mailbox.

IMAP4.deleteacl (mailbox, who): Delete the ACLs (remove any rights) set for who on mailbox.

IMAP4.expunge (): Permanently remove deleted items from selected mailbox. Generates an EXPUNGE response for each deleted message. Returned data contains a list of EXPUNGE message numbers in order received.

IMAP4.fetch (message_set, message_parts): Fetch (parts of) messages. message_parts shocould be a string of message part names enclosed within parentheses, eg: "(uid body [TEXT])". returned data are tuples of message part envelope and data.

IMAP4.getacl (mailbox): Get the ACLs for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.getannotation (mailbox, entry, attribute): Retrieve the specified ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.getquota (root): Get the quota root's resource usage and limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4.getquotaroot (mailbox): Get the list of quota roots for the named mailbox. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4.list ([directory [, pattern]): List mailbox names in directory matching pattern. directory ults to the top-level mail folder, and pattern defaults to match anything. returned data contains a list of LIST responses.

IMAP4.login (user, password): Identify the client using a plaintext password. The password will be quoted.

IMAP4.login _ cram_md5 (user, password): Force use of CRAM-MD5 authentication when identifying the client to protect the password. Will only work if the server CAPABILITY response des the phrase AUTH = CRAM-MD5.

IMAP4.logout (): Shutdown connection to server. Returns server BYE response.

IMAP4.lsub ([directory [, pattern]): List subscribed mailbox names in directory matching pattern. directory ults to the top level directory and pattern defaults to match any mailbox. returned data are tuples of message part envelope and data.

IMAP4.myrights (mailbox): Show my ACLs for a mailbox (I. e. the rights that I have on mailbox ).

IMAP4.namespace (): Returns IMAP namespaces as defined in RFC2342.

IMAP4.noop (): Send NOOP to server.

IMAP4.open (host, port): Opens socket to port at host. this method is implicitly called by the IMAP4 constructor. the connection objects established by this method will be used in the read, readline, send, and shutdown methods. you may override this method.

IMAP4.partial (message_num, message_part, start, length): Fetch truncated part of a message. Returned data is a tuple of message part envelope and data.

IMAP4.proxyauth (user): Assume authentication as user. Allows an authorised administrator to proxy into any user's mailbox.

IMAP4.read (size): Reads size bytes from the remote server. You may override this method.

IMAP4.readline (): Reads one line from the remote server. You may override this method.

IMAP4.recent (): Prompt server for an update. Returned data is None if no new messages, else value of RECENT response.

IMAP4.rename (oldmailbox, newmailbox): Rename mailbox named oldmailbox to newmailbox.

IMAP4.response (code): Return data for response code if already ed, or None. Returns the given code, instead of the usual type.

IMAP4.search (charset, criterion [,...]): Search mailbox for matching messages. charset may be None, in which case no CHARSET will be specified in the request to the server. the IMAP protocol requires that at least one criterion be specified; an exception will be raised when the server returns an error.

IMAP4.send (data): Sends data to the remote server. You may override this method.

IMAP4.setacl (mailbox, who, what): Set an ACL for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.setannotation (mailbox, entry, attribute [,...]): Set ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.setquota (root, limits): Set the quota root's resource limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4.shutdown (): Close connection established in open. This method is implicitly called by IMAP4.logout (). You may override this method.

IMAP4.socket (): Returns socket instance used to connect to server.

IMAP4.sort (sort_criteria, charset, search_criterion [,...]): The sort command is a variant of search with sorting semantics for the results. returned data contains a space separated list of matching message numbers.

IMAP4.status (mailbox, names): Request named status conditions for mailbox.

IMAP4.store (message_set, command, flag_list): Alters flag dispositions for messages in mailbox. command is specified by section 6.4.6 of RFC 2060 as being one of "FLAGS", "+ FLAGS", or "-FLAGS", optionally with a suffix ". SILENT ".

IMAP4.thread (threading_algorithm, charset, search_criterion [,...]): The thread command is a variant of search with threading semantics for the results. returned data contains a space separated list of thread members.

IMAP4.uid (command, arg [,...]): Execute command args with messages identified by UID, rather than message number. returns response appropriate to command. at least one argument must be supplied; if none are provided, the server will return an error and an exception will be raised.

IMAP4.unsubscribe (mailbox): Unsubscribe from old mailbox.

IMAP4.xatom (name [, arg [,...]): Allow simple extension commands notified by server in CAPABILITY response.

IMAP4_SSL.ssl (): Returns SSLObject instance used for the secure connection with the server.

IMAP4.PROTOCOL _ VERSION: The most recent supported protocol in the CAPABILITY response from the server.

IMAP4.debug: Integer value to control debugging output. The initialize value is taken from the module variable Debug. Values greater than three trace each command.

2. imap commands

CREATE <folder>: CREATE can CREATE a new mailbox with the specified name. The mailbox name is usually the full name of the folder with a path. (Some IMAP clients use a folder to name a new mailbox)
C: A003 CREATE owatagusiam // * CREATE a new directory owatagusiam */
S: A003 OK CREATE completed
C: A004 CREATE owatagusiam/blurdybloop
/* CREATE a mailbox named blurdybloop under the Created directory owatagusiam. Of course, you can omit the first step. A004 CREATE owatagusiam/blurdybloop, indicates that a mailbox named blurdybloop is created under the new directory owatagusiam */
S: A004 OK CREATE completed

DELETE <folder>: DELETE command to DELETE the folder with the specified name. The folder name is usually the full name of the folder with a path. After the mailbox is deleted, emails in the folder no longer exist.
C: A683 DELETE blurdybloop
S: A683 OK DELETE completed
C: A684 DELETE foo
S: A684 NO Name "foo" has inferior hierarchical names
C: A685 DELETE foo/bar
S: A685 OK DELETE Completed

RENAME <old folder> <new folder>: the RENAME command can modify the folder name. It uses two parameters: the current mailbox name and the new mailbox name. The names of the two parameters comply with the standard path naming rules.
C: A683 RENAME blurdybloop sarasoop
S: A683 OK RENAME completed
C: A684 RENAME stuff/junk newbox/* RENAME the mailbox junk under the stuff directory (folder) to newbox */
S: A684 OK RENAME Completed

LIST <BASE> <template>: the list command is used to LIST the existing folders in the mailbox. It is a bit like the column directory command of the operating system. There are two parameters, mail path parameter BASE: indicates the user's login directory. The second parameter "template" indicates the name of the mailbox to be displayed. This command can contain the starting path and the characteristics of the folder to be listed. You can use the wildcard "*".
C: A101 LIST """"
S: * LIST (\ Noselect )"/"""
S: A101 OK LIST Completed
C: A102 LIST # news. comp. mail. misc ""
S: * LIST (\ Noselect) "." # news.
S: A102 OK LIST Completed
C: A103 LIST/usr/staff/jones ""
S: * LIST (\ Noselect )"/"/
S: A103 OK LIST Completed
C: A202 LIST ~ /Mail/%
S: * LIST (\ Noselect )"/"~ /Mail/foo
S: * LIST ()"/"~ /Mail/meetings
S: A202 OK LIST completed

APPEND <folder> <attributes> <date/time> <size> <mail data>: The APPEND command allows the Client to upload an email to the specified Folder (folder/mailbox. The command contains the attributes, date/time, and size of the new mail, followed by the mail data.
C: A003 APPEND saved-messages (\ Seen) {310}
C: Date: Mon, 7 Feb 1994 21:52:25-0800 (PST)
C: From: Fred Foobar <foobar@Blurdybloop.COM>
C: Subject: afternoon meeting
C: To: mooch@owatagu.siam.edu
C: Message-Id: <B27397-0100000@Blurdybloop.COM>
C: MIME-Version: 1.0
C: Content-Type: TEXT/PLAIN; charsets = US-ASCII
C:
C: Hello Joe, do you think we can meet at :30 tomorrow?
C:
S: A003 OK APPEND completed

SELECT <folder>: The SELECT command allows the Client to SELECT a mailbox (Folder), which indicates that the mail in the mailbox (Folder) will be operated. The current status of the email mark is also returned to the user, and some additional information about the email and email is returned.
C: A142 SELECT INBOX
S: * 172 EXISTS
S: * 1 RECENT
S: * OK [UNSEEN 12] Message 12 is first unseen
S: * OK [UIDVALIDITY 3857529045] UIDs valid
S: * FLAGS (\ Answered \ Flagged \ Deleted \ Seen \ Draft)
S: * OK [PERMANENTFLAGS (\ Deleted \ Seen \ *)] Limited
S: A142 OK [READ-WRITE] SELECT completed

FETCH <mail id> <datanames>: The FETCH command is used to read the text information of an email and is only used for display purposes. Contains two parameters: messageset: the list of mail numbers to be read. Each mail in the IAMP server mailbox has a unique ID. (The Mail number list parameter can be a mail number, it can also be multiple mail numbers separated by commas, or a range separated by colons). The IMAP server returns the specified data items of all emails in the mail number list.
The data name parameter determines a part of the email that can be returned independently. Let's take a look at the message returned by each parameter:
ALL: returns only the email abstract in a specified format, including the email mark, RFC822.SIZE, time, and envelope information. The IMAP client can parse the standard mail into this information and display it.
BODY: only the abstract information of the BODY text format and size is returned. The IMAP client can identify these details and display detailed information about emails to users. It is actually some non-extended BODYSTRUCTURE information.
FAST: returns only some of the mail summaries, including the mail mark, RFC822.SIZE, and time.
FULL: The same summary information, including the mail mark, RFC822.SIZE, time, and BODYSTRUCTURE information.
BODYSTRUCTUR: The Body Structure of the [MIME-IMB] of the mail. This is what the server gets by parsing the [RFC-2822] fields in the [MIME-IMB] header and the [MIME-IMB] header information. Including the mail body type, Character Set, encoding method, and other types, character sets, encoding methods, and file names of each attachment.
ENVELOPE: the ENVELOPE Structure of the information. Is the server by parsing the [RFC-2822] in the [MIME-IMB] header of each field out, by default each field is required. It mainly includes the time, number of attachments, recipients, and senders.
FLAGS: The identifier of the email.
INTERNALDATE: its own time.
RFC822.SIZE: [RFC-2822] size of the mail
RFC822.HEADER: The function is equivalent to BODY. PEEK [HEADER].
RFC822: similar to BODY [].
RFC822.TEXT: similar to BODY [TEXT].
UID: return the UID of the email. The UID is a unique number that identifies the email.
BODY [section] <partial>: return a specified part of the email. The returned part is represented by section, the section usually contains a number or a part of the following: HEADER, HEADER. FIELDS, HEADER. FIELDS. NOT, MIME, and TEXT. If the section is empty, all information, including header information, is returned.
BODY [HEADER] returns the complete file HEADER information.
BODY [HEADER. FIELDS ()]: You can specify the returned field in parentheses.
BODY [HEADER. FIELDS. NOT ()]: in parentheses, you can specify specific FIELDS that do NOT need to be returned.
BODY [MIME]: returns the HEADER information for the [MIME-IMB] of the message, which is normally the same as BODY [HEADER.
BODY [TEXT]: returns the entire BODY. The BODY does not include the header.

STORE <mail id> <new attributes>: The STORE command is used to modify the attributes of a specified email, including marking the read and delete emails. The STORE Command currently only has two data item types available. FLAGS: indicates a group of emails; FLAGS. SLIENT indicates a group of mail signs. You can add a plus or minus sign before two data items to further change their execution. the plus sign indicates that the value of the data item is added to the mail, minus sign indicates that the value of the data item is deleted from the email.
C: A003 STORE + FLAGS (\ Deleted)/* colon indicates a range of intervals: Set the Deleted attribute for emails from 2 to 4 */
S: * 2 fetch flags (\ Deleted \ Seen)
S: * 3 fetch flags (\ Deleted)
S: * 4 fetch flags (\ Deleted \ Flagged \ Seen)
S: A003 OK STORE completed
The command can also be used to mark an email as unread. You can perform operations on emails on the web in imap.

CLOSE: the CLOSE command indicates that the Client ends access to the current Folder (Folder/mailbox), and all emails marked as and DELETED in the mailbox are physically DELETED. CLOSE has no command parameter. You can then SELECT another Folder.
C: A341 CLOSE
S: A341 OK CLOSE completed


EXPUNGE: The EXPUNGE command deletes all emails marked as "DELETED" without shutting down the mailbox. Emails deleted by EXPUNGE cannot be restored.
C: A202 EXPUNGE
S: * 3 EXPUNGE
S: * 3 EXPUNGE
S: * 5 EXPUNGE
S: * 8 EXPUNGE
S: A202 OK EXPUNGE completed

LOGOUT: The LOGOUT command ends this IMAP session.
C: A023 LOGOUT
S: * BYE IMAP4rev1 Server logging out
S: A023 OK LOGOUT completed
(Server and client then close the connection)

EXAMINE <mailbox>:
The EXAMINE command opens a mailbox in read-only mode. The parameter is the name of the mailbox to be opened. The email opened using the EXAMINE command cannot be changed. Therefore, you cannot add or delete the email flag.

SUBSCRIBE <mailbox>: the SUBSCRIBE command is used to add a mailbox to the active mailbox list of the client. This command has only one parameter and you want to add the mailbox name.
C: A114 SUBSCRIBE new/anotherbox
S: A114 OK SUBSCRIBE completed

UNSUBSCRIBE <mailbox>: The UNSUBSCRIBE command is used to remove a mailbox from the activity list. One parameter is the name of the mailbox to be removed.
C: A115 UNSUBSCRIBE new/anotherbox
S: A115 OK SUBSCRIBE completed

LSUB <folder> <mailbox>: the LSUB command fixes the LIST command. The LIST command returns all the files in the $ HOME directory of the user, however, the LSUB command only displays the files that use the SUBSCRIBE command to set as the active mailbox. Two parameters: Mailbox path and mailbox name.
C: A116 LSUB "" *
S: * LSUB () "/" stuff/junk
S: * LSUB () "/" neebox
S: * LSUB () "/" new/anotherbox
S: A116 OK LSUB completed

STATUS <mailbox> (<parameter1> <parameter2> ...... <Parameter5>): the status Command queries the current STATUS of the mailbox. The first parameter is the mailbox name to be queried, and the second parameter is the project list (the information to be queried) to be queried by the client, which is in parentheses. STATUS can be obtained without the SELECT command (Open email) or EXAMINE (Open email in read-only mode.
Data items that can be obtained by the STATUS command
Description
Total number of emails in the MESSAGE mailbox
Number of emails marked as \ RECENT in the RECENT mailbox
UIDNEXT can be assigned to the next uid of the new email.
UIDVALIDITY indicates the UID validity of the email address.
Number of UNSEEN emails not marked as \ UNSEEN
C: A117 STATUS inbox (message recent unseen)
S: * STATUS inbox (MESSAGE 1 RECENT 0 UNSENN 0)
S: A117 OK STATUS completed
C: A118 STATUS newbox (message recent unseen)
S: * STATUS inbox (MESSAGE 1 RECENT 0 UNSENN 2)
S: A118 OK STATUS completed

CHECK: The CHECK command is used to set a checkpoint in the mailbox. No parameter. Is the sync command in IMAP. Any unfinished operations, such as writing data from the server memory to the hard disk, will be completed to maintain the consistency of the mailbox. This command ensures that the disk buffer data in naemun is written to the disk.

SEARCH [CHARSET specification] (search criteria): You can SEARCH for emails in an active mailbox Based on search criteria, and then display the matching email number. Character Set flag parameter [CHARSET specification] consists of CHARSET and registered character set identifier, the default identifier is US-ASC Ⅱ, so the length of this parameter is omitted. Search criteria: A Query condition parameter that specifies the keywords and values of a query. There are dozens of query keywords.
C: A119 SEARCH header subject another
S: SEARCH 1 2
S: * A119 OK SEARCH completed
C: A120 SEARCH header subject another
S: * SEARCH 2
S: A120 OK SEARCH completed
C: A121 SEARCH UNSEEN
S: * SEARCH 1 2
S: A120 OK SEARCH completed
In each of the preceding examples, a different word is queried in the Subject: Field of the mail header. The server returns the list of condition email numbers. If no matching email is found, the SEARCH word without UID is returned.

COPY <mail id> <mailboxname>: The COPY command can COPY an email from one mailbox to another. Two parameters: mail id is the number of the email to be copied from the active mailbox, mailboxname is the email address to which you want the email to be copied.
The IAMP command does not define the mobile mail. The mobile operation is equivalent to copying the mail to the new mailbox first, and then setting the \ DELETED mark for the mail in the source mailbox. After the next checkpoint is executed, the emails in the new mailbox are deleted and displayed.

UID: The UID command is used together with the FETCH, COPY, STORE, or SEARCH commands. It allows these commands to use the UID of the email instead of the sequential number in the mailbox. The UID is the 32-bit certificate that uniquely identifies the email in the mail system. Generally, these commands use sequential numbers to identify emails in the mailbox. Using UID can enable the IMAP client to remember emails in different IMAP sessions.

CAPABILITY: The CAPABILITY command request returns the list of functions supported by the IMAP server. After receiving the CAPABILITY Command sent by the client, the server returns the functions supported by the server. No parameter.
C: A122 CAPABILITY
S: * A122 CAPABILITY IMAP4 IMAP4REVl NAMESPACE IDLE SCAN SORT MAILBOX
-- REFERRALS [ic: ccc] LOGIN-REFERRALS AUTH = login thread =
ORDERDSUBJECT
S: A122 OK CAPABILITY completed

NOOP: The NOOP command does nothing. It is used to send automatic commands to the server to prevent connection interruption caused by long periods of inactivity. The server's response to this command is always positive. No parameter.

LOGOUT: The LOGOUT command causes the current login user to log out and close all opened mailboxes. All emails with the \ DELETED mark will be DELETED at this time.


To ensure that the mail status does not change, the key lies in the fetch parameter. If we only read the BODY. PEEK [HEADER] of the mail HEADER, the mail status will not change. If you want to read all the mail content, you must use BODY. PEEK [] to ensure that it does not change. Example:

= imaplib.IMAP4_SSL(,=,)              %== M.search(None,  num = M.fetch(num, = email.message_from_string(data[0][1=t+1=str(t)+=open(filename,  %   %

Some abstractions mentioned above, typ, data = M. fetch (num, '(uid body. PEEK []) ') in this sentence, you can try to replace the uid body. PEEK [HEADER], uid body [], RFC822, RFC822.HEADER, and so on will be more intuitive. Here we will not explain them one by one.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.