pochi517004
pochi517004

使用Python自動發送Outlook郵件的教學

在日常生活和工作中,我們經常需要發送電子郵件來進行溝通和分享資訊。本文將介紹如何使用Python的pywin32模組連接到Outlook,並通過程式來自動發送郵件。

安裝所需的模組

首先,我們需要安裝pywin32模組。可以使用pip在終端機中執行以下命令來安裝:

pip install pywin32

實作寄信函式

接下來,我們將實作一個名為send_email的函式來發送郵件。這個函式將接收郵件的主題、內容和收件人,然後使用Outlook應用程式來發送郵件。

import win32com.client as win32

def send_email(subject, body, recipients):
    try:
        outlook = win32.Dispatch('Outlook.Application')
        mail = outlook.CreateItem(0)
        mail.Subject = subject
        mail.Body = body
        mail.To = recipients
        mail.Send()
        print("郵件寄出成功!")
    except Exception as e:
        print("郵件寄出失敗:", str(e))

寄信內容

現在我們可以設置郵件的主題、正文和收件人,然後使用send_email函式來發送郵件。

# 設置郵件主題、正文和收件人
subject = "測試郵件"
body = "這是一封測是自動寄信的郵件。"
recipients = "recipient@example.com"

# 寄出郵件
send_email(subject, body, recipients)

完成了以上步驟後,運行程式將會自動連接到Outlook並發送郵件給指定的收件人。確保你已經登入了Outlook,並且郵件地址是有效的。

希望這篇教學能幫助你學會如何使用Python來自動發送Outlook郵件!如果有任何疑問,歡迎在下方留言。

CC BY-NC-ND 4.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论