一、安装python的email、smtplib包
ubuntu安装sendmail:
https://cloud.tencent.com/developer/article/1608855
pip install email 报错解决办法:
https://blog.youkuaiyun.com/yechi9142/article/details/105150603
python pip安装smtplib库的方法:
https://blog.youkuaiyun.com/qq_40833182/article/details/82504163
二、生成smtp对象,调用SMTP简易邮件服务
可在服务器自行安装、也可以开启163.com和qq.com邮箱的smtp服务,直接调用即可。
开启163邮箱的SMTP服务:
https://jingyan.baidu.com/article/c275f6ba33a95de33d7567d9.html
三、向指定邮箱发送邮件
四、示例代码
#! /usr/bin/env python
#coding=utf-8
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
def send_error_email(receiver = 'xxxxxxxxx@qq.com',errorcontent="服务器"):
#qq邮箱smtp服务器
host_server = 'smtp.163.com'
#sender_qq为发件人的qq号码
sender_qq = 'xxxxxxxxx@163.com'
#pwd为163邮箱的授权码
pwd = 'ABCDEFGHIJKLMN'
#发件人的邮箱
sender_mail = 'xxxxxxxxx@163.com'
#收件人邮箱
receiver = receiver
#邮件的正文内容
mail_content = '你好,xx网站'+errorcontent+'貌似出了点状况,请及时进行维护!'
#邮件标题
mail_title = 'xx网站-服务器情况反馈邮件'
#ssl登录
smtp = SMTP_SSL(host_server)
#set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
smtp.set_debuglevel(1)
smtp.ehlo(host_server)
smtp.login(sender_qq, pwd)
msg = MIMEText(mail_content, "plain", 'utf-8')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq_mail
msg["To"] = receiver
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
print("邮件发送成功!")
本文介绍了如何在Python中通过email和smtplib库发送SMTP邮件,包括安装所需包、生成SMTP对象、开启SMTP服务及示例代码。示例展示了使用163邮箱发送邮件的过程。
648





