Search code examples
pythonfilepathsmtplibos.path

How to find individual files and email file location in python


I'm trying to perform 2 functions using python. The first function is to find the directory path of all *.txt files within a directory structure. The second is to send the file directory path to an email address in the body of the email.

import smtplib
import os, os.path
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

fromaddr = "server@company.com"
toaddr = "user@company.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "New message"

for root, dirs, files in os.walk("/var/logs"):
    for f in files:
        fullpath = os.path.join(root, f)
        if os.path.splitext(fullpath)[1] == '.txt':
         body = "Path = %s" % fullpath
         msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('mail.company.com',25)
server.ehlo()
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

I have had some success, but it's not working as I'd like. At the moment the email arrives with one of the file paths in the body of the email and the other file paths as txt attachments to the email.

I'd like it to send a separate email for each *.txt file it finds. Any help would be very appreciated.

Cheers,

Ben


Solution

  • Create and send a new message for every .txt file inside the loop. Something like this:

    import smtplib
    import os, os.path
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    
    fromaddr = "server@company.com"
    toaddr = "user@company.com"
    
    server = smtplib.SMTP('mail.company.com',25)
    server.ehlo()
    
    for root, dirs, files in os.walk("/var/logs"):
        for f in files:
            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = toaddr
            msg['Subject'] = "New message"
    
            fullpath = os.path.join(root, f)
            if os.path.splitext(fullpath)[1] == '.txt':
                body = "Path = %s" % fullpath
                msg.attach(MIMEText(body, 'plain'))
    
                text = msg.as_string()
                server.sendmail(fromaddr, toaddr, text)
    
    server.quit()