python smtplib发送邮件遇到的认证问题
python的smtplib模块主要是用来发送邮件的,使用起来比较方便。
使用程序发送邮件只需要写以下几行代码就OK了:
#!/usr/bin/env python import smtplib s = smtplib.SMTP(mail server, port) s.login(username, passwd) s.sendmail(fromaddr, toaddrs, msg)
不过使用这种方法不一定总是可行,昨天用这种方式发送邮件的时候程序总是会抛异常:
1 2 3 |
|
查看python smtplib.py代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
抛出异常的地方是上面代码中加粗的地方,主要是当前连接支持server并不支持[AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]
中的任何一种认证方式,导致程序运行出现问题。
解决方案是:在初始化SMTP和login之间调用starttls()方法就可以了,完整的代码如下:
1 2 3 4 5 6 |
|