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

2024-04-26 08:10:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件theimportcomifservermobi电子邮件
3条回答

只是想抛开使用yagmail(完全公开:我是开发人员)发送带有附件的电子邮件是多么容易。在

import yagmail
yag = yagmail.SMTP('sender@gmail.com', your_password)
yag.send('receiver@gmail.com', 'Greetings', contents = '/local/path/to/file.mobi')

你可以用内容做任何事情:如果你有一个清单,它会很好地组合起来。例如,一个文件名列表将使它附加所有。把它和一些信息混合在一起,它就会有一个信息。在

任何有效文件的字符串都将被附加,其他字符串只是文本。在

要一次添加所有mobi文件:

^{pr2}$

或者

yag.send('receiver@gmail.com', contents = ['Lots of files attached...'] + fpaths)

我建议您阅读github documentation以了解其他一些不错的特性,例如使用keyring,您不必在脚本中包含您的密码/用户名(额外的安全性)。设置一次,你就会很高兴。。。。在

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

使用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作业

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

相关问题 更多 >