为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

狐的传说 2021-08-17 10:43:00
我有一个用 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
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

我想您会想要在线程已经发送时更新要发送的照片(不运行带有要发送的目标照片的线程),因此您可以将要发送的照片存储在全局变量中。这是我解决这个问题的方法:


from threading import Thread

import time


def 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


查看完整回答
反对 回复 2021-08-17
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号