簡體   English   中英

如何使用 Python 從 outlook 發送帶有附件的郵件

[英]How to Send Mails with attachments from your outlook using Python

下面的代碼在沒有附件的情況下工作得很好,使用 outlook 發送 30 封電子郵件/分鍾

我正在使用的 csv 文件具有:名稱,email,作為示例附上:

firstname,email@domain.com,firstfile.pdf
secondname,other@domain.com,secondfile.pdf

所以我為附件文件夾的完整路徑設置了一個變量(因為附件文件夾是可變的

attachments_path= "C:\Users\PC\Desktop\My\files\"

並將message.Attachments.add (attachments_path + attach)添加到循環代碼中

import csv
from time import sleep
import win32com.client as client

attachments_path= "C:\\Users\\PC\Desktop\\My\\files\\"

# create template for message body
template = "Hello {}, this is a test."


# open distribution list
with open('emails.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    distro = [row for row in reader]

# chunk distribution list into blocks of 30
chunks = [distro[x:x+30] for x in range(0, len(distro), 30)]

# create outlook instance
outlook = client.Dispatch('Outlook.Application')

# iterate through chunks and send mail
for chunk in chunks:
    # iterate through each recipient in chunk and send mail
    for name, address, attach in chunk:
        message = outlook.CreateItem(0)
        message.To = address
        message.Subject = "Subject Test"
        message.Body = template.format(name)
        message.Attachments.add (attachments_path + attach) # added for testing
        message.Send()

    # wait 60 seconds before sending next chunk
    sleep(60)

所以當我運行代碼時,我得到了錯誤:

Traceback (most recent call last):
  File "c:\Users\PC\Desktop\My\app.py", line 29, in <module>
    message.Attachments.add (attachments_path + attach)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 628, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot add the attachment; no data source was provided.', None, 0, -2147352567), None)

知道如何使此代碼與附件一起運行嗎?

在運行代碼之前,您確定磁盤上存在這樣的文件嗎?

message.Attachments.add (attachments_path + attach)

首先,您需要確保磁盤上存在此類文件,並且文件路徑名稱中包含允許的符號。

Attachments class 的Add方法接受代表附件來源的文件路徑字符串。 這可以是一個文件(由帶有文件名的完整文件系統路徑表示)或構成附件的 Outlook 項目。

經過多次試驗和錯誤,解決方案只是將文件路徑斜杠從 \ 更改為 / 所以而不是

"C:\\Users\\PC\Desktop\\My\\files\\file.pdf" 

它應該是

"C:/Users/PC/Desktop/My/files/file.pdf"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM