我正在尝试编写一个 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()