在Python中为安全系统线程化电子邮件

时间:2018-11-13 20:08:33

标签: python multithreading

我有一个用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 个答案:

答案 0 :(得分:0)

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

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