python tls/ssl email (自动判断是否支持tls)

#from: http://blog.chinaunix.net/u/19742/showart_422492.html

 

# - * - coding: cp936 - * -
#! / usr/ bin/ env python
import sys, smtplib
"" "
使用smtp.sina.com作为邮件发送服务器
1.使用TLS进行加密
2.使用ehlo,如果服务器不支持,则无法使用TLS
3.调用starttls
4.再次调用ehlo
5.像往常一样发送邮件
"
""
server = "smtp.sina.com"
fromaddr= "[email protected]"
toaddr = "[email protected]"

msg = "" "
to:%s
from:%s
Hello,I am smtp server
"
"" % ( toaddr, fromaddr)

s = smtplib. SMTP( server)
# 进行认证,通过后可以发送邮件
s. login( "jcodeer" , "邮箱密码" )
"" "
ehlo返回值:
code:来自服务器的相应码。
string:这个响应码所对应的字符串描述。
"
""
code = s. ehlo( ) [ 0]
usesesmtp = 1
if not ( 200 < = code < = 299) :
    usesesmtp = 0
    "" "
    code和string与ehlo含义相同。
    "
""
    code = s. helo( ) [ 0]
    if not ( 200 < = code < = 299) :
        raise SMTPHeloError( code, resp)
if usesesmtp and s. has_extn( "tls" ) :
    "" "支持tls,则调用starttls(3)" ""
    print ( "starttls" )
    s. starttls( )
    "" "再次调用ehlo(4)" ""
    code = s. ehlo( ) [ 0]
    if not ( 200 < = code < = 299) :
        print ( "Could not EHLO after starttls" )
        sys. exit( 5)
    print ( "using tls connection" )
else :
    "" "不支持tls,使用正常连接(2)" ""
    print ( "server does not support tls,using normal connection" )
"" "发送邮件(5)" ""
s. sendmail( fromaddr, toaddr, msg)

你可能感兴趣的:(加密,server,python,String,服务器,email)