it-swarm.cn

如何使用Python以Gmail作为提供商发送电子邮件?

我正在尝试使用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 = '[email protected]'
toaddrs  = '[email protected]'
msg = 'Why,Oh why!'
username = '[email protected]'
password = 'pwd'
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
257
Mahori

在直接进入EHLO之前你需要说STARTTLS

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()

此外,您应该创建From:To:Subject:消息标题,通过空行与消息正文分隔,并使用CRLF作为EOL标记。

例如。

msg = "\r\n".join([
  "From: [email protected]",
  "To: [email protected]",
  "Subject: Just a message",
  "",
  "Why, oh why"
  ])
197
MattH
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 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'
277
David Okwii

我遇到了类似的问题,偶然发现了这个问题。我收到了SMTP身份验证错误,但我的用户名/密码是正确的。这是修复它的原因。我看了这个:

https://support.google.com/accounts/answer/6010255

简而言之,谷歌不允许您通过smtplib登录,因为它已将此类登录标记为“不太安全”,因此您需要做的就是在登录Google帐户时转到此链接,并允许访问:

https://www.google.com/settings/security/lesssecureapps

设置完成后(请参阅下面的屏幕截图),它应该可以正常工作。

enter image description here

现在登录有效:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

更改后的回复:

(235, '2.7.0 Accepted')

事先回复:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

仍然无法正常工作? 如果你仍然得到SMTPAuthenticationError,但现在代码是534,因为它的位置是未知的。点击此链接:

https://accounts.google.com/DisplayUnlockCaptcha

单击“继续”,这将为您提供10分钟的注册新应用程序。所以现在继续进行另一次登录尝试,它应该工作。

_ update _ :这似乎无法正常工作你可能会在smptlib中遇到这个错误一段时间:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

消息说使用浏览器登录:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

启用'lesssecureapps'后,去喝咖啡,回来,再次尝试'DisplayUnlockCaptcha'链接。根据用户体验,更改可能需要一个小时才能启动。然后再次尝试登录过程。

123
radtek

你有OOP吗?

#!/usr/bin/env python


import smtplib

class Gmail(object):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.server = 'smtp.gmail.com'
        self.port = 587
        session = smtplib.SMTP(self.server, self.port)        
        session.ehlo()
        session.starttls()
        session.ehlo
        session.login(self.email, self.password)
        self.session = session

    def send_message(self, subject, body):
        ''' This must be removed '''
        headers = [
            "From: " + self.email,
            "Subject: " + subject,
            "To: " + self.email,
            "MIME-Version: 1.0",
           "Content-Type: text/html"]
        headers = "\r\n".join(headers)
        self.session.sendmail(
            self.email,
            self.email,
            headers + "\r\n\r\n" + body)


gm = Gmail('Your Email', 'Password')

gm.send_message('Subject', 'Message')
16
Ricky Wilson

你可以在这里找到它: http://jayrambhia.com/blog/send-emails-using-python

smtp_Host = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP()
server.connect(smtp_Host,smtp_port)
server.ehlo()
server.starttls()
server.login(user,passw)
fromaddr = raw_input('Send mail by the name of: ')
tolist = raw_input('To: ').split()
sub = raw_input('Subject: ')

msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = email.Utils.COMMASPACE.join(tolist)
msg['Subject'] = sub  
msg.attach(MIMEText(raw_input('Body: ')))
msg.attach(MIMEText('\nsent via python', 'plain'))
server.sendmail(user,tolist,msg.as_string())
14
Froyo

没有直接相关但仍然值得指出的是,我的包尝试使发送gmail消息非常快速和轻松。它还尝试维护错误列表并尝试立即指向解决方案。

它实际上只需要这个代码就可以完全按照你所写的那样做:

import yagmail
yag = yagmail.SMTP('[email protected]')
yag.send('[email protected]', 'Why,Oh why!')

或者一个班轮:

yagmail.SMTP('[email protected]').send('[email protected]', 'Why,Oh why!')

对于软件包/安装,请查看 gitpip ,可用于Python 2和3。

11
PascalVKooten

这个作品

创建Gmail APP密码!

创建后,然后创建一个名为sendgmail.py的文件

然后添加此代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Created By  : Jeromie Kirchoff
# Created Date: Mon Aug 02 17:46:00 PDT 2018
# =============================================================================
# Imports
# =============================================================================
import smtplib

# =============================================================================
# SET EMAIL LOGIN REQUIREMENTS
# =============================================================================
gmail_user = '[email protected]'
gmail_app_password = 'YOUR-GOOGLE-APPLICATION-PASSWORD!!!!'

# =============================================================================
# SET THE INFO ABOUT THE SAID EMAIL
# =============================================================================
sent_from = gmail_user
sent_to = ['[email protected]', '[email protected]']
sent_subject = "Where are all my Robot Women at?"
sent_body = ("Hey, what's up? friend!\n\n"
             "I hope you have been well!\n"
             "\n"
             "Cheers,\n"
             "Jay\n")

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(sent_to), sent_subject, sent_body)

# =============================================================================
# SEND EMAIL OR DIE TRYING!!!
# Details: http://www.samlogic.net/articles/smtp-commands-reference.htm
# =============================================================================

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_app_password)
    server.sendmail(sent_from, sent_to, email_text)
    server.close()

    print('Email sent!')
except Exception as exception:
    print("Error: %s!\n\n" % exception)

所以,如果你成功了,会看到这样的图像:

我通过向自己发送电子邮件进行测试。

Successful email sent.

注意:我的帐户已经 两步验证 启用。 App密码适用于此!

此设置不适用于启用了两步验证的帐户。此类帐户需要特定于应用程序的密码才能访问安全性较低的应用.

Less secure app access... This setting is not available for accounts with 2-Step Verification enabled.

5
JayRizzo

来自@David的很好的答案,这里是没有通用try-except的Python 3:

def send_email(user, password, recipient, subject, body):

    gmail_user = user
    gmail_pwd = password
    FROM = user
    TO = recipient if type(recipient) is 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)

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(FROM, TO, message)
    server.close()
2
juan Isaza

现在有一个gmail API,它允许您通过REST发送电子邮件,阅读电子邮件和创建草稿。与SMTP调用不同,它是非阻塞的,对于基于线程的Web服务器在请求线程中发送电子邮件(如python webservers)可能是一件好事。 API也非常强大。

  • 当然,电子邮件应该移交给非网络服务器队列,但是很高兴有选择权。

如果您拥有域名的Google Apps管理员权限,则最容易进行设置,因为这样您就可以为您的客户授予一揽子权限。否则,您必须使用OAuth身份验证和权限。

这是一个Gist演示它:

https://Gist.github.com/timrichardson/1154e29174926e462b7a

2
Tim Richardson

好像是旧smtplib的问题。在python2.7中一切正常。

更新 :是的,server.ehlo()也可以提供帮助。

1
mega.venik