pyhton 自动化邮件发送脚本
时间: 2023-09-22 13:06:55 浏览: 102
可以通过使用Python中的smtplib和email模块来自动化发送邮件。下面是一个简单的示例代码片段:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# 邮箱登录信息
sender_email = "sender@gmail.com"
sender_password = "password"
# 收件人信息
receiver_email = "receiver@gmail.com"
subject = "这是一封测试邮件"
body = "你好,这是一封自动化发送的测试邮件!"
# 创建邮件体
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = subject
# 添加邮件正文
message.attach(MIMEText(body, 'plain'))
# 添加附件
filename = "example.txt"
attachment = open(filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
message.attach(part)
# 发送邮件
smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
smtp_server.starttls()
smtp_server.login(sender_email, sender_password)
text = message.as_string()
smtp_server.sendmail(sender_email, receiver_email, text)
smtp_server.quit()
```
使用这个脚本可以发送带有正文和附件的邮件,你需要将sender_email和sender_password更改为你自己的邮箱地址和密码,并将receiver_email更改为收件人的邮箱地址。同时,你需要保证你的发件人邮箱开启了SMTP服务。
阅读全文