MichaelChou0806 commited on
Commit
e5b86b0
·
verified ·
1 Parent(s): bcfbee7

Create email_test.py

Browse files
Files changed (1) hide show
  1. email_test.py +69 -0
email_test.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # email_test.py
3
+ # 使用方法:
4
+ # 1) 在環境變數設定 ALERT_EMAIL 與 ALERT_PASS
5
+ # ALERT_EMAIL = yourname@gmail.com
6
+ # ALERT_PASS = Google App Password (16 chars, no spaces)
7
+ # 2) python email_test.py recipient@example.com "可選主旨" "可選內文"
8
+
9
+ import os
10
+ import sys
11
+ import smtplib
12
+ import ssl
13
+ from email.message import EmailMessage
14
+ from datetime import datetime
15
+
16
+ def send_test_email(sender_email, app_password, recipient_email,
17
+ subject=None, body=None):
18
+ subject = subject or f"[測試] SMTP 郵件 {datetime.now().isoformat()}"
19
+ body = body or "這是一封由 email_test.py 發出的測試郵件。若收到表示 SMTP 與應用程式密碼設定正確。"
20
+
21
+ msg = EmailMessage()
22
+ msg["From"] = sender_email
23
+ msg["To"] = recipient_email
24
+ msg["Subject"] = subject
25
+ msg.set_content(body)
26
+
27
+ smtp_host = "smtp.gmail.com"
28
+ smtp_port = 465 # SSL
29
+
30
+ context = ssl.create_default_context()
31
+ try:
32
+ with smtplib.SMTP_SSL(smtp_host, smtp_port, context=context) as server:
33
+ server.login(sender_email, app_password)
34
+ server.send_message(msg)
35
+ return True, "郵件已成功發送。"
36
+ except Exception as e:
37
+ return False, f"發送失敗:{e}"
38
+
39
+ def main():
40
+ sender = os.getenv("ALERT_EMAIL")
41
+ app_pass = os.getenv("ALERT_PASS")
42
+
43
+ if not sender or not app_pass:
44
+ print("錯誤:請先設定環境變數 ALERT_EMAIL 與 ALERT_PASS (Gmail 應用程式密碼)。")
45
+ print("範例(Linux/macOS):")
46
+ print(" export ALERT_EMAIL='you@gmail.com'")
47
+ print(" export ALERT_PASS='abcdabcdefghijklmnop'")
48
+ print("範例(Windows PowerShell):")
49
+ print(" setx ALERT_EMAIL \"you@gmail.com\"")
50
+ print(" setx ALERT_PASS \"abcdabcdefghijklmnop\"")
51
+ sys.exit(1)
52
+
53
+ if len(sys.argv) < 2:
54
+ print("用法:python email_test.py recipient@example.com [subject] [body]")
55
+ sys.exit(1)
56
+
57
+ recipient = sys.argv[1]
58
+ subject = sys.argv[2] if len(sys.argv) >= 3 else None
59
+ body = sys.argv[3] if len(sys.argv) >= 4 else None
60
+
61
+ ok, msg = send_test_email(sender, app_pass, recipient, subject, body)
62
+ if ok:
63
+ print("✅", msg)
64
+ else:
65
+ print("❌", msg)
66
+ sys.exit(2)
67
+
68
+ if __name__ == "__main__":
69
+ main()