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

时间:2015-07-28 01:43:27

标签: python email filehandler

我正在尝试编写一个Python脚本,它将: 1.在白天的预定时间运行。 2.将收集特定目录中的任何文件(以.mobi格式)(例如C:\ myFiles),并将其作为特定电子邮件地址的附件发送(电子邮件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()

3 个答案:

答案 0 :(得分:1)

只是想放弃使用yagmail发送带附件的电子邮件是多么容易(完全披露:我是开发人员)。

import yagmail
yag = yagmail.SMTP('sender@gmail.com', your_password)
yag.send('receiver@gmail.com', 'Greetings', contents = '/local/path/to/file.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)

我建议您阅读github documentation以查看其他不错的功能,例如您不必使用密钥环在脚本中获得密码/用户名(额外的安全性)。设置一次,你就会开心....

哦,是的,而不是你的41行代码,可以使用yagmail完成5;)

答案 1 :(得分:0)

按如下方式使用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作业

答案 2 :(得分:0)

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

相关问题