python自动化运维一键发送邮箱
时间: 2024-06-17 14:01:32 浏览: 80
Python自动化运维中,使用SMTplib库可以实现发送电子邮件的自动化功能。以下是一个基础的示例,展示如何通过SMTP协议发送一封带有附件的邮件:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
# 邮件设置
sender_email = 'your_email@example.com'
sender_password = 'your_email_password' # 如果是SMTP应用密码,请使用
receiver_email = 'recipient_email@example.com'
subject = 'Automated Email from Python'
body = 'This is an automated message sent using Python.'
attachment_path = 'path_to_your_attachment' # 例如 'document.pdf'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
# 添加附件(如果有的话)
with open(attachment_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attachment_path)))
msg.attach(part)
# 连接SMTP服务器
smtp_server = 'smtp.example.com' # 根据你的邮箱提供商填写
smtp_port = 587 # 或者465 for SSL/TLS (default for Gmail is 465)
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # 如果需要加密连接,添加这行
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully.")
except Exception as e:
print("Error sending email: ", str(e))
# 关闭连接
server.quit()
```
阅读全文