下面的代碼在沒有附件的情況下作業得很好,使用 Outlook 發送 30 封電子郵件/分鐘
我正在使用的 csv 檔案具有:名稱、電子郵件、附件作為示例:
firstname,[email protected],firstfile.pdf
secondname,[email protected],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)
知道如何使此代碼與附件一起運行嗎?
uj5u.com熱心網友回復:
在運行代碼之前,您確定磁盤上存在此類檔案嗎?
message.Attachments.add (attachments_path attach)
首先,您需要確保磁盤上存在此類檔案,并且檔案路徑在名稱中包含允許的符號。
該類的Add方法Attachments接受代表附件源的檔案路徑字串。這可以是一個檔案(由帶有檔案名的完整檔案系統路徑表示)或構成附件的 Outlook 專案。
uj5u.com熱心網友回復:
經過多次反復試驗,解決方案只是將檔案路徑斜杠從 \ 更改為 / so 而不是
"C:\\Users\\PC\Desktop\\My\\files\\file.pdf"
它應該是
"C:/Users/PC/Desktop/My/files/file.pdf"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/388531.html
上一篇:無需使用IMAP和POP3即可從office365收件箱中讀取電子郵件
下一篇:在流分析中將列逆透視為兩個新列
