以下文章會介紹用 Python 使用 smtplib 連接到 Gmail 的 SMTP 伺服器, 並發出電子郵件的方法。
但在開始前, Google 帳號是使用雙重認證密碼, 如果直接在 Python code 內輸入 Google 密碼, 會回傳以下報錯:
smtplib.SMTPAuthenticationError: (534, b’5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor q29-20020aa7983d000000b0056c47a5c34dsm3753436pfl.122 – gsmtp’)
所以要先到 Google 帳戶, 選取左邊的 “安全性” 。
按下在「登入 Google」底下的 [應用程式密碼], 然後需要 Google 帳號密碼。
在 “選取應用程式” 選擇 “郵件”
“選取裝置” 選擇 “其他 (自訂名稱”, 輸入自已析別的名稱, 例如 “Python”.
按 “產生”
這時便會彈出一個應用程式的專屬密碼, 把這個密碼複製下來, 稍後在 Python 的程式碼需要用上。
現在可以寫 Python 的程式, 以下程式碼會使用 smtplib 模組, 具體寫法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#!/usr/bin/python3.6 import smtplib # Google login gmail_id = 'Your Gmail Account' gmail_passwd = 'Google App Password' to_address = 'To Email Address' # email content subject = "email subject" text = "email message" # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # gmail username and password s.login(gmail_id, gmail_passwd) message = 'Subject: {}\n\n{}'.format(subject, text) # sending the mail s.sendmail(gmail_id, to_address, message) # terminating the session s.quit() |
在上面的程式碼, 需要修改 gmail_id, gmail_passwd, to_address, subject 及 text 變數:
gmail_id: Gmail 登入名稱.
gmail_passwd: 在 Google Account 建立的應用程式密碼.
to_address: 收件人的電郵地址.
subject: 電子郵件標題.
text: 電子郵件內容.
以上程式會連接到 Gmail 的 smtp 伺服器發出電子郵件, 而寄出的內容會存放在 Gmail 的寄件備份。