-1

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()

3 Answers3

1

Just wanted to throw out there how easy it is to send emails with attachments using yagmail (full disclose: I'm the developer).

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

You can do all kind of things with contents: if you have a list of stuff it will nicely combine it. For example, a list of filenames will make it so that it will attach all. Mix it with some message, and it will have a message.

Any string that is a valid file will be attached, other strings are just text.

To add all mobi files at once:

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)

or

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

I encourage you to read the github documentation to see other nice features, for example you do not have to have your password / username in the script (extra safety) by using the keyring. Set it up once, and you'll be happy....

Oh yea, instead of your 41 lines of code here, it can be done with 5 using yagmail ;)

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
0

Use glob as follows to filter the files in the folder

fileNames = glob.glob("C:\Temp\*.txt")

Iterate through the filenames and send them using the following :

  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()

To schedule the emails please refer to cron jobs with python

ken lun
  • 22
  • 4
0

Here's how I finally solved it. PascalvKooten had an interesting solution and that would have made my job a lot easier, however since I am learning Python so I wanted to build it from scratch. Thank you everyone for the answers :) You can find my solution here