Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
我們將透過使用OpenAI的ChatGPT來學習如何撰寫一段Python程式,自動寄送Email。ChatGPT是一款強大的語言模型,不僅可以回答你的問題,還能幫助你寫程式碼!
首先,你需要設定SMTP(Simple Mail Transfer Protocol)伺服器的相關設定。以下是使用Gmail SMTP伺服器作為範例:
import smtplib
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587 # TLS port
EMAIL_ADDRESS = '[email protected]' # 請將此替換為你的Gmail地址
EMAIL_PASSWORD = 'your_password' # 請將此替換為你的Gmail密碼
注意:使用此方法可能需要您允許Google帳戶的”低安全性應用程式存取”。為了安全起見,建議您建立一個專門的Gmail帳戶來執行此作業,或考慮使用其他方法,如API金鑰或OAuth2。
接著,我們需要一個函數來寄送Email。
def send_email(subject, message, recipient):
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls() # Upgrade the connection to secure encrypted SSL/TLS connection
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
email_message = f'Subject: {subject}\n\n{message}'
server.sendmail(EMAIL_ADDRESS, recipient, email_message)
現在,你只需要呼叫send_email
函數,並提供主題、內容和收件人,就可以輕鬆寄出Email了。
subject = 'Hello from Python!'
message = 'This is a test email sent using Python and ChatGPT.'
recipient = '[email protected]'
send_email(subject, message, recipient)
完成以上步驟後,收件人應該能夠收到來自Python程式的測試Email。
使用Python寄送Email其實非常簡單,只要掌握基本的SMTP設定和smtplib模組,就能輕鬆完成。而有了ChatGPT的協助,無論你是程式新手或經驗豐富的開發者,都能迅速地寫出你需要的程式碼。