可以使用Python的smtplib和email模块来实现发送带附件的邮件。以下是一个简单的示例代码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email_with_attachment(sender_email, sender_password, recipient_email, subject, body, attachment_path):
# 设置SMTP服务器和端口号
smtp_server = 'smtp.example.com'
smtp_port = 587
# 创建MIMEMultipart对象,用于构建邮件内容
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open(attachment_path, 'rb') as f:
attachment = MIMEApplication(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=attachment_path)
msg.attach(attachment)
# 登录SMTP服务器并发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
# 使用示例
sender_email = 'your_email@example.com'
sender_password = 'your_email_password'
recipient_email = 'recipient@example.com'
subject = 'Test Email with Attachment'
body = 'This is a test email with an attachment.'
attachment_path = 'path/to/your/attachment.txt'
send_email_with_attachment(sender_email, sender_password, recipient_email, subject, body, attachment_path)
在上面的代码中,需要替换 sender_email、sender_password、recipient_email为发件人和收件人的实际邮箱地址,smtp_server和 smtp_port为你的SMTP服务器地址和端口号,attachment_path为要发送的附件文件的路径。
注意:使用SMTP发送邮件涉及到邮箱账号密码等敏感信息,请确保代码安全性,不要将敏感信息硬编码在代码中。推荐使用配置文件或环境变量来保存这些信息。
香港五网CN2网络云服务器链接:www.tsyvps.com
蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。