如何使用python从文件夹发送所有文件?

2024-04-24 13:55:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我想创建一个可以从文件夹发送所有文件的应用程序

想从文件夹中获取所有文件并向某人发送电子邮件吗

例如,我的文件夹中有四个文件,我希望从一个文件夹中获取所有文件 多谢各位

Folder
 -AAA.txt
 -BBB.zip
 -CCC.docx
 -av.mp4

我的代码

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


mail_host="smtp.gmail.com"  
mail_user="testing"    
mail_pass="testing"   

sender = 'testing@gmail.com'
receivers = ['testing@gmail.com']

message = MIMEMultipart()
message['From'] = Header("Hello2", 'utf-8')
message['To'] =  Header("World2", 'utf-8')

subject = 'Python SMTP Testing'
message['Subject'] = Header(subject, 'utf-8')

att1 = MIMEText(open('folder/*', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'

att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(mail_user,mail_pass)  
    smtpObj.sendmail(sender, receivers, message.as_string())
    print('Sent...')
except:
    traceback.print_exc()
    print('Error: ')

Tags: 文件fromimport文件夹commessageemailmail