从目录中选择一个随机文件并发送(Python、MIME)



我正在开发一个python程序,该程序从目录中随机选择一个文件,然后使用email.mime模块将其发送给您。我有一个问题,我可以选择随机文件,但由于这个错误,我无法发送它:

File "C:UsersMihkelDesktopdnak.py", line 37, in sendmemeone
attachment  =open(filename, 'rb')
TypeError: expected str, bytes or os.PathLike object, not list

这是代码:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import  MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import random
path ='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:UsersMihkelDesktope8re.py", line 29, in send
part.add_header('Content-Disposition',"attachment; filename= "+filename)
TypeError: can only concatenate str (not "list") to str

这部分似乎仍在列表中,我该如何修复?

您选择一个随机文件,然后将其丢弃(好吧,您打印它,然后将它丢弃(:

files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])

(你可以用random.choice(files)做哪个BTW(

当调用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')

相关内容

  • 没有找到相关文章

最新更新