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 才會不變

Function

  • namespace()
  • list()
  • select()
  • status()
  • store()
  • append()
  • copy()
  • fetch()

namespace()

IMAP4.namespace()

e.g.

# 每個 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.

e.g.

('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]])

e.g.

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)

command

  • "FLAGS"
  • "+FLAGS"
  • "-FLAGS"

e.g.

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

Notes

設置了 '\Deleted' 不等於移到垃圾筒

append() - 修改 mail

append()        # Append message to named mailbox

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

.copy()           #

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

e.g.

# 同時提取 UID 及 BODY[TEXT]

"(UID BODY[TEXT])"        # message_parts 是一個 tuple 來
  • UID
  • FLAGS
  • BODY[HEADER]
  • BODY[TEXT]
  • ...

e.g.

# Returned data are tuples of message part envelope and data

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

mailbox - create, rename, delete, expunge

create() - Create mailbox

# mailbox named "MyMail"

IMAP4.create(MyMail)

# SubFolder

M.create("namespace.FolderName")

rename() - Rename mailbox

IMAP4.rename(oldmailbox, newmailbox)

delete()

# Delete old mailbox named mailbox.

IMAP4.delete(mailbox)

expunge()

# Permanently remove deleted items from selected mailbox.

 * 在 imap 裡, mail 有 flag '\Deleted' 就代表要 Delete. 行 expunge() 後代表刪除它們.

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:

noop()

# 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()

typ, msgnums = IMAP4.search(charset, criterion[, ...])

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

 * When multiple criteria are specified => the result is the intersection AND

 * search 的 criterion 係無分大細階的 !!

Criterion 的 format

# Format 1
criterion = '(FROM "test")'

# Format 2
criterion = ('FROM', '"test"')

typ

  • OK - search completed
  • NO - search error
  • BAD - command unknown or arguments invalid

msgnums

    msgnums 係一個 list of byte object 來

[b'1 2']

    1 及 2 係 mail 的 ID

必須 select mailbox 後才可以 search

conn.select()
print conn.search(None, criterion)

Return

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

P.S.

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

mySubject = "test msg"
criterion = ("subject", mySubject)
conn.select()
typ, msgid = conn.search(None, criterion)

詳見: telnet_mail_service

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()

Time2Internaldate()

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

imaplib.Time2Internaldate(date_time)

 


 

 

 

 

 

Creative Commons license icon Creative Commons license icon