使用QQ邮箱发送email(Python)
实际开发过程中使用到邮箱的概率很高,那么如何借助python使用qq邮箱发送邮件呢?
代码很简单,短短几行代码就可以实现这个功能。
使用到的模块有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
运行结果如下:
大功告成!
上面是网络上转发参考,下面是我的代码
1 #! /usr/bin/env python
2 # -*- coding:utf-8 -*-
3 import smtplib
4 from email.mime.text import MIMEText
5 from email.utils import formataddr
6
7 def sendemail():
8 ret=True
9 try:
10 msg=MIMEText('猴子邮件攻击','plain','utf-8')
11 msg['From']=formataddr(["深深",'117567607@qq.com'])
12 msg['To']=formataddr(["走人",'29447551@qq.com'])
13 msg['Subject']="猴子代码攻击"
14
15 server=smtplib.SMTP_SSL("smtp.qq.com",465)
16 server.login("117567607@qq.com","zklehpgdagbebggh")
17 server.sendmail('117567607@qq.com',['29447551@qq.com',],msg.as_string())
18 server.quit()
19 print('邮件发送成功')
20 ret=True
21 except:
22 ret=False
23 while True:
24 sendemail()