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

时间:2018-12-11 09:10:53

标签: python file random directory mime-mail

我正在研究一个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 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:\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 个答案:

答案 0 :(得分:1)

您选择一个随机文件,然后将其丢弃(嗯,您先打印,然后将其丢弃):

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')