亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號