python 发送邮件:添加文件名为中文的附件

时间:2024-10-24 18:12:51
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from email.utils import formataddr import os from urllib.parse import quote from datetime import datetime # 配置邮件服务器和账户信息 smtp_server = 'smtp.163.com' # 替换为你的SMTP服务器地址 smtp_port = 465 # SMTP服务器端口,例如587或465 smtp_user = 'test@163.com' # 替换为你的发件邮箱地址 smtp_password = '123456' # 替换为你的邮箱密码或应用专用密码 # 发件人信息 sender_email = smtp_user # 收件人信息 recipients = ['test2@163.com', 'test3@163.com'] recipient_email = ', '.join(recipients) # 将收件人列表转换为逗号分隔的字符串,用于邮件头 # 邮件内容 current_time = datetime.now() formatted_time = current_time.strftime("%m月%d日") subject = '中文文件名-测试邮件发送: '+ formatted_time body = '详见附件' # 创建MIMEMultipart对象 msg = MIMEMultipart() msg['From'] = sender_email msg['To'] = recipient_email msg['Subject'] = subject # 添加邮件正文 msg.attach(MIMEText(body, 'plain', 'utf-8')) # 添加附件 excel_file_path = f"中文文件名_{formatted_time}.xlsx" # 确保文件路径和名称正确 if os.path.isfile(excel_file_path): with open(excel_file_path, 'rb') as attachment: # 设置附件的MIME类型和文件名(包括编码) mime_base = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet') mime_base.set_payload(attachment.read()) encoders.encode_base64(mime_base) # 添加附件头信息,包括文件名(需要处理编码) # safe:可选参数,指定不需要编码的 ASCII 字符集合。默认值是 '/' filename_encoded = quote(excel_file_path, safe=':/?#[]@!$&\'()*+,;=') # 构建Content-Disposition头部 content_disposition = f'attachment; filename*=utf-8\'\'{filename_encoded}' mime_base.add_header('Content-Disposition', content_disposition) msg.attach(mime_base) else: print(f'文件 {excel_file_path} 不存在!') # 这里可以处理文件不存在的情况,比如返回错误或者发送不包含附件的邮件 # 发送邮件 try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() # 启用TLS加密 server.login(smtp_user, smtp_password) # 登录到SMTP服务器 server.sendmail(sender_email, recipient_email, msg.as_string()) # 发送邮件 print('邮件发送成功!') except Exception as e: print(f'邮件发送失败:{e}') finally: server.quit() # 关闭连接