次のような Python スクリプトを作成しようとしています。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()