使用python来收发邮件。
收邮件
使用POP3协议,以网易企业邮箱为例,注意要使用客户端密码。
import poplib
from email.parser import Parser
from email.header import Header
from email.header import decode_header
username = "xxxx"
password = "xxxxx"
pop3_server = "pophz.qiye.163.com"
server = poplib.POP3_SSL(pop3_server, 995, timeout=10)
server.user(username)
server.pass_(password)
resp, mails, octets = server.list()
index = len(mails)
for i in range(index, 0, -1):
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
resp, lines, octets = server.retr(i)
print(now, "邮件读取成功,索引号:", i)
except:
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(now, "邮件读取失败,索引号:", i)
continue
msg_content = b'\n'.join(lines).decode('utf-8')
msg = Parser().parsestr(msg_content)
date = datetime.datetime.strptime(msg.get('Date')[:24], '%a, %d %b %Y %H:%M:%S')
# 邮件中的时间是UTC的,需要转换到东八区
date = date + datetime.timedelta(hours=8)
date = datetime.datetime.strftime(date, '%Y%m%d')
# 控制下载的时间间隔,是20230609这样的格式
if date < start_date:
break
if date > end_date:
continue
# 获得特定主题的邮件
subject_check = "特定主题"
decode_subject = decode_header(msg["Subject"])
subject = decode_subject[0][0].decode(decode_subject[0][1])
if not subject_check in subject:
continue
# 下载符合以上条件的附件
for part in msg.walk():
file_name = part.get_filename()
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]))
downfileNum += 1
data = part.get_payload(decode=True)
if not os.path.isdir(save_path):
os.mkdir(save_path)
att_file = open(save_path + os.sep + filename, "wb")
att_file.write(data)
att_file.close()
server.quit()
使用IMAP协议
import imaplib
from email import message_from_bytes
from email.header import decode_header
import datetime
username = "xxxx"
password = "xxxxxxxx"
server = imaplib.IMAP4_SSL(host="imaphz.qiye.163.com", port=993)
server.login(username, password)
# 选择邮箱
server.select("INBOX")
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
# 搜索条件:当天及前一天
# search_criteria = f'(SINCE "{today.strftime("%d-%b-%Y")}")'
search_criteria = f'(SINCE "{yesterday.strftime("%d-%b-%Y")}")'
status, data = server.search(None, search_criteria)
if status == 'OK':
# 邮件ID列表
email_ids = data[0].split()
if email_ids:
for email_id in email_ids:
email_id_dc = email_id.decode("utf-8")
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(now, "成功获取邮件索引:", email_id_dc)
# 遍历每封邮件
_, email_data = server.fetch(email_id, '(RFC822)')
email_body = email_data[0][1]
msg = message_from_bytes(email_body)
# 邮件主题
decode_subject = decode_header(msg["Subject"])
try:
subject = decode_subject[0][0].decode(decode_subject[0][1])
except:
subject = decode_subject[0][0].decode("utf-8")
# 关闭与邮件服务器的连接
server.logout()
发邮件
使用SMTP协议。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
username = "xxxx"
password = "xxxxx"
server = smtplib.SMTP_SSL(host="smtphz.qiye.163.com", port=465)
server.login(username, password)
receivers_list = ["收件人邮箱"]
cc_list = ["抄送邮箱"]
sender = username
send_list = receivers_list + cc_list
subject = "主题"
message = MIMEText(msg, "plain", "utf-8")
message['From'] = Header("自动提醒", 'utf-8')
message['to'] = ",".join(receivers_list)
message['Cc'] = ",".join(cc_list)
message['Subject'] = Header(subject, 'utf-8')
server.sendmail(sender, send_list, message.as_string())
server.quit()