天天看點

python: smtp/pop/imap

郵件的伺服器MTA:smtp協定

郵件的用戶端MUA: pop3協定,imap協定。

###############################################

python使用smtplib子產品編寫郵件伺服器程式。

SMTP類:

__init__(self, host='', port=0, local_hostname=None, timeout=<object object>)

smtplib.SMTP類的方法:

connect(host='localhost', port=0)

sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]):

to_addrs是一個位址清單,msg的From: To: Subject:能自動識别

sendmail傳回沒有發出的郵件和錯誤資訊的字典{email,message}

quit()

################################################

python的郵件用戶端子產品有poplib和imaplib兩種

POP3類:

__init__(self, host, port=110, timeout=<object object>)

POP3類的方法:

user(username)

pass_(password)

stat()-> 擷取消息的數量和消息總大小,傳回(message count, mailbox size)

list(which=None) -> 

如果沒有給出which傳回,['response', ['mesg_num octets', ...], octets]

如果給出which隻傳回response

retr(which)-> 擷取which的伺服器傳回資訊、消息的所有行、消息的位元組,傳回['response', ['line', ...], octets]

dele(which) -> 删除which,傳回response

quit()

response:是一個字元串: +OK ...

['line', ...]:是一個清單,清單中‘’前面的是伺服器傳回的消息内容,後面的是郵件正文内容。

####################################################

#!/usr/bin/env python

from smtplib import SMTP

from poplib import POP3

from time import sleep

SMTPSVR = 'smtp.yourmail'

POP3SVR = 'pop3.yourmail'

#send to who

to_address = ['sendtowho']

#this will be  auto recognised

origHdrs = ['From: youremail',

            'To: sendtowho',

            'Subject: test']

#this is the real message you want to send

origBody = ['msgline1',

            'msgline2',

            'msgline3']

#the origHdrs and the origBody has a null line

origMsg = '\r\n\r\n'.join(['\r\n'.join(origHdrs),'\r\n'.join(origBody)])

#used for send mail with smtp

sendSvr = SMTP(SMTPSVR)

errs = sendSvr.sendmail('yourmail', to_address, origMsg)

sendSvr.quit()

assert len(errs) == 0, errs

#wait for the mail to come

sleep(10)

#used for recve mail with pop

recvSvr = POP3(POP3SVR)

recvSvr.user('yourname')

recvSvr.pass_('yourpassword')

rsp, msg, siz = recvSvr.retr(recvSvr.stat()[0])

sep = msg.index('')

recvBody = msg[sep+1:]

assert origBody == recvBody