2013-06-26 262 views
4

我想通过使用Python 3发送电子邮件。我还没有理解我见过的例子。这里有一个参考:Python 3 |发送电子邮件 - SMTP - Gmail - 错误:SMTPException

我拉了上面的参考找到第一个简单的例子。我发现这个例子很好地代表了我在互联网上看到的例子的组合。这似乎是我正在做的事情的基本形式。

当我尝试下面的代码,我收到错误:

File "C:\Python33\Lib\email.py", line 595, in login 
    raise SMTPException("SMTP AUTH extension not supported by server.") 
smtplib.SMTPException: SMTP AUTH extension not supported by server. 

下面是代码:

# Send Mail 

import smtplib 
server = smtplib.SMTP('smtp.gmail.com', 587) 

# Log in to the server 
server.login("[email protected]","myPassword") 

# Send mail 
msg = "\nHello!" 
server.sendmail("[email protected]","[email protected]", msg) 

回答

17

我在YouTube上发现一个解决方案。

这里是video link

# smtplib module send mail 

import smtplib 

TO = '[email protected]' 
SUBJECT = 'TEST MAIL' 
TEXT = 'Here is a message from python.' 

# Gmail Sign In 
gmail_sender = '[email protected]' 
gmail_passwd = 'password' 

server = smtplib.SMTP('smtp.gmail.com', 587) 
server.ehlo() 
server.starttls() 
server.login(gmail_sender, gmail_passwd) 

BODY = '\r\n'.join(['To: %s' % TO, 
        'From: %s' % gmail_sender, 
        'Subject: %s' % SUBJECT, 
        '', TEXT]) 

try: 
    server.sendmail(gmail_sender, [TO], BODY) 
    print ('email sent') 
except: 
    print ('error sending mail') 

server.quit() 
2

截至10月中旬2017的,Gmail是不经由smtplib.SMTP()端口587接受连接,但需要smtplib.SMTP_SSL()和端口465。立即开始TLS,不需要ehlo。请尝试使用此代码段:

# Gmail Sign In 
gmail_sender = '[email protected]' 
gmail_passwd = 'password' 

server = smtplib.SMTP_SSL('smtp.gmail.com', 465) 
server.login(gmail_sender, gmail_passwd) 

# build and send the email body.