使用 Python 透過 Gmail 發送電子郵件可能是一項簡單的任務,但有時您可能會遇到錯誤。此類錯誤之一是「伺服器不支援 SMTP AUTH 擴充功能」。當您嘗試使用 login() 方法登入 Gmail 帳戶時,就會發生這種情況。
要解決此問題,需要修改您的 Python 腳本。將嘗試呼叫 login() 方法的程式碼替換為以下內容:
import smtplib def send_email(user, pwd, recipient, subject, body): 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")
或者,您可以選擇透過實作 SMTP_SSL 物件來使用連接埠 465:
# 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')
以上是使用Python和Gmail發送電子郵件時如何解決「伺服器不支援SMTP AUTH擴充」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!