class - poplib 與 imaplib (mail相關)

最後更新: 2018-01-31

介紹

 


getpass

 

#!/usr/bin/env python

import getpass

myuser = getpass.getuser()

 

 


poplib

 

  • class poplib.POP3_SSL(host[, port[, keyfile[, certfile]]])         # Port 995

Example - getpass

#!/usr/bin/env python

import getpass, poplib

myuser = getpass.getuser()
mypass = getpass.getpass()

try:
    # Mailbox = poplib.POP3(host[, port[, timeout]])       # no encryption
    Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995') # POP3-over-SSL. Default port: 995

    # Login
    Mailbox.user(myuser)
    Mailbox.pass_(mypass)  # 必須要有 "_" 的

    # Output: (numMsgs, totalSize)
    # (2, 4292)
    print Mailbox.stat()

    # ('+OK 2 messages:', ['1 2147', '2 2145'], 16)
    print Mailbox.list()

    # Return: (response, ['mesg_num octets',...], octets)
    (server_msg, body, octets) = Mailbox.retr(1)

    # commit changes, unlock mailbox, drop connection
    Mailbox.quit()

except poplib.error_proto as e:
    print(email+":fail")
    print(e)

Other

# Do nothing. Might be used as a keep-alive.
POP3.noop()

# Return message digest (unique id) list
POP3.uidl([which])

# Retrieves the message header plus howmuch lines of the message after the header
POP3.top(which, howmuch)

# Flag message number which for deletion.
# On most servers deletions are not actually performed until QUIT
POP3.dele(which)

# Remove any deletion marks for the mailbox.
POP3.rset()

 

Doc

https://docs.python.org/2/library/poplib.html

 


imaplib

 

此 imaplib 內一共有 3 client classes (IMAP4 Objects)

  • IMAP4
  • IMAP4_SSL                        # Port 993
  • IMAP4_stream ( standard input and standard output of an external command )

Example:

- imaplib.IMAP(host).login(user, pass).logout

- imaplib.IMAP.error

#!/usr/bin/env python

import imaplib

def open_conn(host, user, pw):
    # 設定 port: imaplib.IMAP4([host[, port]])
    # 行 SSL: imaplib.IMAP4_SSL(host)
    conn = imaplib.IMAP4(host)
    conn.login(user, pw)
    return conn

if __name__ == '__main__':
    host="xxx"
    user="yyy"
    pw="zzz"
    try:
        c = open_conn(host, user, pw)
        # Login success 的話會見到 <imaplib.IMAP4 instance at 0x0000000002400AC8>
        print c
        c.logout()
    except imaplib.IMAP4.error as e:
        # 當 login 唔成功, 那會有 exception, e.messagre="Login failed."
        print e.message

imap object

Each command returns a tuple: (type, [data, ...])

- a simple message number ('1')
- a range of message numbers ('2:4')
- asterisk to indicate an infinite upper bound ('3:*')

* IMAP4 message numbers change as the mailbox changes
* UID 才會不變

namespace

IMAP4.namespace()

i.e.

    # 每個 mailbox 都是 "INBOX.?????" 這格式

('OK', ['(("INBOX." ".")) NIL (("#shared." ".")("shared." "."))'])

    # Dovect 的 namespace

('OK', ['(("" "/")) (("Shared/" "/")) NIL'])

list

IMAP4.list([directory[, pattern]])

# List mailbox names in directory matching pattern.
# directory defaults to the top-level mail folder, and
# pattern defaults to match anything.

i.e.

('OK', ['(\\HasNoChildren) "." "INBOX.Sent"', '(\\HasNoChildren) "." "INBOX.Drafts"', ...])

select

  • Select a mailbox.
  • Returned data is the count of messages in mailbox (EXISTS response).
  • The default mailbox is 'INBOX'
  • If the readonly flag is set, modifications to the mailbox are not allowed.

IMAP4.select([mailbox[, readonly]])

i.e.

M.select("INBOX")

# INBOX 內有兩個 mail

('OK', ['2'])

status

# Request named status conditions for mailbox

IMAP4.status(mailbox, names)

  • MESSAGES - The number of messages in the mailbox
  • RECENT - The number of messages with the Recent flag set
  • UIDNEXT - The next unique identifier value of the mailbox
  • UIDVALIDITY -  The unique identifier validity value of the mailbox
  • UNSEEN - The number of messages which do not have the Seen flag set

ie.

M.status("INBOX","(MESSAGES UNSEEN)")

result:

('OK', ['"INBOX" (MESSAGES 1216 UNSEEN 1216)'])

store - 修改 mail 的 flag

IMAP4.store(message_set, command, flag_list)

i.e.

M.store(num, '+FLAGS', '\\Deleted')
M.expunge()

Notes

delete 與垃圾筒無關

修改 mail

# Append message to named mailbox

IMAP4.append(mailbox, flags, date_time, message)

Convert date_time to an IMAP4 INTERNALDATE representation.
("DD-Mmm-YYYY HH:MM:SS +HHMM")

imaplib.Time2Internaldate(date_time)

IMAP4.copy(message_set, new_mailbox)

Copy message_set messages onto end of new_mailbox.

fetch - 讀取 mail

Fetch (parts of) messages.

IMAP4.fetch(N, message_parts)

message_parts should be a string of message part names enclosed within parentheses

eg: "(UID BODY[TEXT])"        # message_parts 是一個 tuple 來

- UID
- FLAGS
- BODY[HEADER]
- BODY[TEXT]
- msg[header]

ie.

# Returned data are tuples of message part envelope and data

typ, msg_data = M.fetch('1', '(UID BODY[header])')

mailbox

Create mailbox

# mailbox named "MyMail"

IMAP4.create(MyMail)

# SubFolder

M.create("namespace.FolderName")

Delete mailbox

IMAP4.delete(mailbox)

Rename mailbox

IMAP4.rename(oldmailbox, newmailbox)

Permanently remove deleted items from selected mailbox

IMAP4.expunge()

delete

# Delete old mailbox named mailbox.

IMAP4.delete(mailbox)

# Permanently remove deleted items from selected mailbox.

IMAP4.expunge() 

quota

IMAP4.getquotaroot(mailbox)         # Get the list of quota roots for the named mailbox.

IMAP4.getquota(root)                    # Get the quota root‘s resource usage and limits.

subscribe

# List subscribed mailbox names in directory matching pattern.
IMAP4.lsub([directory[, pattern]])

# Subscribe to new mailbox.
IMAP4.subscribe(mailbox)

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

Uploading Messages

import email.message

new_message = email.message.Message()
new_message.set_unixfrom('pymotw')
new_message['Subject'] = 'subject goes here'
new_message['From'] = '[email protected]'
new_message['To'] = '[email protected]'
new_message.set_payload('This is the body of the message.\n')

print new_message

Other:

# Send NOOP to server

IMAP4.noop()

# recent

# Prompt server for an update.

# Returned data is None if no new messages, else value of RECENT response.

IMAP4.recent()

# 未 select mailbox 時, 會出 "[None]", 選了的話, 出數字

('OK', [None])

Search

IMAP4.search(charset, criterion[, ...])

 * charset may be None, in which case no CHARSET will be specified in the request to the server.

 * search 的條件係無分大細階

criterion = "(from " + config["myfrom"] + ")"
conn.select()                 # 必須 select mailbox 後才可以 search
print conn.search(None, criterion)

return

('OK', ['1 2'])       # ID 1, 2 呢兩個 mail 中 criterion
('OK', [''])          # 沒有 mail 中 criterion

P.S.

# 當 subject 有空格時, 必須用 " 包它

sub = "test msg"
criterion = ['(subject "' + sub + '")']
conn.select()
_, msgid = conn.search(None, " ".join(criterion))

# Checkpoint mailbox on server.

# Only allowed in states SELECTED

# command CHECK illegal in state AUTH, only allowed in states SELECTED

IMAP4.select()       # ('OK', ['3'])
IMAP4.check()        # ('OK', ['Check completed.'])

# close

# Close currently selected mailbox.

# This is the recommended command before LOGOUT.

IMAP4.close()

DOC

https://docs.python.org/2/library/imaplib.html

 


 

 

 

 

 

Creative Commons license icon Creative Commons license icon