Python 向邮箱发送文件
时间: 2024-03-28 20:16:48 浏览: 53
python应用开发:邮件发送GUI程序.zip
可以使用 Python 的 smtplib 和 email 库来发送邮件和附件。以下是一个示例代码:
```
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 邮箱服务器地址和端口
smtp_server = 'smtp.example.com'
smtp_port = 587
# 发件人邮箱地址和授权码
from_addr = 'your_email@example.com'
password = 'your_email_password'
# 收件人邮箱地址
to_addr = 'recipient_email@example.com'
# 创建邮件对象
msg = MIMEMultipart()
# 添加邮件主题、发件人和收件人信息
msg['Subject'] = 'Python email with attachment'
msg['From'] = from_addr
msg['To'] = to_addr
# 添加邮件正文
text = MIMEText('This is a Python email with attachment.')
msg.attach(text)
# 添加附件
with open('file.txt', 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
attachment['Content-Type'] = 'application/octet-stream'
attachment['Content-Disposition'] = 'attachment; filename=file.txt'
msg.attach(attachment)
# 发送邮件并退出
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
print('Email sent successfully!')
except Exception as e:
print('Email sending failed:', e)
```
请将示例代码中的 smtp_server、from_addr、password、to_addr 和 attachment 的文件名改为您自己的信息,然后运行代码即可发送带有附件的电子邮件。
阅读全文