smtplib 发送多条消息而不是一条

smtplib sending multiple messages instead of one

我正在尝试 运行 启动时的 python 脚本,这将需要大约 10 秒的视频来应用外部输入(例如按钮、红外传感器等,在我们的例子中超声波传感器),然后使用 Python.

的 SMTPlib 库将此视频邮寄到指定的电子邮件地址

所有这些都运行良好。但是,当多次使用此输入时,Raspberry Pi 会将多个视频(通过过去按下按钮拍摄)发送到电子邮件地址,而不是最后一次输入启动的视频。因此,按下按钮 1 次将发送 1 个视频;推它 2 次将与最后一个一起发送一个新的;按 3 次将发送一个新的和最后两个,依此类推。

我什至尝试在 python 脚本中发送邮件后立即插入 os.remove()。在 运行ning 程序之后,运行ning 一个 ls 显示文件确实被删除了。然而不知何故,这些已删除的视频进入了电子邮件。会不会是在使用smtplib的时候存储在内存的某个地方?

提到的脚本如下:

from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText


emailfrom = "xyz@abc.com"
emailto = "xyz123@abc.com"

username = "xyz@abc.com"
password = "pass"

msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "Email Subject -- "
msg.preamble = "Email Body --"


while(True):
        d=0
        # Possibly the relevant section
        d = pulse_d*17150
        d= round(d, 2)  

        if(d<100):
            with picamera.PiCamera() as camera:
                camera.start_preview()
                camera.start_recording('/home/pi/video.h264')
                time.sleep(5)
                camera.stop_recording()
                camera.stop_preview()
        time.sleep(5)
                fileToSend = "/home/pi/video.h264"

                ctype, encoding = mimetypes.guess_type(fileToSend)
                if ctype is None or encoding is not None:
            GPIO.output(test, True)
                    ctype = "application/octet-stream"

            maintype, subtype = ctype.split("/", 1)
                fp = open(fileToSend, "rb")
            GPIO.output(test,False)
                attachment = MIMEBase(maintype, subtype)
                attachment.set_payload(fp.read())
                fp.close()
                encoders.encode_base64(attachment)
                attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
                msg.attach(attachment)  
                server = smtplib.SMTP("smtp.gmail.com:587") 
                server.starttls()
                server.login(username,password) 
                server.sendmail(emailfrom, emailto, msg.as_string())
                server.quit()
        os.remove("/home/pi/video.h264")

我认为你应该创建新消息而不是重复使用旧消息。

将创建 msg 的代码移到 while 循环中

问题出在这里:

msg.attach(attachment)

您将文件附加到同一封邮件,但不删除旧附件。