上集为大家讲解了Gmail的专用密码设置和IMAP的设置,接下来主要为大家展示一下代码的实现
import imaplib
import email
import re
class receive_gmail:
def __init__(self):
self.emailuser = "【Gmail邮箱】"
self.emailpasswd = "【专用密码】"
self.imapserver = 'imap.gmail.com'
self.imapport = 993 # IMAP协议专用端口,该端口可根据各个邮箱厂家的协议绑定
self.conn = self.connect_mail()
self.mailidlist = self.get_mailidlist()
def connect_mail(self):
conn = imaplib.IMAP4_SSL(host=self.imapserver, port=self.imapport)
conn.login(self.emailuser, self.emailpasswd)
conn.list() # 列出邮箱中所有的列表,如:收件箱、垃圾箱、草稿箱。。。
conn.select('INBOX') # 选择收件箱(默认)
return conn
def get_mailidlist(self):
result, dataid = self.conn.uid('search', None, "ALL")
mailidlist = dataid[0].split() # 转成标准列表,获得所有邮件的ID
mailidlist.reverse()
return mailidlist
def get_body(self, msg):
try:
# 解析邮件内容
if msg.is_multipart():
return self.get_body(msg.get_payload(0))
else:
return msg.get_payload(None, decode=True)
except:
return ''
def get_list_message_one(self):
# 获取邮箱下所有的发件人和主题
latest_message = self.mailidlist
# 获取所有的邮件信息
for id in latest_message:
result, data = self.conn.fetch(id, '(RFC822)') # 通过邮件id获取邮件
e = email.message_from_bytes(data[0][1])
try:
subject = email.header.make_header(email.header.decode_header(e['SUBJECT']))
mail_from = email.header.make_header(email.header.decode_header(e['From']))
print("邮件的subject -- [%s]" % subject)
print("邮件的发件人 -- [%s]" % mail_from)
except:
pass
def get_list_message_two(self):
# 根据邮箱发件人读取对应的邮件内容并匹配验证码
latest_message = self.mailidlist
# 获取所有的邮件信息
for id in latest_message:
result, data = self.conn.fetch(id, '(RFC822)') # 通过邮件id获取邮件
e = email.message_from_bytes(data[0][1])
try:
subject = email.header.make_header(email.header.decode_header(e['SUBJECT']))
mail_from = email.header.make_header(email.header.decode_header(e['From']))
print("邮件的subject -- [%s]" % subject)
print("邮件的发件人 -- [%s]" % mail_from)
if 'book' in str(mail_from):
try:
body = str(self.get_body(e), encoding='utf-8') # utf-8 gb2312 GB18030解析中文日文英文
if 'FB-' in str(body):
facebook_code = re.compile(r'FB-(\d{5})', re.S).findall(body)
print(f'gmail code: {facebook_code[0]}')
# print("邮件内容 -- [%s]" % body)
break
except:
pass
except:
pass
def run(self):
try:
self.get_list_message_one()
self.get_list_message_two()
except Exception as error:
print(f'error:{error}')
finally:
self.conn.logout() # 推出邮件连接
if __name__ == '__main__':
runstart = receive_gmail()
runstart.run()
不管是qq、360、136等各大系列的邮箱,基本上大同小异。