使用python发送automail
时间: 2023-10-24 19:13:46 浏览: 142
以下是使用Python发送电子邮件的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
# 邮件发送方
sender = 'your_email@example.com'
# 邮件接收方
receiver = 'recipient_email@example.com'
# 邮件主题
subject = 'This is a test email'
# 邮件正文
body = 'Hello, this is a test email.'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
# 添加图片附件
with open('image.png', 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name='image.png')
msg.attach(image)
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'your_email@example.com'
smtp_password = 'your_password'
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls()
smtp_obj.login(smtp_user, smtp_password)
smtp_obj.sendmail(sender, receiver, msg.as_string())
smtp_obj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("邮件发送失败")
```
请注意替换`sender`、`receiver`、`smtp_server`、`smtp_user`和`smtp_password`等变量的值。此外,您还需要确保您的SMTP服务器允许使用Python发送邮件。
阅读全文