我正在尝试使用python发送电子邮件(Gmail),但出现以下错误。
Traceback (most recent call last): File "emailSend.py", line 14, in <module> server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by server.") smtplib.SMTPException: SMTP AUTH extension not supported by server.
Python脚本如下。
import smtplib fromaddr = 'user_me@gmail.com' toaddrs = 'user_you@gmail.com' msg = 'Why,Oh why!' username = 'user_me@gmail.com' password = 'pwd' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit()
你需要EHLO先直接说一下STARTTLS:
EHLO
STARTTLS
server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls()
此外,你应该真正创造From:,To:以及Subject:邮件标题,一个空行,并使用从邮件正文中分离出来CRLF作为EOL标志。
From:,To:
Subject:
CRLF
EOL
例如
msg = "\r\n".join([ "From: user_me@gmail.com", "To: user_you@gmail.com", "Subject: Just a message", "", "Why, oh why" ])
def send_email(user, pwd, recipient, subject, body): import smtplib FROM = user TO = recipient if isinstance(recipient, list) else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() print 'successfully sent the mail' except: print "failed to send mail"
如果要使用端口465,则必须创建一个SMTP_SSL对象:
SMTP_SSL
# SMTP_SSL Example server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465) server_ssl.ehlo() # optional, called by login() server_ssl.login(gmail_user, gmail_pwd) # ssl server doesn't support or need tls, so don't call server_ssl.starttls() server_ssl.sendmail(FROM, TO, message) #server_ssl.quit() server_ssl.close() print 'successfully sent the mail'