Python安全系统的邮件线程化

2024-04-16 21:36:33 发布

您现在位置: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

Tags: thetopathasmsg线程照片gmail
1条回答
网友
1楼 · 发布于 2024-04-16 21:36:33

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

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

相关问题 更多 >