调好文件路径以及邮箱号即可随地大小用
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 邮件配置
smtp_server = "smtp.163.com" # 使用你的邮箱服务提供商的 SMTP 服务器
smtp_port = 465 # SSL 端口
sender_email = "???7@163.com" # 发件人邮箱,这里我给隐藏掉了
sender_password = "PD2S733JaVV4YsPA" # 发件人邮箱密码或授权码
receiver_email = "???7@qq.com" # 接收方邮箱,几乎所有邮箱网址都可以
# 创建邮件对象
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "TXT 文件传输"
# 添加邮件正文
body = "请查收附件中的 TXT 文件。"
msg.attach(MIMEText(body, "plain"))
# 读取并附加 TXT 文件
file_path = "国产新闻联播总结.txt" # 要发送的 TXT 文件路径
try:
with open(file_path, "rb") as file:
attachment = MIMEApplication(file.read(), _subtype="txt")
attachment.add_header("Content-Disposition", "attachment", filename="国产新闻联播总结.txt")
msg.attach(attachment)
except FileNotFoundError:
print(f"文件未找到,请确认路径是否正确: {file_path}")
exit()
# 连接 SMTP 服务器并发送邮件
try:
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")