Python中的安全系统线程电子邮件

我有一个用 python 编写的安全程序。它检测何时有人在相机前(机器学习)并向所有者发送一封带有入侵者照片的电子邮件。我的问题是如何线程化电子邮件功能,因为我想在程序发现入侵者时发送照片。现在,如果它发现入侵者,则执行将停止,直到通过电子邮件发送照片。我尝试使用线程模块,但它不起作用(我没有 python 线程的经验)。我只能启动一个线程,但我不知道如何让它用同一个线程发送多张照片。(不创建更多线程)。


def send_mail(path):

    sender = 'MAIL'

    gmail_password = 'PASS'

    recipients = ['OWNER']


# Create the enclosing (outer) message

    outer = MIMEMultipart()

    outer['Subject'] = 'Threat'

    outer['To'] = COMMASPACE.join(recipients)

    outer['From'] = sender

    outer.preamble = 'Problem.\n'


# List of attachments

    attachments = [path]


# Add the attachments to the message

    for file in attachments:

        try:

            with open(file, 'rb') as fp:

                msg = MIMEBase('application', "octet-stream")

                msg.set_payload(fp.read())

            encoders.encode_base64(msg)

            msg.add_header('Content-Disposition', 'attachment', 

filename=os.path.basename(file))

            outer.attach(msg)

        except:

            print("Unable to open one of the attachments. Error: ", 

sys.exc_info()[0])

            raise


    composed = outer.as_string()


# Send the email

    try:

        with smtplib.SMTP('smtp.gmail.com', 587) as s:

            s.ehlo()

            s.starttls()

            s.ehlo()

            s.login(sender, gmail_password)

            s.sendmail(sender, recipients, composed)

            s.close()

        print("Email sent!")

    except:

        print("Unable to send the email. Error: ", sys.exc_info()[0])

        raise


狐的传说
浏览 145回答 1
1回答

隔江千里

我想您会想要在线程已经发送时更新要发送的照片(不运行带有要发送的目标照片的线程),因此您可以将要发送的照片存储在全局变量中。这是我解决这个问题的方法:from threading import Threadimport timedef send_email():    print('started thread')    global photos_to_send    while len(photos_to_send) > 0:        current_photo = photos_to_send.pop(0)        print('sending {}'.format(current_photo))        time.sleep(2)        print('{} sent'.format(current_photo))    print('no more photos to send ending thread')photos_to_send = ['photo1.png']thread1 = Thread(target=send_email, args=())thread1.start()photos_to_send.append('photo2.png')thread1.join()#started thread#sending photo1.png#photo1.png sent#sending photo2.png#photo2.png sent#no more photos to send, ending thread
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python