我正在开发一个 python 程序,该程序从目录中随机选择一个文件,然后使用该email.mime模块将其发送给您。我遇到了一个问题,我可以选择随机文件,但由于此错误而无法发送: File "C:\Users\Mihkel\Desktop\dnak.py", line 37, in sendmemeone attachment =open(filename, 'rb')TypeError: expected str, bytes or os.PathLike object, not list这是代码:import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email import encodersimport osimport randompath ='C:/Users/Mihkel/Desktop/memes'files = os.listdir(path)index = random.randrange(0, len(files))print(files[index])def send(): email_user = 'yeetbotmemes@gmail.com' email_send = 'miku.rebane@gmail.com' subject = 'Test' msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = subject body = 'Here is your very own dank meme of the day:' msg.attach(MIMEText (body, 'plain')) filename=files attachment =open(filename, 'rb') part = MIMEBase('application','octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition',"attachment; filename= "+filename) msg.attach(part) text = msg.as_string() server = smtplib.SMTP('smtp.gmail.com',587) server.starttls() server.login(email_user,"MY PASSWORD") server.sendmail(email_user,email_send,text) server.quit()我相信它只是将文件名作为选定的随机选择,我怎么能让它选择文件本身?编辑:在进行建议的更改后,我现在收到此错误:File "C:\Users\Mihkel\Desktop\e8re.py", line 29, in send part.add_header('Content-Disposition',"attachment; filename= "+filename)TypeError: can only concatenate str (not "list") to str似乎这部分仍在列表中,我该如何解决?
1 回答
慕姐4208626
TA贡献1852条经验 获得超7个赞
您选择一个随机文件,然后将其丢弃(好吧,您打印它,然后将其丢弃):
files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])
(顺便说一句,你可以用它做什么random.choice(files))
并在调用open时将整个files列表传递给它:
filename = files
attachment = open(filename, 'rb')
相反,传递open您选择的文件:
attachment = open(random.choice(files), 'rb')
但是,这仍然不起作用,因为listdir只返回文件名而不是完整路径,因此您需要将其取回,最好使用os.path.join:
attachment = open(os.path.join(path, random.choice(files)), 'rb')
添加回答
举报
0/150
提交
取消