import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 指定目录
directory = 'D:\\file'
# 邮件相关配置
sender_email = '***********@qq.com' # 发送方邮箱
receiver_email = '**********@qq.com' # 接收方邮箱(QQ 邮箱)
password = '授权码' # 发送方邮箱密码
# 创建邮件
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = '文件内容'
# 遍历目录收集 Word 文档路径
word_files = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.docx') or file.endswith('.doc'):
word_files.append(os.path.join(root, file))
# 添加 Word 文档作为附件
for file_path in word_files:
with open(file_path, 'rb') as f:
attachment = MIMEApplication(f.read(), Name=os.path.basename(file_path))
message.attach(attachment)
# 发送邮件
with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
这里我们选择的是使用qq邮箱作为STMP服务器 请确保您打开STMP服务并拥有有效授权码
以上为实现代码 可以将想给目标邮箱发送的东西以word文档形式展开