I have a small program that searches through two folders and gets the size of the files in them. As of right now for every file that is over the specified size limit sends a email. What i am wanting to do it have it compile a lsit of the files that are to large and send the list as one email.

import requests, shutil, datetime, glob, os, csv,fnmatch,StringIO,smtplib,argparse, math
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from os import path

parser = argparse.ArgumentParser(description='Search art folders.')
parser.add_argument('-b', help='The base path', required=False, dest='basePath', metavar='Base directory path',default='/home/hatterx/Desktop')
parser.add_argument('--se', help='Change sending emailaddress', required=False, dest='sendEmail', metavar='Sending Emailaddress', default='addon2031@gmail.com')
parser.add_argument('--re', help='Change reciveing emailaddress', required=False,dest='reciveEmail', metavar='Reciveing Emailaddress', default='hatterx@oakleysign.com')
parser.add_argument('--pw', help='Change password', required=False, dest='changePassword', metavar='Change Password', default='jcfutalhndkwsltg')
parser.add_argument('-s', help='Change File size', required=True, dest ='changesize', metavar='Change size', default='0')
args = parser.parse_args()

files = StringIO.StringIO()

def sendEmail(toaddress, subject, body):
    fromaddr=args.sendEmail
    toaddr= toaddress
    msg=MIMEMultipart()
    msg['From']=fromaddr
    msg['To']=toaddr
    msg['Subject']= subject
    body= body
    msg.attach(MIMEText(body,'plain'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(Sender, Password)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)

fF = datetime.datetime.now().strftime("%Y%B")
fA = datetime.datetime.now().strftime("%Y%b")

filebase = args.basePath
fileFull = filebase+'/'+fF.upper()+'JPG'
fileAbriv = filebase+'/'+fA.upper()+'JPG'
Reciver = args.reciveEmail
Sender = args.sendEmail
Password = args.changePassword


def fileSearch(filename):

    os.chdir(filename)
    for fileName in glob.iglob("*"):
        files.write(fileName)
        files.seek(0)
        dirname, filenamE = os.path.split(fileName)
        SUBJECT = 'File size'
        statinfo = os.stat(fileName)
        numToString = str(statinfo.st_size/1024)
        BODY = 'The following list of files are to large: '+files.readline()
        print (str(statinfo.st_size/1024))+'KB'
        print (filename)+'/'+(filenamE)
        if args.changesize >= str(statinfo.st_size/1024):
            sendEmail(args.reciveEmail, SUBJECT, BODY)
        elif args.changesize < str(statinfo.st_size/1024):
            print 
    print 'These files are the correct size please check email for files that are to large.'
fileSearch(fileFull)
fileSearch(fileAbriv)   

Dani AI

Generated

Short summary and a concrete fix for the problems in the original post.

As suggested, collect the names of oversized files while you scan the folders, then send a single email with that list. The original code is doing three things that commonly cause trouble: treating the size limit as text (string) instead of a number, appending to/reading from a rolling buffer instead of keeping a simple list, and calling the mail send inside the per-file loop. For this means: convert the CLI size arg to an integer, append matching filenames to a list, and only call the SMTP send once after both folders are scanned.

Example pattern (Python 3, succinct):

import os
from email.message import EmailMessage
import smtplib

def find_oversized(paths, limit_kb):
    out = []
    for base in paths:
        for root, _, files in os.walk(base):
            for name in files:
                p = os.path.join(root, name)
                try:
                    size_kb = os.path.getsize(p) // 1024
                except OSError:
                    continue
                if size_kb > limit_kb:
                    out.append(f"{p}  {size_kb} KB")
    return out

# after collecting, build body once:
# body = "\n".join(find_oversized([dir1, dir2], limit_kb))
# send the message with smtplib once

Practical tips and cautions:

  • Parse the size argument with int() and compare numeric values (avoid string comparisons).
  • Only send mail when the list is non-empty. That prevents dozens of messages.
  • Use a context manager or call quit() on the SMTP object; see the stdlib smtplib documentation for examples.
  • If you are using smtp.gmail.com, plain account passwords are often blocked now; enable 2‑step verification and use an app password or a more modern auth flow. See Google’s guidance on app passwords and less-secure-app access: .

Following that pattern makes the code simpler, reduces SMTP connections, and produces one clear, readable alert email with all oversized files listed.

Why you are using StringIO here? Just build the string normally and send it.
Python pseudo-code:

send_mail(address, subject,'\n'.join(info_i_want(big_file) for big_file in list_of_files if size_of(big_file) > SIZE_LIMIT)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.