0

I am trying to automate a mass e-mailing and need to change the 'From' field in Outlook. The e-mail cannot be 'Sent on Behalf of' per compliance reasons. When I attempted this solution, I received the following error...

pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1)

This error is referencing the mail._oleobj_.Invoke(*(64209, 0, 8, 0, email_from)) line. Code snippet is below. Let me know what I have wrong or if there is a better way.

to = 'jsmith@external_domain.com'
cc = 'my_group_e-mail@my_domain.com'
subject = personalized_subject_from_data_source
body = f'''personalized body from other data source with a {table}'''

outlook = win32.Dispatch('outlook.application')
# adding the code suggested by h0r53:
email_from = None
for account in outlook.Session.Accounts:
    if account.DisplayName == 'why_i_asked_email@my_domain.com':
        email_from = account
        break
mail = outlook.CreateItem(0)
# email_from = 'why_i_asked_email@my_domain.com'
mail._oleobj_.Invoke(*(64209, 0, 8, 0, email_from))
mail.To = to
mail.CC = cc
mail.Subject = subject
mail.HTMLbody = body
mail.Display(True)

EDIT After adding the code suggested by h0r53, I still receive the same error. the variable account is listed as <COMObject <unknown>> and thus never satisfies the logic gate and when the for iteration completes, email_from == None and thus throws the same error. Any further help is appreciated

Thanks!!

AJames
  • 81
  • 1
  • 1
  • 10
  • `email_from` likely isn't supposed to be a `String` at all, but rather an object that represents a domain user. In the solution you referenced, the `email_from` variable is NOT a string, but rather an entry in `outlook_app.Session.Accounts` – h0r53 Sep 22 '21 at 16:27

1 Answers1

1

I figured it out with this: Python - Reveal a COM object. In the for method, it is not outlook.Session.Accounts, rather it is outlook.GetNamespace('MAPI').Accounts as below:

    for account in outlook.GetNamespace('MAPI').Accounts:
        if str(account) == 'the_e-mail_in_question':
            email_from = account
            break
    mail = outlook.CreateItem(0)
    mail._oleobj_.Invoke(*(64209, 0, 8, 0, email_from))
    mail.To = to
    mail.CC = cc
    mail.Subject = subject
    mail.HTMLbody = body
    mail.Display(True)
AJames
  • 81
  • 1
  • 1
  • 10