发送多个邮件时出现Outlook错误:“该项目已被移动或删除”

时间:2019-12-02 06:46:45

标签: excel python-3.x outlook

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") 
outlook2 = win32com.client.Dispatch("Outlook.Application") 
ns = outlook2.GetNamespace("MAPI") 
ns.Logon("Outlook2010") 
mail = outlook2.CreateItem(0) 
inbox = outlook.GetDefaultFolder(6) 
messages = inbox.Items
for i in processed_corpus:
  for j in i:
     if j == "pricing" or j == "price" or j == "quote" or j =="quotation":
        mail.To = "abc@xyz.com"
        mail.Subject = message.Subject
        mail.Body = message.Body + "Belongs To Pricing"
        mail.Send()
        # print("Belongs to Pricing")
        # print("**************")
        # print(j)
        worksheet.write(row,col +4,"Pricing")
        ram=1
     elif j == "service" or j=="request" or j=="servicerequest":
        mail.To = "abc@xyz.com"
        mail.Subject = message.Subject
        mail.Body = message.Body + "Belongs To Service Request"
        mail.Send()
        # print("Belongs to servicerequest")
        # print("**************")
        # print(text_corpus)
        # print(j)
        worksheet.write(row, col + 4, "Service Request")
        ram=1
if(ram==0):
    #print("nothing")
    worksheet.write(row, col + 4, "Category Not Defined")
     # else:
     #    print("Belongs to nothing")
     #    print("**************")
     #    worksheet.write(row, col + 4, "Category Not Defined")

row = row + 1
message = lastHourMessages.GetNext()
wb.save("C:\\Users\\Innovation\\Desktop\\Demo_Format.xls")`

这是我得到的错误:

Traceback (most recent call last):

File "28/11/2k19.py", line 81, in <module>
     mail.To = "abc@xyz.com"
File "venv\lib\site-packages\win32com\client\dynamic.py", line 549, in __setattr__
     self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) 
     pywintypes.com_error: (-2147352567, 'Exception occurred.', 
         (4096, 'Microsoft Outlook', 'The item has been moved or deleted.',
                None, 0, -2147221238),
     None)

1 个答案:

答案 0 :(得分:0)

问题在于,您仅使用mail创建一个CreateItem(0)对象,并且一旦发送了该对象,就不允许在下一次循环中对其进行修改。 / p>

您真正想要的是在每个迭代中创建一个新邮件。所以改变这个:

mail = outlook2.CreateItem(0) # <-- this should be moved inside the inner loop
inbox = outlook.GetDefaultFolder(6) 
messages = inbox.Items
for i in processed_corpus:
  for j in i:
    if j == "pricing" or j == "price" or j == "quote" or j =="quotation":

对此:

inbox = outlook.GetDefaultFolder(6) 
messages = inbox.Items
for i in processed_corpus:
  for j in i:
    mail = outlook2.CreateItem(0) # <--- moved here
    if j == "pricing" or j == "price" or j == "quote" or j =="quotation":