2

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.

Shiriru
  • 181
  • 1
  • 10

2 Answers2

7

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()
Shiriru
  • 181
  • 1
  • 10
  • 1
    Thank you so much for that win32 black magic. It seems to be the only way to set the SendUsingAccount value. (For your information, I use Outlook 2013, Windows 7, and my system is in French, but not Japanese). – Réchèr Apr 25 '16 at 07:08
  • Sender account is obvious, but what do the parameters of the `Invoke()` method mean? It works, but I cant find it in the docs anywhere – marengaz Jan 14 '17 at 17:40
3

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!

Samnater
  • 67
  • 5