python发送从GMAIL发送邮件带附件
时间: 2023-07-07 14:30:58 浏览: 189
使用yagmail在Python中方便地为gmail发送电子邮件-Python开发
以下是一个使用 Python 发送带附件的邮件的示例代码:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# 邮件发送者和接收者
sender = 'your_email_address@gmail.com'
recipient = 'recipient_email_address@example.com'
# 创建一个带附件的邮件
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = 'Test Email with Attachment'
# 邮件正文
body = 'This is a test email with attachment'
msg.attach(MIMEText(body, 'plain'))
# 附件文件路径
filename = 'path/to/attachment'
# 读取附件文件并添加到邮件
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# 连接 Gmail SMTP 服务器并发送邮件
smtp_server = 'smtp.gmail.com'
smtp_port = 587
username = 'your_email_address@gmail.com'
password = 'your_email_password'
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
smtp.starttls()
smtp.login(username, password)
smtp.send_message(msg)
print('Email sent successfully')
```
请注意,您需要将 `your_email_address@gmail.com` 和 `your_email_password` 更改为您自己的 Gmail 邮箱地址和密码,并将 `recipient_email_address@example.com` 更改为收件人的邮箱地址。另外,将 `path/to/attachment` 更改为您要添加为附件的文件路径。
阅读全文