使用Python发送带有附件的电子邮件

使用Python发送带有附件的电子邮件,python,email,filehandler,Python,Email,Filehandler,我正在尝试编写一个Python脚本,该脚本将: 1.在一天中的预定时间运行。 2.将收集特定目录(例如C:\myFiles)中的任何文件(以.mobi格式),并将其作为附件发送到特定的电子邮件地址(电子邮件id保持不变)。 3.C:\myFiles目录中的文件将随着时间的推移不断更改(因为我有另一个脚本,它对这些文件执行一些存档操作,并将它们移动到另一个文件夹)。然而,新的文件将不断出现。我在开始时有一个if条件检查,以确定文件是否存在(只有这样它才会发送电子邮件) 我无法检测到任何mobi文件

我正在尝试编写一个Python脚本,该脚本将: 1.在一天中的预定时间运行。 2.将收集特定目录(例如C:\myFiles)中的任何文件(以.mobi格式),并将其作为附件发送到特定的电子邮件地址(电子邮件id保持不变)。 3.C:\myFiles目录中的文件将随着时间的推移不断更改(因为我有另一个脚本,它对这些文件执行一些存档操作,并将它们移动到另一个文件夹)。然而,新的文件将不断出现。我在开始时有一个if条件检查,以确定文件是否存在(只有这样它才会发送电子邮件)

我无法检测到任何mobi文件(使用*.mobi无效)。如果我显式地添加文件名,那么我的代码就可以工作,否则就不行

如何使代码在运行时自动检测.mobi文件?

以下是我到目前为止的情况:

import os

# Import smtplib for the actual sending function
import smtplib
import base64

# For MIME type
import mimetypes

# Import the email modules 
import email
import email.mime.application


#To check for the existence of .mobi files. If file exists, send as email, else not
for file in os.listdir("C:/Users/srayan/OneDrive/bookManager/EmailSenderModule"):
    if file.endswith(".mobi"):
           # Create a text/plain message
            msg = email.mime.Multipart.MIMEMultipart()
            #msg['Subject'] = 'Greetings'
            msg['From'] = 'sender@gmail.com'
            msg['To'] = 'receiver@gmail.com'

            # The main body is just another attachment
            # body = email.mime.Text.MIMEText("""Email message body (if any) goes here!""")
            # msg.attach(body)

            # File attachment
            filename='*.mobi'   #Certainly this is not the right way to do it?
            fp=open(filename,'rb')
            att = email.mime.application.MIMEApplication(fp.read(),_subtype="mobi")
            fp.close()
            att.add_header('Content-Disposition','attachment',filename=filename)
            msg.attach(att)


            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login('sender@gmail.com','gmailPassword')
            server.sendmail('sender@gmail.com',['receiver@gmail.com'], msg.as_string())
            server.quit()

按如下所示使用glob筛选文件夹中的文件

fileNames=glob.glob(“C:\Temp\*.txt”)

迭代文件名并使用以下命令发送:

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

  s.sendmail(fro, to, msg.as_string() )
  s.close()

要安排电子邮件,请参阅使用python的cron jobs

,我只是想告诉大家使用(完全公开:我是开发人员)发送带有附件的电子邮件是多么容易

你可以用内容做各种各样的事情:如果你有一个东西的列表,它会很好地结合起来。例如,一个文件名列表将使其能够附加所有文件名。把它和一些信息混合在一起,它就会有一条信息

将附加任何有效文件的字符串,其他字符串仅为文本

要一次添加所有mobi文件,请执行以下操作:

my_path = "C:/Users/srayan/OneDrive/bookManager/EmailSenderModule"
fpaths = [file for file in os.listdir(my_path) if file.endswith(".mobi")]
yag.send('receiver@gmail.com', contents = fpaths)

我鼓励您阅读以查看其他优秀功能,例如,您不必使用钥匙圈在脚本中输入密码/用户名(额外安全)。设置一次,你就会很高兴


哦,是的,这里的代码不是41行,而是5行,使用yagmail;)

以下是我最终解决问题的方法。PascalvKooten有一个有趣的解决方案,这将使我的工作变得更容易,但是因为我正在学习Python,所以我想从头开始构建它。 谢谢大家的回答:)
你可以找到我的解决方案

嗯,太好了。你有问题吗?是的,对不起:(我的意思是我无法检测到任何mobi文件(使用*.mobi不起作用)。如果我显式添加文件名,那么我的代码就起作用,否则它就不起作用。
my_path = "C:/Users/srayan/OneDrive/bookManager/EmailSenderModule"
fpaths = [file for file in os.listdir(my_path) if file.endswith(".mobi")]
yag.send('receiver@gmail.com', contents = fpaths)
yag.send('receiver@gmail.com', contents = ['Lots of files attached...'] + fpaths)