Python电子邮件接收循环

时间:2019-01-19 03:03:52

标签: python gmail

我正在编写一个程序来测试标题为“ sup1”的电子邮件。如果收到,它将删除电子邮件,并向原始发件人发送一个随机数。现在,它只是有时会得到回应。顺便说一句,这是针对另一个项目的测试,这就是为什么它是一种奇怪的探测程序的原因。

#Get Email#
import easyimap
import imaplib
import smtplib
import ssl
import random

#Get Variables
login = "****"
password = "****"

imapserver = "imap.gmail.com"

#Send Variables
port = 465
smtp_server = "smtp.gmail.com"

#Booting Up
print("Booted up!")

#Functions
#Delete Emails
def deleteEmails(user,password,IMAP):
    mail = imaplib.IMAP4_SSL(IMAP)

    mail.login(user,password)
    mail.select("inbox")

    typ,data = mail.search(None,"ALL")

    for num in data[0].split():
        mail.store(num,"+FLAGS",r"(\Deleted)")

    mail.expunge()
    mail.close()
    mail.logout()

#Send
def sendEmail(message):
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL(smtp_server,port,context=context) as server:
        server.login(login,password)
        server.sendmail(login,receiver_email,message)

#While Loop
while True:
    #Read All Emails
    imapper = easyimap.connect("imap.gmail.com",login,password)
    for mail_id in imapper.listids(limit = 100):
        mail = imapper.mail(mail_id)

        temp = list(mail.from_addr)
        sender = ""
        temp2 = False
        for i in range(len(temp)):
            if temp[i] == "<":
                temp2 = True
            elif temp2 and temp[i] != ">":
                sender += temp[i]

        receiver_email = sender

        #Test For Kinds Of Emails
        if mail.title == "sup1":
            sendEmail("Subject: "+str(random.randint(1,10)))
            deleteEmails(login,password,imapserver)

            print("Sent")

0 个答案:

没有答案