通过python发送视频文件

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

我需要弄清楚如何制作一个脚本来扫描目录中的新文件,并在有新文件时通过电子邮件发送文件。

有人不断在我的公寓楼偷自行车!首先是我的错(我必须锁住它),现在骗子通过切断链条升级了。骗子剪断 1/2 英寸的飞机电线偷走了我的第二辆自行车后,我得到了它。

无论如何,使用树莓派作为运动激活的安全摄像头,我希望它在视频程序完成录制后立即向我发送视频文件。这是为了防止他们偷走圆周率。

我正在查看这些示例,但我不知道如何使脚本连续运行(每分钟)或如何使其扫描文件夹中的新文件。

如何使用 SMTP 发送附件?

好的 我把它归结为扫描然后尝试发送电子邮件。尝试附加视频文件时失败。你能帮忙吗?这是修改后的代码:

失败的是:
msg = MIMEMultipart() 类型错误:“LazyImporter”对象不可调用,第 38 行

import time, glob
import smtplib
import email.MIMEMultipart  
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders, MIMEMultipart
import os

#Settings:
fromemail= "Jose Garcia <[email protected]>"
loginname="[email protected]"
loginpassword="somerandomepassword"
toemail= "Jose Garcia <[email protected]>"
SMTPserver='smtp.gmail.com'
SMTPort=587
fileslocation="/Users/someone/Desktop/Test/*.mp4"
subject="Security Notification"

def mainloop():   
        files=glob.glob(fileslocation) #Put whatever path and file format you're using in there.
        while 1:
            new_files=glob.glob(fileslocation)
            if len(new_files)>len(files):
                for x in new_files:
                    if x in files:
                        print("New file detected "+x)
                        print("about to call send email")
                        sendMail(loginname, loginpassword, toemail, fromemail, subject, gethtmlcode(), x, SMTPserver, SMTPort)

            files=new_files
            time.sleep(1)

def sendMail(login, password, to, frome, subject, text, filee, server, port):
#    assert type(to)==list
#    assert type(filee)==list

    msg = MIMEMultipart()
    msg['From'] = frome
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

#    #for filee in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(filee,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(filee))
    msg.attach(part)

    smtp = smtplib.SMTP(SMTPserver, SMTPort)
    smtp.sendmail(frome, to, msg.as_string() )
    server.set_debuglevel(1) 
    server.starttls() 
    server.ehlo() 
    server.login(login, password) 
    server.sendmail(frome, to, msg) 
    server.quit()

def gethtmlcode():
    print("about to assemble html")
    html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
    html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
    html +='<body style="font-size:12px;font-family:Verdana"><p>A new video file has been recorded </p>'
    html += "</body></html>"
    return(html)

#Execute loop
mainloop()
python security email raspberry-pi
5个回答
1
投票

我终于成功了。我必须使用 python 2.5 来消除 LazyImporter 错误。每次将新文件添加到安全文件夹时,它都会通过电子邮件发送给我。日志记录已损坏。

import time, glob
import smtplib
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEMultipart import MIMEBase 
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
import datetime 
from email import Encoders
import os
import sys


#Settings:
fromemail= 'RaspberryPI Security Camera <someone>'
loginname='[email protected]'
loginpassword='something'
toemail= 'Jose Garcia < [email protected]>'
SMTPserver='smtp.gmail.com'
SMTPort=587
fileslocation='/Users/someone/Desktop/Test/*.*'
subject="Security Notification"
log='logfile.txt'

def mainloop():   
        files=glob.glob(fileslocation) #Put whatever path and file format you're using in there.
        while 1:
            f = open(log, 'w')
            sys.stdout = Tee(sys.stdout, f)
            new_files=glob.glob(fileslocation)
            if len(new_files)>len(files):
                for x in new_files:
                    if x in files:
                        print(str(datetime.datetime.now()) + "New file detected "+x)
                        sendMail(loginname, loginpassword, toemail, fromemail, subject, gettext(), x, SMTPserver, SMTPort)
            files=new_files
            f.close()
            time.sleep(1)

def sendMail(login, password, send_to, send_from, subject, text, send_file, server, port):

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(send_file,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(send_file))
    msg.attach(part)

    smtp = smtplib.SMTP(SMTPserver, SMTPort)
    smtp.set_debuglevel(1) 
    smtp.ehlo() 
    smtp.starttls() 
    smtp.login(login, password) 
    smtp.sendmail(send_from, send_to, msg.as_string() )
    smtp.close()


def gettext():
    text = "A new file has been added to the security footage folder. \nTime Stamp: "+ str(datetime.datetime.now())
    return(text)

class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)


#Execute loop
mainloop()

1
投票

看起来电子邮件模块已经随着时间的推移而被重构。这修复了我在 Python 2.7 上的

'LazyImporter' object not callable
错误:

from email.mime.text import MIMEText

值得注意的是,它对(我所认为的)像

import email; email.mime.text.MIMEText(...)

这样的同义词不满意

1
投票

我使用 python3,我一生都无法让这些示例中的任何一个发挥作用,但我能够想出一些有效且简单得多的东西。

import smtplib
from email.message import EmailMessage
from email.mime.base import MIMEBase
from email import encoders

# Defining Objects and Importing Files ------------------------------------

# Initializing video object
video_file = MIMEBase('application', "octet-stream")

# Importing video file
video_file.set_payload(open('video.mkv', "rb").read())

# Encoding video for attaching to the email
encoders.encode_base64(video_file)

# creating EmailMessage object
msg = EmailMessage()

# Loading message information ---------------------------------------------
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = 'text for the subject line'
msg.set_content('text that will be in the email body.')
msg.add_attachment(video_file, filename="video.mkv")

# Start SMTP Server and sending the email ---------------------------------
server=smtplib.SMTP_SSL('smtp.gmail.com',465)
server.login("[email protected]", "some-clever-password")
server.send_message(msg)
server.quit()

0
投票

只需将脚本放入循环中并让它休眠 60 秒。您可以使用

glob
获取目录中的文件列表。
in
对于查看列表中的内容(即目录中的文件列表)非常有用。

import time, glob

files=glob.glob("/home/me/Desktop/*.mp4") #Put whatever path and file format you're using in there.

while 1:
    new_files=glob.glob("/home/me/Desktop/*.mp4")
    if len(new_files)>len(files):
        for x in new_files:
            if x not in files:
                print("New file: "+x) #This is where you would email it. Let me know if you need help figuring that out.
    files=new_files
    time.sleep(60)

0
投票

@Dewey Brooke 代码很好,需要额外一行。

我的代码与他添加的代码有点不同,比如时间是可选的。

我刚刚开始工作,所以有一个问题。当你打开gmail时,有两个文件。我稍后会解决这个问题

import cv2
import smtplib
from time import sleep
from email import encoders
from email.mime.base import MIMEBase
from email.message import EmailMessage



VIDEOFILE='example.mp4'

TO='[email protected]'
FROM='[email protected]'
subject='Greetings'
body='Camera photo'
Pass='App_pass'#App password from google gmail



vidFile=MIMEBase('application','octect-stream')
vidFile.set_payload(open(VIDEO,'rb').read())

encoders.encode_base64(vidFile)vidFile.add_header('Content-Disposition','attachment; filename={}'.format(example.mp4'))


msg=EmailMessage()
msg["To"]=TO
msg["From"]=FROM
msg["Subject"]=subject
msg.set_content('Video From Cam')
msg.add_attachment(vidFile,filename='VIDEOFILE')



final_message=msg.as_string()

s=smtplib.SMTP('smtp.gmail.com',587)
s.set_debuglevel(1)
s.ehlo()
s.starttls()
s.login(FROM,Pass)
s.sendmail(FROM,TO,final_message)
sleep(1)
s.quit()
print('\nMessage Sent')
© www.soinside.com 2019 - 2024. All rights reserved.