python 发送tsl加密邮件

来源:互联网 发布:阿里云费用 编辑:程序博客网 时间:2024/05/20 09:09


python版本测试通过。但是我在用expect实现,在tsl加密之后,不知道该怎么处理了。

两个都帖进来。

#!/usr/bin/env python#-*-coding = UTF-8-*-import smtplib, mimetypesfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.image import MIMEImageimport sys,sockettoaddr = "xxx@xxx"msg = MIMEMultipart()msg['From'] = "no-reply@xxx.com"msg['To'] = toaddrmsg['Subject'] = 'this is letter subject'fileName = r'test.jpg'ctype, encoding = mimetypes.guess_type(fileName)if ctype is None or encoding is not None:    ctype = 'application/octet-stream'maintype, subtype = ctype.split('/', 1)att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype = subtype)att1.add_header('Content-Disposition', 'attachment', filename = fileName)msg.attach(att1) s = smtplib.SMTP("xxx.xxx.com",xxx)try:    code = s.ehlo()[0]    if code != 250:        usesesntp = 0        code = s.helo()[0]        if not code != 250:            raise SMTPHeloError(code,resp)    if s.has_extn('starttls'):        code = s.starttls()        code = s.ehlo()[0]        if code != 250:            print "Couldn't EHLO after STARTTLS."            sys.exit(1)    else:        print "Server does not suport TLS; using normal connection."        sys.exit(1)    if s.has_extn('auth'):        try:            s.login('xxx','xxx')        except smtplib.SMTPException,e:            print "Authentication failed:",e            sys.exit(1)    else:        print "Server does not suport Authentication; using normal connect."        sys.exit(1)    #if usesesmtp and s.has_extn('size'):        #print "Maxinum message size is ",s.esmtp_features['size']    s.sendmail("no-reply@xxx.com",toaddr,message)except(socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:    print "***Your message may not have been sent!"    print e    sys.exit(1)else:    print "***Message successful sent to %d recipient(s)" % len(toaddr)

下面的是expect版本的


#!/usr/bin/expectset smtp   xxx.xxx.xxxset user   xxxxxset pass   xxxxxset from   no-reply@xxx.comset to     xxxset title  testtitle!set content testcontent!spawn telnet $smtp 587expect "221"send "HELO LOCALHOST\r"expect "250"send "STARTTLS\r"expect "220"send "HELO LOCALHOST\r"expect "250"send "AUTH LOGIN\r"expect "334"send "$user\r"expect "334"send "$pass\r"expect "235"send "MAIL FROM: <$from>\r"expect "250"send "RCPT TO: <$to>\r"expect "250"send "DATA\r"expect "354"send "TO: $to\r"send "FROM: $from\r"send "SUBJECT: $title\r"send "Content-Type: text/html; charset=\"UTF-8\"\r"send "\r"send "$content\r"send ".\r"expect "250"send "QUIT"