python3:利用SMTP协议发送QQ邮件!室友面前的装逼神技能!

1.发送QQ邮件,首先必须知道QQ邮箱的SMTP服务器

http://service.mail.qq.com/cgi-bin/help?id=28&no=167&subtype=1

 

2.发送邮件之前,必须开启qq邮箱的smtp服务

设置路径:邮箱设置--账户--开启截图服务--保存更改

 

3.代码抛出异常分析

(1)邮箱密码传入值为日常登录密码,报错

global send_user
global email_host
global password
password = 'xxx92'
email_host = "smtp.qq.com"
send_user = "[email protected]"

抛出异常:

smtplib.SMTPAuthenticationError:(535, b'Error: \xc7\xeb\xca\xb9\xd3\xc3\xca\xda\xc8\xa8\xc2\xeb\xb5\xc7\xc2\xbc\xa1\xa3\xcf\xea\xc7\xe9\xc7\xeb\xbf\xb4: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256')

打开抛出异常中的链接:是关于授权码的介绍,根据介绍,登录时应该使用授权码作为登录密码,该处的授权码是开启服务时收到的16位授权码

http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

修改代码:

password = "lunkbrgwqxhfjgxx"(对应的16位授权码)

(2)安全邮件,需要通过SSL发送

server = smtplib.SMTP()
server.connect(email_host,25)

抛出异常:

smtplib.SMTPServerDisconnected: Connection unexpectedly closed

QQ邮箱是支持安全邮件的,需要通过SSL发送的邮件:使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,然后再使用SMTP协议发送邮件

修改代码:

server = smtplib.SMTP_SSL()
server.connect(email_host,465)# 启用SSL发信, 端口一般是465

4.附上完整代码

#coding:utf-8
import smtplib
from email.mime.text import MIMEText
class SendEmail:
 global send_user
 global email_host
 global password
 password = "lunkbrgwqxhfjgxx"
 email_host = "smtp.qq.com"
 send_user = "[email protected]"
 def send_mail(self,user_list,sub,content):
 user = "shape" + "<" + send_user + ">"
 message = MIMEText(content,_subtype='plain',_charset='utf-8')
 message['Subject'] = sub
 message['From'] = user
 message['To'] = ";".join(user_list)
 server = smtplib.SMTP_SSL()
 server.connect(email_host,465)
 server.login(send_user,password)
 server.sendmail(user,user_list,message.as_string())
 server.close()
if __name__ == '__main__':
 send = SendEmail()
 user_list = ['[email protected]']
 sub = "测试邮件"
 content = "ceshi看看"
 send.send_mail(user_list,sub,content)

(1)Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件

(2)构造MIMEText对象时,第一个参数是邮件正文;第二个参数是MIME的subtype,传入'plain'表示纯文本,最终的MIME就是'text/plain';最后一定要用utf-8编码保证多语言兼容性

(3)发送的邮件需要添加头部信息,头部信息中包含发送者、接收者、邮件主题等信息:message['From']、message['To']、message['Subject']

(4)构造完要发送的邮件信息后,通过SMTP发出去:login()方法用来登录SMTP服务器;sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list;邮件正文是一个str,as_string()把MIMEText对象变成str

(5)SMTP.close() :关闭SMTP服务器连接

欢迎关注我的博客或者公众号:https://home.cnblogs.com/u/Python1234/ Python学习交流

 欢迎加入我的千人交流学习群:125240963

猜你喜欢

转载自www.cnblogs.com/Python1234/p/9118363.html
今日推荐