」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Python SMPT 和 Gmail 發送電子郵件很簡單!

使用 Python SMPT 和 Gmail 發送電子郵件很簡單!

發佈於2024-11-13
瀏覽:208

向其他人發送電子郵件是一件重要的事情,在開發中它可以用來發送一些程式碼,如 OTP、PIN、身份驗證等。

最近,我有一個項目,要求我能夠向用戶發送電子郵件以獲取 OTP 代碼,結果證明這非常簡單。

這是我所做的基本步驟:

首先,您需要設定您的Google帳戶,以便能夠透過允許兩步驟驗證(如果完成,請跳過此步驟)來發送電子郵件。

  • 開啟您的 Google 帳戶。
  • 在導覽面板中,選擇安全
  • 在「您如何登入 Google」下,選擇兩步驟驗證,然後選擇開始使用
  • 請依照螢幕上的步驟操作。 開啟兩步驟驗證

其次,建立一個應用程式密碼(16 位元密碼,允許安全性較低的應用程式或裝置存取您的 Google 帳戶)。

  • 確保允許兩步驟驗證。
  • 開啟建立和管理您的應用程式密碼。
  • 新增應用程式的名稱(無論你喜歡什麼),產生的密碼將如下所示: Send Email with Python SMPT and Gmail is Easy!
  • 保存密碼(稍後會用到),不要分享給任何人。

最後,這是 python 中用於發送電子郵件的基本程式碼:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("[email protected]", "yyaz pgow khtd xeqn")


# Create a multipart message
msg = MIMEMultipart()
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
msg['Subject'] = "Subject of the Email"
message = "How are you mate? This is a test email sent using Python"

# Attach the message body
msg.attach(MIMEText(message, 'plain'))

# Send the email
s.send_message(msg)
# terminating the session
s.quit()
  • 使用已設定的Google帳戶(兩步驟驗證)和使用您的電子郵件已產生的應用程式密碼作為參數s.login( ) 就像上面的程式碼一樣。
  • 運行它,這是一個有效的範例:

Send Email with Python SMPT and Gmail is Easy!

如果您遇到任何困難,請隨時提問:)

來源

  • https://stackoverflow.com/questions/75021886/gmail-smtp-send-535-5-7-8-username-and-password-not-accepted
  • https://support.google.com/accounts/answer/185839?sjid=7869472629511530464-AP)
  • https://support.google.com/accounts/answer/185833?hl=en)
版本聲明 本文轉載於:https://dev.to/riparuk/send-email-with-python-smpt-and-gmail-is-easy-3e64?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3