Reputation: 23
I'm working on a mailbomb program that randomizes images from a given directory. The code looks like this:
import schedule, time, smtplib, random, os, sys, socket
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
# Image randomization still under development
def message(subject="Python Notification",
text="", img="", attachment=None):
msg = MIMEMultipart()
msg['Subject'] = subject
msg.attach(MIMEText(text))
if type(img) is not list:
img=[img]
for one_img in img:
path = "C:\\Users\\JoeBiden\\Desktop\\PJ\\AMP\\ImgLib"
files=os.listdir(path)
randPic=random.choice(files)
img_data = open(randPic, 'rb').read()
msg.attach(MIMEImage(img_data,
name=os.path.basename(img_data)))
if attachment is not None:
if type(attachment) is not list:
attachment = [attachment]
for one_attachment in attachment:
with open(one_attachment, 'rb') as f:
file = MimeApplication(
f.read(),
name=os.path.basename(one_attachment)
)
file['Content-Disposition'] = f'attachment;\
filename="{os.path.basename(one_attachment)}"'
msg-attach(file)
return msg
def mail():
smtp=smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('[email protected]', 'PEEENIS')
msg = message("Pizza", "Pizza", r"C:\Users\JoeBiden\Desktop\PJ\AMP\ImgLib")
to = ("[email protected]")
smtp.sendmail(from_addr="[email protected]",
to_addrs=to, msg=msg.as_string())
smtp.quit()
schedule.every(2).seconds.do(mail)
while True:
schedule.run_pending()
time.sleep(1)
When running in CMD I get the following error:
ret = self.job_func()
File "C:\Users\JoeBiden\Desktop\PJ\AMP\MailRandomizer.py", line 46, in mail
msg = message("Pizza", "Pizza", r"C:\Users\JoeBiden\Desktop\PJ\AMP\ImgLib")
File "C:\Users\JoeBiden\Desktop\PJ\AMP\MailRandomizer.py", line 22, in message
img_data = open(randPic, 'rb').read()
FileNotFoundError: [Errno 2] No such file or directory: 'RandImageFile.jpg'
To me the error seems paradoxical since it clearly shows me that it has found one of the desired files in the correct directory. That being the 'RandImageFile.jpg'
Upvotes: 0
Views: 346
Reputation: 2764
os.listdir()
only gives you the filenames, so try replacing
files=os.listdir(path)
with something like
files = [os.path.join(path, f) for f in os.listdir(path)]
Upvotes: 2