Python使用QQ邮箱发送Email的方法实例

yipeiwu_com6年前Python基础

前言

其实Python使用QQ邮箱发送Email代码很简单,短短几行代码就可以实现这个功能。

使用到的模块有smtplib和email这个两个模块,关于这两个模块的方法就不多说了。不了解的朋友们可以查看这篇文章:python中使用smtplib和email模块发送邮件实例

我们先说说网上常用的使用这那两个模块发送邮件的方法

代码如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def SendEmail(fromAdd, toAdd, subject, attachfile, htmlText):
 strFrom = fromAdd;
 strTo = toAdd;
 msg =MIMEText(htmlText);
 msg['Content-Type'] = 'Text/HTML';
 msg['Subject'] = Header(subject,'gb2312');
 msg['To'] = strTo;
 msg['From'] = strFrom;
 
 smtp = smtplib.SMTP('smtp.qq.com');
 smtp.login('501257367@qq.com','password');
 try:
 smtp.sendmail(strFrom,strTo,msg.as_string());
 finally:
 smtp.close;

if __name__ == "__main__":
 SendEmail("501257367@qq.com","501257367@qq.com","","hello","hello world");

运行结果:

smtplib.SMTPAuthenticationError: (530, 'Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28')

报错,需要一个安全的连接,例如SSL,因此接下来我们会使用SSL的方式去登录,但是在那之前,我们需要做一些准备,打开qq邮箱,点击设置->

账户,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,开启IMAP/SMTP服务,然后根据要求使用手机发送到指定号码,获取授权码,

这个授权码就是你接下来登录要使用的密码,配置完成,上代码

import smtplib
from email.mime.text import MIMEText
_user = "你的qq邮箱"
_pwd = "你的授权码"
_to = "501257367@163.com"

msg = MIMEText("Test")
msg["Subject"] = "don't panic"
msg["From"] = _user
msg["To"] = _to

try:
 s = smtplib.SMTP_SSL("smtp.qq.com", 465)
 s.login(_user, _pwd)
 s.sendmail(_user, _to, msg.as_string())
 s.quit()
 print "Success!"
except smtplib.SMTPException,e:
 print "Falied,%s"%e 

运行结果如下:


总结

好了,大功告成!以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流。

相关文章

python中reduce()函数的使用方法示例

python中reduce()函数的使用方法示例

前言 本文主要给大家介绍了关于python中reduce()函数使用的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: reduce()函数在库functools...

在SQLite-Python中实现返回、查询中文字段的方法

博主在这个问题上卡了挺久的,贴出来解决方法帮助需要的朋友,直接上代码(测试环境:win10+Python2.7): # coding=utf-8 import sqlite3...

python装饰器实例大详解

一.作用域 在python中,作用域分为两种:全局作用域和局部作用域。  全局作用域是定义在文件级别的变量,函数名。而局部作用域,则是定义函数内部。  关于作用域,我们要理解两点:   ...

详解DeBug Python神级工具PySnooper

PySnooper 在 GitHub 上自嘲是一个“乞丐版”调试工具(poor man's debugger)。 一般情况下,在编写 Python 代码时,如果想弄清楚为什么 Pytho...

python的re模块使用方法详解

一、正则表达式的特殊字符介绍 正则表达式 ^ 匹配行首 $ 匹配行尾 . 任意...