Python使用smtplib模块发送电子邮件的流程详解
1、登录SMTP服务器 import smtplib server = smtplib.SMTP('smtp.163.com',25) server.login('j_hao104@163.com','password') Traceback (most recent call last): File "C:/python/t.py",line 192,in <module> server.login('j_hao104@163.com','password') File "C:Python27libsmtplib.py",line 622,in login raise SMTPAuthenticationError(code,resp) smtplib.SMTPAuthenticationError: (535,'Error: authentication failed') 发现返回: smtplib.SMTPAuthenticationError: (535,'Error: authentication failed') ,提示验证失败。 import smtplib server = smtplib.SMTP('smtp.163.com','clientPassword') 此时便返回登录成功提示: (235,'Authentication successful') 2、发送邮件 首先使用网上给出的代码: import smtplib from email.mime.text import MIMEText server = smtplib.SMTP('smtp.163.com','clientPassword') msg = MIMEText('hello,send by Python...','plain','utf-8') server.sendmail('j_hao104@163.com',['946150454@qq.com'],msg.as_string()) 构造MIMEText对象时,第一个参数是邮件正文,第二个参数是MIME的subtype,最后个是编码方式。 而是: Traceback (most recent call last): File "C:/python/t.py",line 195,in <module> server.sendmail('j_hao104@163.com',msg.as_string()) File "C:Python27libsmtplib.py",line 746,in sendmail raise SMTPDataError(code,resp) smtplib.SMTPDataError: (554,'DT:SPM 163 smtp11,D8CowEDpDkE427JW_wQIAA--.4996S2 1454562105,please see http://mail.163.com/help/help_spam_16.htm?ip=171.221.144.51&hostid=smtp11&time=1454562105') 网上一查才知道:smtplib.SMTPDataError: (554,'DT:SPM 163 smtp11……的错误是因为信封发件人和信头发件人不匹配。可以看出看出图片中并没有发件人和主题,所以需要对代码做如下修改: import smtplib from email.header import Header from email.mime.text import MIMEText server = smtplib.SMTP('smtp.163.com','utf-8') msg['From'] = 'j_hao104@163.com <j_hao104@163.com>' msg['Subject'] = Header(u'text','utf8').encode() msg['To'] = u'飞轮海 <jinghao5849312@qq.com>' server.sendmail('j_hao104@163.com',msg.as_string()) 这样就能成功发出邮件啦 3、参考示例 import smtplib from email.mime.text import MIMEText to_list = ['123@123.com','456@456.com'] server_host = 'smtp.163.com' username = '你的邮箱账号' password = '你的邮箱密码' def send(to_list,sub,content): ''' :param to_list: 收件人邮箱 :param sub: 邮件标题 :param content: 内容 ''' me = "manager" + "<" + username + ">" # _subtype 可以设为html,默认是plain msg = MIMEText(content,_subtype='html') msg['Subject'] = sub msg['From'] = me msg['To'] = ';'.join(to_list) try: server = smtplib.SMTP() server.connect(server_host) server.login(username,password) server.sendmail(me,to_list,msg.as_string()) server.close() except Exception as e: print str(e) if __name__ == '__main__': send(to_list,"这个是一个邮件","<h1>Hello,It's test email.</h1>") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |