python win32com outlook 2013 SendUsingAccount return exception

冷暖自知 提交于 2019-12-22 12:23:50

问题


While working on a simple mail automation with python and win32com api, I had an issue with SendUsingAccount. It was ignored or, worse, generating an error when I upgraded from windows 7 to windows 10.

Here is my original code

import win32com.client

o = win32com.client.Dispatch("Outlook.Application")
oacctouse = None
for oacc in o.Session.Accounts:
    if oacc.SmtpAddress == "sender@mail.com":
        oacctouse = oacc
        break
Msg = o.CreateItem(0)
if oacctouse:
    Msg.SendUsingAccount = oacctouse
if to:
    Msg.To = ";".join(to)
if cc:
    Msg.CC = ";".join(cc)
if bcc:
    Msg.BCC = ";".join(bcc)

Msg.HTMLBody = ""

Msg.Send()

Resulting in the following error: Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.3\helpers\pydev\pydevd_exec.py", line 3, in Exec exec exp in global_vars, local_vars File "", line 1, in File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 560, in setattr self.oleobj.Invoke(entry.dispid, 0, invoke_type, 0, value) com_error: (-2147417851, '\x83T\x81[\x83o\x81[\x82\xc9\x82\xe6\x82\xc1\x82\xc4\x97\xe1\x8aO\x82\xaa\x95\xd4\x82\xb3\x82\xea\x82\xdc\x82\xb5\x82\xbd\x81B', None, None)

My system is in Japanese.

I will answer my issue below.


回答1:


So, I found the solution to my problem by chance on this thread at the very bottom (most of it is for VBA but the last post solved the python issue).

Here is the working code

import win32com.client

o = win32com.client.Dispatch("Outlook.Application")
oacctouse = None
for oacc in o.Session.Accounts:
    if oacc.SmtpAddress == "sender@mail.com":
        oacctouse = oacc
        break
Msg = o.CreateItem(0)
if oacctouse:
    Msg._oleobj_.Invoke(*(64209, 0, 8, 0, oacctouse))  # Msg.SendUsingAccount = oacctouse

if to:
    Msg.To = ";".join(to)
if cc:
    Msg.CC = ";".join(cc)
if bcc:
    Msg.BCC = ";".join(bcc)

Msg.HTMLBody = ""

Msg.Send()



回答2:


For others not having luck seeing their secondary account name show up under the "for oacc in o.Session.Accounts:" loop: try using Msg.SentOnBehalfOfName = '2ndaryemail@mail.com' . This worked for me!



来源:https://stackoverflow.com/questions/35908212/python-win32com-outlook-2013-sendusingaccount-return-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!