我正在使用 smtplib 来自动接收电子邮件。以下是我到目前为止所取得的成就
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import poplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from email.header import Header
def get_email(email,password,path):
server = poplib.POP3_SSL('pop.' + email.split('@')[-1])
server.user(email)
server.pass_(password)
resp, mails, octets = server.list()
index = len(mails)
for x in reversed(range(index-2, index+1)):
server=poplib.POP3_SSL('pop.'+email.split('@')[-1])
server.user(email)
server.pass_(password)
# resp, mails, octets = server.list()
# index = len(mails)
# print("total emails: ", index)
resp, lines, octets = server.retr(x)
msg_content = b'\r\n'.join(lines).decode('utf-8','ignore')
msg = Parser().parsestr(msg_content)
#server.dele(index)
get_header(msg)
get_file(path,msg)
get_content(msg)
server.quit()
print('receive the lastest',index-x+1, "email")
print('----------------------------'"\n")
Above function would only start to receive email if the program is activated manually, or with a pre-set timer (e.g. activate the function every 5 minutes). What I need is a more smart function which can help to automatically check if any new emails received in the mailbox, and if yes it follows what is defined in the function to receive and process the email(s).