python发送带附件的邮件
时间: 2023-07-21 20:06:16 浏览: 80
利用Python发送邮件或发带附件的邮件
要在Python中发送带附件的邮件,你可以使用smtplib和email模块。下面是一个简单的示例代码:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def send_email(sender_email, sender_password, recipient_email, subject, message, attachment_path):
# 创建MIMEMultipart对象
msg = MIMEMultipart()
# 设置发件人、收件人和主题
msg['From'] = sender_email
msg['To'] = recipient_email
msg['Subject'] = subject
# 添加正文
msg.attach(MIMEText(message, 'plain'))
# 添加附件
attachment = open(attachment_path, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path)
msg.attach(part)
# 发送邮件
server = smtplib.SMTP('smtp.gmail.com', 587) # 使用Gmail的SMTP服务器,端口号587
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
server.quit()
# 使用示例
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
recipient_email = 'recipient_email@example.com'
subject = '邮件主题'
message = '这是一封带附件的邮件。'
attachment_path = '/path/to/attachment_file.txt'
send_email(sender_email, sender_password, recipient_email, subject, message, attachment_path)
```
请确保将代码中的发送者邮箱、发送者密码、收件人邮箱、主题、消息内容和附件路径替换为实际值。此示例使用Gmail的SMTP服务器,你可以根据需要更改SMTP服务器和端口号。
阅读全文