SMTP协议
SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送邮件,不能用来接收邮件,而大多数的邮件发送服务器都是使用SMTP协议。SMTP协议的默认TCP端口号是25。
STMP环境调试
上面说了是使用SMTP协议发送的邮件,所以需要先查看你的发件人邮箱是否有开启SMTP协议,如没有,则需要开启,我测试使用的是qq.com的邮箱作为发信人邮箱,在设置中开启SMTP协议如下图所示。
image
检查开发环境是否存在smtplib
python之所以这么受欢迎,一大特点是因为它拥有很多模块,编程就好像玩乐高积木一样。好了废话不多说,我们先检查python是否安装了这个模块,进入python的交互模式,执行 improt smtplib ,如下报错,证明环境中不存在此模块,需要额外安装。
[root@node1 ~]# python Python 2.7.5 (default, Jul 13 2018, 13:06:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> improt smtplib File "<stdin>", line 1 improt smtplib ^ SyntaxError: invalid syntax >>>
安装smtplib模块
利用pip安装简单方便,直接执行 pip install PyEmail 。安装好之后,在交互模式下执行,如下:
[root@node1 ~]# python Python 2.7.5 (default, Jul 13 2018, 13:06:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import smtplib
学以致用
进群:960410445 即可获取源码!
import smtplib from email.mime.text import MIMEText def sendEmail(from_addr,passwd,subject,content,to_addr): msg=MIMEText(content) msg['Subject']=subject msg['From']=from_addr msg['to']=to_addr try: s=smtplib.SMTP_SSL("smtp.qq.com",465) s.login(from_addr,passwd) s.sendmail(from_addr,to_addr,msg.as_string()) print("发送成功") except s.SMTPException: print("发送失败") finally: s.quit() if __name__ == '__main__': from_addr="发件人邮箱地址" passwd="密码" subject="主题" content="内容" to_addr='收件人邮箱地址'