python smtplib發送郵件遇到的認證問題

來源:互聯網
上載者:User

標籤:

python的smtplib模組主要是用來發送郵件的,使用起來比較方便。

使用程式發送郵件只需要寫以下幾行代碼就OK了:

#!/usr/bin/env pythonimport smtplibs = smtplib.SMTP(mail server, port)s.login(username, passwd)s.sendmail(fromaddr, toaddrs, msg)

不過使用這種方法不一定總是可行,昨天用這種方式發送郵件的時候程式總是會拋異常:

  File "/usr/lib64/python2.7/smtplib.py", line 617, in login    raise SMTPException("No suitable authentication method found.")smtplib.SMTPException: No suitable authentication method found.

查看python smtplib.py代碼

        if not self.has_extn("auth"):            raise SMTPException("SMTP AUTH extension not supported by server.")        # Authentication methods the server supports:        authlist = self.esmtp_features["auth"].split()        # List of authentication methods we support: from preferred to        # less preferred methods. Except for the purpose of testing the weaker        # ones, we prefer stronger methods like CRAM-MD5:        preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]        # Determine the authentication method we‘ll use        authmethod = None        for method in preferred_auths:            if method in authlist:                authmethod = method                break        if authmethod == AUTH_CRAM_MD5:            (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)            if code == 503:                # 503 == ‘Error: already authenticated‘                return (code, resp)            (code, resp) = self.docmd(encode_cram_md5(resp, user, password))        elif authmethod == AUTH_PLAIN:            (code, resp) = self.docmd("AUTH",                AUTH_PLAIN + " " + encode_plain(user, password))        elif authmethod == AUTH_LOGIN:            (code, resp) = self.docmd("AUTH",                "%s %s" % (AUTH_LOGIN, encode_base64(user, eol="")))            if code != 334:                raise SMTPAuthenticationError(code, resp)            (code, resp) = self.docmd(encode_base64(password, eol=""))        elif authmethod is None:            raise SMTPException("No suitable authentication method found.")

拋出異常的地方是上面代碼中加粗的地方,主要是當前串連支援server並不支援[AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]

中的任何一種認證方式,導致程式運行出現問題。

 

解決方案是:在初始化SMTP和login之間調用starttls()方法就可以了,完整的代碼如下:

#!/usr/bin/env pythonimport smtplibs = smtplib.SMTP(mail server, port)s.starttls()s.login(username, passwd)s.sendmail(fromaddr, toaddrs, msg)

 

python smtplib發送郵件遇到的認證問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.