python 向qq邮箱发邮件

#coding:utf-8
'''
Created on 2017-1-12

@author: xiaochun
'''
import smtplib
from email.mime.text import MIMEText

mail_host = "smtp.qq.com:465" 		 #qq邮件服务器地址
mail_host = "smtp.exmail.qq.com:465" #企业邮箱邮件服务器地址

mail_to_list = ["52521866@qq.com"] #收件人列表

#发送方信息
mail_user = "75813287@qq.com"
mail_pass = "XXXXXX"


#邮件标题
mail_sub = "这是标题"

#邮件文本内容
mail_content = "这是内容"


def send_mail(mail_to_list,mail_sub,mail_content):
	msg = MIMEText(mail_content)
	msg['Subject'] = mail_sub
	msg['From'] = mail_user
	msg['To'] = ";".join(mail_to_list)
	msg['Cc'] = ";".join(mail_cc_list) #抄送
	receive = mail_to_list
	receive.extend(mail_cc_list)
try:
	server = smtplib.SMTP_SSL(mail_host)
	server.login(mail_user,mail_pass)
	server.sendmail(mail_user,receive,msg.as_string())
	server.close()
	return True
except Exception, e:
	print str(e)
	return False

if __name__ == '__main__':
	if send_mail(mail_to_list, mail_sub, mail_content):
		print "send success"
	else:
		print "send failed"

运行结果:

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服务,然后根据要求使用手机发送到指定号码,获取授权码,
这个授权码就是你接下来登录要使用的密码。

然后把

server = smtplib.SMTP('smtp.qq.com') 改成 server = smtplib.SMTP_SSL('smtp.qq.com:465')

运行结果:

 

posted @ 2017-01-13 10:04  那一剑的風情  阅读(449)  评论(0编辑  收藏  举报