如何使用ChatGPT 撰寫Python 自動寄Email程式

我們將透過使用OpenAI的ChatGPT來學習如何撰寫一段Python程式,自動寄送Email。ChatGPT是一款強大的語言模型,不僅可以回答你的問題,還能幫助你寫程式碼!

步驟1:設定SMTP

首先,你需要設定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。

步驟2:撰寫寄送Email函數

接著,我們需要一個函數來寄送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)

步驟3:使用程式

現在,你只需要呼叫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的協助,無論你是程式新手或經驗豐富的開發者,都能迅速地寫出你需要的程式碼。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *