Google SMTP 不太安全的应用程序

Google SMTP less secure applications

我正在尝试使用以下简单的 python 和邮件客户端通过 Google SMTP 服务器发送电子邮件。

我对 Google 将此脚本标记为不安全并要求我允许安全性较低的应用程序访问发件人的 gmail 帐户的部分感到有些困惑。

有什么方法可以解决这个问题,而不必允许安全性较低的应用程序访问我的 gmail 帐户。

#Make necessary imports

import mailclient

#Craft the message
msg = mailclient.Message("This will be the subject", "This will be the body content", 'sender@gmail.com', 'recipient@domain.com')

#Create server object with gmail

s = mailclient.Server('smtp.gmail.com', '587', 'sender@gmail.com', 'senderpassword', True)

#Send email

s.send(msg)

很难说,因为 Google 对于他们所谓的 不安全的应用程序 不是很明确,但我猜他们是使用端口 25 或 587 的应用程序。在这些端口上,连接最初是在未加密的通道上建立的,并且只有在(并且如果)发出 STARTTLS 命令时才会加密。

所以我想你应该尝试在端口 465 上直接通过 SSL 建立连接。我不知道是否可以使用 mailclient 但是对于标准库模块,它应该很简单:

import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = "This will be the subject"
msg['From'] = 'sender@gmail.com'
msg['To'] = [ 'recipient@domain.com' ]
msg.set_content("This will be the body content")

server = smtplib.SMTP_SSL('smtp.gmail.com')
server.login('sender@gmail.com', 'senderpassword')
server.send_message(msg)
server.quit()