Python3 pop3取件
困難點(diǎn)
部分郵箱提示密碼錯(cuò)誤
-ERR Unable to log on
反饋密碼錯(cuò)誤,但實(shí)際上密碼是正確的檩互,該種情況盯捌,需要使用授權(quán)碼一也,而非密碼
目前已知需要授權(quán)碼的郵箱列表
- 騰訊 @qq.com
- 網(wǎng)易 @163.com
Date時(shí)間解析
查詢相關(guān)資料赖舟,得知可使用email.utils針對(duì)郵箱的時(shí)間格式進(jìn)行解析
Date: Sat, 15 Jan 2022 14:08:55 +0800
from email.utils import parsedate
import time
date="Sat, 15 Jan 2022 14:08:55 +0800"
print(time.strftime("%Y-%m-%d %H:%M:%S", parsedate(date)))
163郵箱在長(zhǎng)時(shí)間運(yùn)行后報(bào)錯(cuò)
報(bào)錯(cuò)內(nèi)容
-ERR \xc4\xfa\xb5\xc4\xd5\xca\xba\xc5\xd4\xdd\xca\xb1\xb2\xbb\xbf\xc9\xd3\xc3.\xbf\xc9\xc4\xdc\xb5\xc4\xd4\xad\xd2\xf2\xca\xc7:\xc4\xfa\xb5\xc4\xd5\xca\xba\xc5\xb6\xe0\xb4\xce\xb3\xa2\xca\xd4\xb4\xed\xce\xf3\xb5\xc4\xc3\xdc\xc2\xeb,\xb3\xf6\xd3\xda\xb0\xb2\xc8\xab\xbf\xbc\xc2\xc7,\xce\xd2\xc3\xc7\xc1\xd9\xca\xb1\xcf\xde\xd6\xc6\xc1\xcb\xc4\xfa\xb5\xc4\xd5\xca\xba\xc5\xb5\xc4pop\xb7\xc3\xce\xca\xc8\xa8\xcf\xde
嘗試復(fù)現(xiàn):
- 長(zhǎng)時(shí)間運(yùn)行出現(xiàn)
- 在停止運(yùn)行半小時(shí)后恢復(fù)
通過(guò)以上觀測(cè)得知蓬戚,可猜測(cè)為頻繁請(qǐng)求導(dǎo)致【取件間隔5秒】,延長(zhǎng)后可解決
完整代碼
import poplib,quopri,requests,json,re,time
from email.header import decode_header
from email.utils import parseaddr
from email.parser import Parser
from email.utils import parsedate
from urllib.parse import urlencode
def get_info(msg):
value = {}
i = 0
for header in ['From', 'To', 'Subject','Date']: # 解析郵件頭
value[i] = msg.get(header, '')
if value[i]:
if header == 'Subject': # 解析主題
value[i] = decode_str(value[i])
elif header=='Date':
value[i] = time.strftime("%Y-%m-%d %H:%M:%S", parsedate(value[i]))
else:
hdr, addr = parseaddr(value[i])
value[i] = addr
i = i + 1
return value
def decode_str(s):
value, charset = decode_header(s)[0]
if charset:
value = value.decode(charset)
return value
def get_content(msg,pop3_server):
content = msg.get_payload()
if pop3_server == 'pop.163.com':
decoded_string = quopri.decodestring(content[0].get_payload())
return decoded_string.decode('utf-8')
decoded_string = quopri.decodestring(content)
return decoded_string.decode('utf-8')
def parsing(msg,pop3_server):
#獲取郵箱來(lái)源 0發(fā)件人 1收件人 2主題 3收信時(shí)間
email_info=get_info(msg)
print('獲取到新郵件:{} 來(lái)源:{} 收件人:{}'.format(email_info[2],email_info[0],email_info[1]))
if email_info[0] not in ['AccountSupport@ubi.com','noreply@steampowered.com']:
return False
#郵箱內(nèi)容
email_content = get_content(msg,pop3_server)
return email_content
if __name__=='__main__':
server = poplib.POP3_SSL('pop.163.com')
server.set_debuglevel(0)
server.user('xxx@163.com')
server.pass_('password 授權(quán)碼')
resp, mails, octets = server.list()
#郵件數(shù)量
email_count=len(mails)
#取最新一封
resp, lines, octets = server.retr(email_count)
msg_content = b'\r\n'.join(lines).decode('gbk')
lists = []
for e in lines:
lists.append(e.decode('gbk'))
msg_content = '\r\n'.join(lists)
msg = Parser().parsestr(msg_content)
result=parsing(msg,temp[2])
print('獲取結(jié)果:',result)