自动发送给自己邮件,请写出代码
时间: 2023-12-14 16:03:26 浏览: 78
以下是使用Python的smtplib和email库实现自动发送邮件的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
# 发件人邮箱账号
from_addr = 'your_email_address'
# 发件人邮箱密码或授权码
password = 'your_email_password_or_authorization_code'
# 收件人邮箱账号
to_addr = 'your_email_address'
# 创建一个带附件的邮件实例
msg = MIMEMultipart()
# 设置邮件主题、发件人、收件人
msg['Subject'] = 'Test Email'
msg['From'] = from_addr
msg['To'] = to_addr
# 添加文本内容
text = MIMEText('This is a test email.')
msg.attach(text)
# 添加图片附件
with open('test.jpg', 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-Disposition', 'attachment', filename='test.jpg')
msg.attach(img)
# 发送邮件
try:
# 连接SMTP服务器
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(from_addr, password)
# 发送邮件
server.sendmail(from_addr, to_addr, msg.as_string())
print('邮件发送成功!')
except Exception as e:
print('邮件发送失败:', e)
finally:
# 关闭连接
server.quit()
```
在代码中,需要将`from_addr`、`password`和`to_addr`替换为实际的发件人、密码或授权码和收件人邮箱地址。同时,需要将`test.jpg`替换为实际要发送的附件文件名。
阅读全文