Select 目录中的随机文件并发送 (Python, MIME)

Select a random file from a directory and send it (Python, MIME)

我正在开发一个 python 程序,该程序随机 select 从目录中获取一个文件,然后使用 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 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()

我相信它只是将文件名作为 selected 随机选择,我如何才能将它获取到 select 文件本身?

编辑:进行建议的更改后,我现在收到此错误:

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

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

你 select 一个随机文件,然后把它扔掉(好吧,你 打印 它,然后把它扔掉):

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 您 select 编辑的文件:

attachment  = open(random.choice(files), 'rb')

但是,这仍然行不通,因为 listdir 只有 returns 文件名而不是完整路径,所以你需要得到它返回,最好使用 os.path.join:

attachment  = open(os.path.join(path, random.choice(files)), 'rb')