我正在尝试使用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'
有人可以帮我解决我所缺少的吗?
编辑
随着服务器的更改,我现在得到了
send: 'ehlo Louis-PC.hitronhub.home\r\n'
reply: b'250-smtp.gmail.com at your service, [2607:fea8:5b9f:f9c5:6d68:a665:373b:b92a]\r\n'
reply: b'250-SIZE 35882577\r\n'
reply: b'250-8BITMIME\r\n'
reply: b'250-STARTTLS\r\n'
reply: b'250-ENHANCEDSTATUSCODES\r\n'
reply: b'250-PIPELINING\r\n'
reply: b'250-CHUNKING\r\n'
reply: b'250 SMTPUTF8\r\n'
reply: retcode (250); Msg: b'smtp.gmail.com at your service, [2607:fea8:5b9f:f9c5:6d68:a665:373b:b92a]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8'
和
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 15, in send_mail
server.login(from_email, 'Password') # user & password
File "C:\Users\Louis\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 697, in login
"SMTP AUTH extension not supported by server.")
smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.
>>>
答案 0 :(得分:2)
smtplib.SMTP
构造函数期望服务器主机和端口作为单独的参数,而不作为元组。将呼叫更改为:
server = smtplib.SMTP(server[0], server[1])
Google要求客户端在身份验证之前打开加密。这就是造成错误消息的原因:实际上,在未加密状态下,不支持AUTH
扩展名。在server.login
调用之前,添加:
server.starttls()