I am trying to write a Python script that will: 1. Run at scheduled times during the day. 2. Will collect whatever files (in .mobi format) are in a particular directory (say C:\myFiles) and email them as attachments to a particular email address(email id remains constant). 3. The files in the C:\myFiles directory will keep changing over time (because I have another script which performs some archiving actions on these files and moves them to a different folder). However new files will keep on coming. I have an if condition check in the beginning to determine if files are present (and only then will it send an email).
I am not being able to detect any mobi files (using *.mobi did not work). If I explicitly add the filename then my code works, else it doesn't.
How do I make the code detect .mobi files automatically when it runs?
Here is what I have so far:
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()