Python 3.x Python,通过Gmail发送电子邮件

Python 3.x Python,通过Gmail发送电子邮件,python-3.x,Python 3.x,我正在尝试使用python通过gmail发送电子邮件 到目前为止,我已经建立了我的gmail帐户,允许使用不太安全的应用程序。不过还是有错误 import smtplib from email.message import EmailMessage def send_mail(to_email, subject, message, server=('smtp.gmail.com', 587), from_email='myemail@gma

我正在尝试使用python通过gmail发送电子邮件

到目前为止,我已经建立了我的gmail帐户,允许使用不太安全的应用程序。不过还是有错误

import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message,
              server=('smtp.gmail.com', 587),
              from_email='myemail@gmail.com'):
    # import smtplib
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(to_email)
    msg.set_content(message)
    print(msg)
    server = smtplib.SMTP(server)
    server.set_debuglevel(1)
    server.login(from_email, 'Password')  # user & password
    server.send_message(msg)
    server.quit()
    print('successfully sent the mail.')


send_mail(to_email=['stackoverflow@gmail.com', 'python10@gmail.com'],
          subject='hello', message='Please Work')
错误消息:

Traceback (most recent call last):
  File "C:/Users/Louis/AppData/Local/Programs/Python/Python36/emailtry.py", line 22, in <module>
    subject='hello', message='Please Work')
  File "C:/Users/Louis/AppData/Local/Programs/Python/Python36/emailtry.py", line 13, in send_mail
    server = smtplib.SMTP(server)
  File "C:\Users\Louis\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Users\Louis\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 324, in connect
    if not port and (host.find(':') == host.rfind(':')):
AttributeError: 'tuple' object has no attribute 'find'

回溯(最近一次呼叫最后一次):
文件“C:/Users/Louis/AppData/Local/Programs/Python/Python36/emailtry.py”,第22行,在
主题为“你好”,信息为“请工作”)
文件“C:/Users/Louis/AppData/Local/Programs/Python/Python36/emailtry.py”,第15行,在send_mail中
服务器登录(通过电子邮件“密码”)#用户和密码
文件“C:\Users\Louis\AppData\Local\Programs\Python\Python36\lib\smtplib.py”,第697行,登录
“服务器不支持SMTP身份验证扩展。”)
smtplib.SMTPNotSupportedError:服务器不支持SMTP验证扩展名。
>>> 

smtplib.SMTP
构造函数希望服务器主机和端口作为单独的参数,而不是元组。将呼叫更改为:

    server = smtplib.SMTP(server[0], server[1])
谷歌要求客户端在认证前打开加密。这就是错误消息令人困惑的原因:在未加密状态下,
AUTH
扩展实际上不受支持。在调用
server.login
之前,添加:

server.starttls()

这看起来很正常。这是来自服务器的“问候语”,表示它已准备好接受消息。我认为显示的原因是调试级别-使脚本打印与服务器交互。我编辑了问题,以包含我得到的完整错误消息。对,在尝试登录之前需要打开加密。我更新了答案。非常感谢你。
    server = smtplib.SMTP(server[0], server[1])
server.starttls()