使用python语言,通过IMAP收qq邮件。
需要改对应的qq邮箱账号,以及对应16位授权码。
实现功能:接收并筛选qq邮箱并处理邮箱内容,进行数据解析。
筛选范围:当天+特定主题+指定发送人+特定内容。此处请按需修改。
1.代码如下:
# =============================================================================
# 接收QQ邮件进行筛选解析获取所需trader数据
# 筛选范围:当天+特定主题+特定内容
# @author: zhangb
# =============================================================================
def getTraderData():
import imapclient
import pyzmail
from datetime import date
#创建一个IMAPClient对象,大多数邮件提供商要求SSL加密,传入ssl = True关键字参数
imapObj = imapclient.IMAPClient('imap.qq.com',ssl = True)
imapObj.login('[email protected]','xxx') #xxx处填写16位授权码
imapObj.select_folder('INBOX',readonly = True)
# 读取 2020 1月1日后的未读邮件 注意写法
UIDs = imapObj.search([u'SINCE', date.today(),['FROM [email protected]']])
# 解析邮件数据
count=0
trader = [[0 for i in range(3)] for j in range(100)]
for i in UIDs:
#获得邮件内容
rawMessage = imapObj.fetch(i, ['BODY[]']) # 获取邮件内容
messageObj = pyzmail.PyzMessage.factory(rawMessage[i][b'BODY[]'])
#打印邮件信息,根据信息进行筛选邮件
#print(messageObj.get_subject())#邮件主题
#print(messageObj.get_addresses('from'))#发件人
#print(messageObj.get_addresses('to'))#收件人
##主题一致&&邮件有内容
if messageObj.get_subject()=='Info from JoinQuant' and messageObj.text_part != None:
#按需使用text_part或是html_part进行格式转换
messageContent = messageObj.text_part.get_payload().decode(messageObj.text_part.charset)
list = messageContent.split(" ")
for i in range(len(list)):
if list[i]=='code':
trader[count][0]=list[i+1]
elif list[i]=='account':
trader[count][1]=float(list[i+1])
elif list[i]=='price':
trader[count][2]=float(list[i+1])
count+=1
imapObj.logout()
#打印邮件数据
for i in range(count):
print(type(trader[i][0]),trader[i][0])
print(type(trader[i][1]),trader[i][1])
print(type(trader[i][2]),trader[i][2])
if __name__ == '__main__':
getTraderData()
2.邮箱内容如下:
3.最终的运行结果如下: