import poplib# email = input('email: ')
# password = input('password: ')
# pop3_server = input('pop3 server: ')
from email.parser import parser
from email.parser import parser
from email.header import decode_header
from email.utils import parseaddr
email = '[email protected]'
password = 'zt4662751'
pop3_server = 'imap.exmail.qq.com'
# 連線到pop3伺服器:
server = poplib.pop3(pop3_server)
# 可以開啟或關閉除錯資訊:
server.set_debuglevel(1)
# 可選:列印pop3伺服器的歡迎文字:
print(server.getwelcome().decode('utf-8'))
# 身份認證:
server.user(email)
server.pass_(password)
# stat()返回郵件數量和占用空間:
print('messages: %s. size: %s' % server.stat())
# list()返回所有郵件的編號:
resp, mails, octets = server.list()
# 可以檢視返回的列表類似[b'1 82923', b'2 2184', ...]
print(mails)
# 獲取最新一封郵件, 注意索引號從1開始:
index = len(mails)
print(index,'2222')
resp, lines, octets = server.retr(83)
# lines儲存了郵件的原始文字的每一行,
# 可以獲得整個郵件的原始文字:
msg_content = b'\r\n'.join(lines).decode('utf-8')
# 稍後解析出郵件:
msg = parser().parsestr(msg_content)
# print(msg)
messageobject = parser().parsestr(msg_content)
msgdate = messageobject["date"]
print(678,msgdate)
# 可以根據郵件索引號直接從伺服器刪除郵件:
# server.dele(index)
# 關閉連線:
# indent用於縮排顯示:
def print_info(msg, indent=0):
if indent == 0:
for header in ['from', 'to', 'subject']:
value = msg.get(header, '')
# print(123,value)
if value:
if header == 'subject':
value = decode_str(value)
# print(45678,value)
else:
# print(666666,value)
hdr, addr = parseaddr(value)
# print(1,hdr,2,addr)
name = decode_str(hdr)
# print(456789,name)
value = u'%s <%s>' % (name, addr)
print('%s%s: %s' % (' ' * indent, header, value))
if (msg.is_multipart()):
parts = msg.get_payload()
for n, part in enumerate(parts):
print('%spart %s' % (' ' * indent, n))
print('%s--------------------' % (' ' * indent))
print_info(part, indent + 1)
else:
content_type = msg.get_content_type()
if content_type == 'text/plain' or content_type == 'text/html':
content = msg.get_payload(decode=true)
charset = guess_charset(msg)
if charset:
content = content.decode(charset)
print('%stext: %s' % (' ' * indent, content + '...'))
else:
print('%sattachment: %s' % (' ' * indent, content_type))
def decode_str(s):
value, charset = decode_header(s)[0]
if charset:
value = value.decode(charset)
return value
def guess_charset(msg):
charset = msg.get_charset()
if charset is none:
content_type = msg.get('content-type', '').lower()
pos = content_type.find('charset=')
if pos >= 0:
charset = content_type[pos + 8:].strip()
return charset
print_info(msg = msg)
server.quit()
Python3實現郵件群發
1 在 mysql 資料庫建立 mail 資料庫,並建立 mail 表 2 將郵箱的電子郵件位址存在於mail 表中 3 編寫 python 程式 coding utf 8 import smtplib from email.mime.text import mimetext import time...
初識python3郵件傳送
前不久學習了一下python是如何傳送郵件到指定郵箱,python使用版本為python3.7。usr bin python3 匯入smtplib包,引用對應外掛程式 import smtplib from email.mime.text import mimetext from email.uti...
python3接收 解析郵件
python3可以使用poplib.pop3進行郵件接收,具體如下 import poplib from email.parser import parser def get email email,password,host mail.163.com connect to pop3 server ...