目录
发送邮件的流程
邮件的发送协议
smtplib模块
email包
demo
发送html邮箱
发送带附件的邮箱
发送定时邮件schedule模块
发送邮件的流程

邮件的发送协议
- smtp是邮件的发送协议
- pop3是邮件的接受协议
- 协议就是一种规则,已经被底层网络封装好了,无需关心他的具体规则,直接使用上层工具即可
smtplib模块
python自带无需安装
import smtplib
#创建协议对象
smtpObj=smtplib.SMTP()
#创建链接,25端口号
smtpObj.connect(smtp服务器地址,25)
#登录验证
smtpObj.login(mail_user,mail_pass)
#发送邮件
smtpObj.sendmail(sender,receivers,message)
email包

demo
1. 需要注意内容:发生邮箱需要开通smtp与pop3的访问许可,否则发生不出去,每个邮箱开通的方法自行百度,下方只是只是演示了qq邮箱的
2.需要授权码和密码
3.有些邮箱开通可能会收费
# coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#声明使用邮箱协议,使用qq邮箱
mail_host="smtp.qq.com"
mail_user="2211910447@qq.com"
#qq邮箱授权码获取:1.需要开通smtp>(qq邮箱设置>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务>开启获取授权码)
mail_pass="goxcqlvjgnggdjii"
#定义发送者
sender="2211910447@qq.com"
#定义接受者
receivers=["15837174334@163.com"]
#第一个参数邮件内容,第二个参数:文件类型:plain 普通邮箱 第三个参数:编码
#message=MIMEText("标题-测试","plain","utf-8")
message=MIMEText("<p style='color:red'>标题-测试</p>","html","utf-8")
#定义发送者
message["From"]=Header(sender)
#定义发送内容
message["Subject"]=Header("邮件标题","utf-8")
print("发送邮件内容:",message.as_string())
try:
smtpobj=smtplib.SMTP()
smtpobj.connect(mail_host,25)
smtpobj.login(mail_user,mail_pass)
smtpobj.sendmail(sender,receivers,message.as_string())
except smtplib.SMTPException as e:
print("error:",e)
发送html邮箱
.
message=MIMEText("<p style='color:red'>标题-测试</p>","html","utf-8")
发送带附件的邮箱

# coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
#声明使用邮箱协议,使用qq邮箱
mail_host="smtp.qq.com"
mail_user="xxxx@qq.com"
#qq邮箱授权码获取:1.需要开通smtp>(qq邮箱设置>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务>开启获取授权码)
mail_pass=""
#定义发送者
sender="xxxxx@qq.com"
#定义接受者
receivers=["xxxxx@163.com"]
#第一个参数邮件内容,第二个参数:文件类型:plain 普通邮箱 第三个参数:编码
#message=MIMEText("标题-测试","plain","utf-8")
message=MIMEMultipart()
#定义发送者
message["From"]=Header(sender)
#定义发送内容
message["Subject"]=Header("邮件标题","utf-8")
#发送附件
attr=MIMEText(open("send_email.py","rb").read(),"base64","utf-8")
attr["Content-Type"]= "application/octet-stream"
attr["Content-Disposition"]= "attachment;filename='send_email.py'"
message.attach(attr)
message.attach(MIMEText("<p style='color:red'>标题-测试</p>","html","utf-8"))
print("发送邮件内容:",message.as_string())
try:
smtpobj=smtplib.SMTP()
smtpobj.connect(mail_host,25)
smtpobj.login(mail_user,mail_pass)
smtpobj.sendmail(sender,receivers,message.as_string())
except smtplib.SMTPException as e:
print("error:",e)
发送定时邮件schedule模块
1. 在特定时间执行的一些内容;
2.安装 pip install schedule



# coding:utf-8
import smtplib
import time
import schedule
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
def send():
#发送邮件代码...
if __name__ == '__main__':
schedule.every(10).seconds.do(send)
while 1:
schedule.run_pending()
time.sleep(1)



















