Python 之 pop 获取邮件和附件
有些库可能用不上的,大家自行判断吧
import re
import module.UpExcel as moduleExcel
import os
from email.utils import parseaddr, parsedate, getaddresses
from email.header import decode_header, Header
from email.parser import Parser
import xlwings as xw
import time
import email
import datetime
import poplib
import pandas as pd
poplib._MAXLINE = 20480
email_address = '****@263.com'
email_password = 'password'
def recv_email_by_pop3(email_address, email_password,interval_day):
pop_server_host = "pop.263.net"
pop_server_port = 110
try:
email_server = poplib.POP3(host=pop_server_host, timeout=30, port=pop_server_port)
except:
print("pop3----sorry the given email server address connect time out")
exit(1)
try:
email_server.user(email_address)
except:
print("pop3----sorry the given email address seem do not exist")
exit(1)
try:
email_server.pass_(email_password)
except:
print("pop3----sorry the given username seem do not correct")
exit(1)
email_count = len(email_server.list()[1])
resp, mails, octets = email_server.list()
for i in range(len(mails), 0, -1):
resp, lines, octets = email_server.retr(i)
email_content = b'\r\n'.join(lines)
try:
email_content = email_content.decode('utf-8')
except Exception as e:
print(str(e))
continue
msg = Parser().parsestr(email_content)
print('------------- 分隔符 ---------------')
list = []
list = parse_email(list, msg, 0, interval_day)
nowTime = (datetime.datetime.now()+datetime.timedelta(days=interval_day)
).strftime("%Y-%m-%d") + ' 00:00:00'
if list[0] < nowTime:
email_server.close()
return
if len(list) > 2:
riqi = str(time.strftime("%Y-%m-%d", time.localtime()))
filename = r'D:\AutoEmail\Get\Get' + riqi + '.xlsx'
app = xw.App(visible=False, add_book=False)
wb = app.books.open(filename)
sht = wb.sheets[0]
info = sht.used_range
nrows = info.last_cell.row
sht.range('A'+str(nrows+1)).value = [list]
info.column_width = 40
sht.range('A1:A'+str(nrows+1)).column_width = 16
wb.save(filename)
wb.close()
app.kill()
email_server.close()
def get_att(msg):
attachment_files = []
for part in msg.walk():
file_name = part.get_filename()
contentType = part.get_content_type()
mycode = part.get_content_charset()
if file_name:
h = Header(file_name)
dh = decode_header(h)
filename = dh[0][0]
if dh[0][1]:
filename = decode_str(str(filename, dh[0][1]))
attachment_files.append(filename)
data = part.get_payload(decode=True)
with open(filename, 'wb') as f:
f.write(data)
print(f'附件 {filename} 已下载完成')
elif contentType == 'text/plain':
data = part.get_payload(decode=True)
content = data.decode(mycode)
print('正文:', content)
print('附件文件名列表', attachment_files)
def parse_email(list, msg, indent,interval_day):
if indent == 0:
for header in ['Date', 'From', 'To', 'CC', 'Subject']:
value = msg.get(header, '')
if header == 'Date':
strDate = time.strftime("%Y-%m-%d %H:%M:%S", parsedate(value))
nowTime = (datetime.datetime.now(
)+datetime.timedelta(days=interval_day)).strftime("%Y-%m-%d") + ' 00:00:00'
list.append(strDate)
if strDate[:10] < nowTime:
print('%s%s: %s' % (' ' * indent, header, strDate))
return list
print('%s%s: %s' % (' ' * indent, header, strDate))
elif header == 'From':
hdr, addr = parseaddr(value)
strFrom = u'<%s>' % (addr)
list.append(strFrom)
print('%s%s: %s' % (' ' * indent, header, strFrom))
elif header == 'To':
listTo = []
tos = msg.get_all('to', [])
for to in getaddresses(tos):
to = to[0] + ' <' + to[1] + '>'
hdr, addr = parseaddr(to)
name = decode_str(hdr)
strTo = u'<%s>' % (addr)
listTo.append(strTo)
strlistto = ''.join(listTo)
list.append(strlistto)
print('%s%s: %s' % (' ' * indent, header, strlistto))
elif header == 'CC':
listCc = []
ccs = msg.get_all('cc', [])
for cc in getaddresses(ccs):
cc = cc[0] + ' <' + cc[1] + '>'
hdr, addr = parseaddr(cc)
name = decode_str(hdr)
strCc = u'<%s>' % (addr)
listCc.append(strCc)
strlistCc = ''.join(listCc)
if strlistCc == '':
strlistCc = '空'
list.append(strlistCc)
print('%s%s: %s' % (' ' * indent, header, strlistCc))
elif header == 'Subject':
strSubject = decode_str(value)
list.append(strSubject)
print('%s%s: %s' % (' ' * indent, header, strSubject))
if (msg.is_multipart()):
parts = msg.get_payload()
for n, part in enumerate(parts):
parse_email(list, part, indent + 1,interval_day)
return list
else:
for part in msg.walk():
content_type = msg.get_content_type()
file_name = part.get_filename()
if content_type == 'text/plain' or content_type == 'text/html':
if len(list) < 6:
content = msg.get_payload(decode=True)
charset = guess_charset(msg)
if charset:
try:
content = content.decode(charset)
except:
content = content.decode("gb2312", errors='ignore')
print('%sText: %s' % (' ' * indent, content))
list.append('text:' + content.replace(' ',
'').replace('\n', '').replace('\r', '')[:300])
if file_name:
h = email.header.Header(file_name)
dh = email.header.decode_header(h)
filename = dh[0][0]
if dh[0][1]:
filename = decode_str(str(filename, dh[0][1]))
data = part.get_payload(decode=True)
riqi = str(time.strftime("%Y-%m-%d", time.localtime()))
attfileadd = 'D:\\AutoEmail\\Att\\Get\\'+riqi
if not os.access(attfileadd, os.X_OK):
os.mkdir('D:\\AutoEmail\\Att\\Get\\' + './'+riqi+'')
with open(attfileadd + '\\' + filename, 'wb') as f:
f.write(data)
print('%sAtt: %s' % (' ' * indent, filename))
list.append(filename)
return list
def decode_str(s):
value, charset = decode_header(s)[0]
try:
value = value.decode(charset)
except:
try:
value = value.decode("gb2312", errors='ignore')
except:
pass
return value
def guess_charset(msg):
try:
charset = msg.get_charset()
if charset is None:
content_type = msg.get('Content-Type', '').lower()
for item in content_type.split(';'):
item = item.strip()
if item.startswith('charset'):
charset = item.split('=')[1]
break
return charset
except:
pass
smtplib 发送邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
import os
import pandas as pd
import datetime
import tkinter.messagebox
import traceback
import xlwings as xw
def wain_send_mail(mail_user,mail_pass,sub, content, files, path):
mailto_list = ['']
mail_host = "smtp.263.net"
Cc_list = ['抄送人员列表']
me = "<" + mail_user + ">"
msg = MIMEMultipart()
msg.attach(MIMEText(content, _subtype='html', _charset='utf-8'))
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ",".join(mailto_list)
msg['Cc'] = ",".join(Cc_list)
for file in files:
if os.path.isfile(path + '/' + file):
att = MIMEText(open(path + '/' + file, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header("Content-Disposition", "attachment", filename=("gbk", "", file))
msg.attach(att)
try:
server = smtplib.SMTP()
if mail_host == 'smtp.gmail.com':
server.connect(mail_host, port=587)
server.starttls()
else:
server.connect(mail_host)
server.login(mail_user, mail_pass)
server.sendmail(me, mailto_list + Cc_list, msg.as_string())
server.close()
print('Mail sent successfully')
shijian = '已发送,' + str(datetime.datetime.now())
return shijian
except Exception as e:
print('Mail sent failed')
print(sys.exc_info()[0], sys.exc_info()[1])
shijian = '1,发送失败'
return shijian
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义