SMTP:发送的视频附件原来是一个空文件(gmail)

问题描述 投票:0回答:0

您好,我正在尝试使用 python flask 将视频附件发送到 gmail。不幸的是,当我将其作为电子邮件发送时,我的视频附件为空(0Kb)。在它甚至作为视频附件发送出去之前,视频能够运行。在 gmail 中作为视频附件发送之前或之后我的代码没有错误

这是我的代码:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders



def send_email(subject, message, to_email, attachment_path=None):
    from_email = "[email protected]"
    password = "abcdefghijklmnop"

    # create message object instance
    msg = MIMEMultipart()

    # setup the parameters of the message
    msg['From'] = '[email protected]'
    msg['To'] = '[email protected]'
    msg['Subject'] = 'pigoen'

    # add in the message body
    msg.attach(MIMEText(message, 'plain'))

    # add attachment if provided
    if email_attachment_path is not None:
        # open the file in bynary
        attachment = open(email_attachment_path, "rb")

        # instance of MIMEBase and named as part
        part = MIMEBase('application', 'octet-stream')
        
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= %s" % email_attachment_path)
        # part.add_header('Content-Disposition',
        #                 'attachment; filename={}'.format("test.mp4"))
        # attach the instance 'part' to instance 'msg'
        msg.attach(part)

    # create SMTP session
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()

    # Login
    server.login(from_email, password)

    # send the message via the server.
    server.sendmail(from_email, to_email, msg.as_string())

    # Terminate the SMTP session and close the connection
    server.quit()

我调用上面函数的代码的另一部分:

filename = 'output_' + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.avi'
              out = cv2.VideoWriter(filename, fourcc, 20.0, (640,480))
              cv2.putText(frame, 'Sharp Object Detected!', (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2, cv2.LINE_AA)
              subject = "Sharp object detected"
              message = "Please check the attached video"
              to_email = "[email protected]"
              email_attachment_path = filename
              send_email(subject, message, to_email, email_attachment_path)

如果我能得到一些指导就好了。这是我第一次使用 python flask 发送 gmail,我发现它非常酷和有趣!

python flask smtp gmail email-attachments
© www.soinside.com 2019 - 2024. All rights reserved.