Python 利用Python自動寄送Gmail電子郵件Email
應用程式密碼取得
1.進入管理妳的Google帳戶

2.左邊點選安全性

3.先設定兩步驟驗證才會出現應用程式密碼

4.選取其他(自訂名稱)

5.應用程式密碼紀錄 待會登入需要填入這組密碼

程式範例
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
content = MIMEMultipart()
content["subject"] = "美女圖片" # 標題
content["from"] = "yc38529@gmail.com" # 寄件者
content["to"] = "sample@gmail.com" # 收件者
content.attach(MIMEText("嗨妳好")) # 郵件內容
# 郵件附件內容 所以類型都可以傳 要放在python檔案同一層
attachments = ['girl.jpg']
for file in attachments:
with open(file, 'rb') as fp:
add_file = MIMEBase('application', "octet-stream")
add_file.set_payload(fp.read())
encoders.encode_base64(add_file)
add_file.add_header('Content-Disposition', 'attachment', filename=file)
content.attach(add_file)
# SMTP設定 並登入Gmail 要使用專用應用程式密碼
with smtplib.SMTP(host="smtp.gmail.com", port="587") as smtp: # 設定SMTP伺服器
try:
smtp.ehlo() # 驗證SMTP伺服器
smtp.starttls() # 建立加密傳輸
smtp.login("yc38529@gmail.com", "專用應用程式密碼") # 登入寄件者gmail
smtp.send_message(content) # 寄送郵件
print("傳送成功")
except Exception as e:
print("錯誤訊息: ", e)
效果展示
