Python's Smtplib module is mainly used to send mail, which is more convenient to use.
To use the program to send a message only need to write the following lines of code is OK:
# !/usr/bin/env python Import = smtplib. SMTP (mail server, port) s.login (username, passwd) s.sendmail (fromaddr, Toaddrs, msg)
However, it is not always possible to use this method, the program will always throw an exception when sending mail in this way yesterday:
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.
View Python smtplib.py code
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 AU Thentication 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_aut HS = [Auth_cram_md5, Auth_plain, Auth_login] # Determine the authentication method we ' ll use Authmethod = No Ne 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, R ESP) = Self.docmd (Encode_cram_md5 (RESP, user, password)) elif Authmethod = = Auth_plain: (code, RESP) = Self.docmd ("AUTH", Auth_plain + "" + Encode_plai N (user, password)) elif Authmethod = = Auth_login: (code, RESP) = Self.docmd ("AUTH", "%s%") S "% (Auth_login, encode_base64 (user, eol=" ")))) if code! = 334:raise Smtpauthenticationerror (CO DE, RESP) (code, RESP) = Self.docmd (encode_base64 (password, eol= "")) Elif Authmethod is None:Raise Smtpexception ("No suitable authentication method found.")
The exception is thrown in the above code where the bold, mainly the current connection support server does not support [Auth_cram_md5, Auth_plain, Auth_login]
Any one of the authentication methods, causing problems with the program running.
The solution is to call the STARTTLS () method between initializing SMTP and login, and the complete code is as follows:
#!/usr/bin/env pythonimport smtplibs = smtplib. SMTP (mail server, port) s.starttls () S.login (username, passwd) s.sendmail (fromaddr, Toaddrs, msg)
Python Smtplib authentication issues encountered in sending mail