问题
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