2

I would like to save an email to the drafts folder of a shared mailbox using the win32 API for Outlook. I can save an email to my (default?) mailbox drafts folder using the below:

def TestEmailer(text, subject, recipient):
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    mail.Save()

TestEmailer('hello world', 'test', 'recipient@gmail.com')

Thanks to this previous question I can see that the SendUsingAccount() method can be used to send from a defined mailbox. Is there an equivalent method for saving to the drafts folder of a defined mailbox?

user 123342
  • 463
  • 1
  • 9
  • 21

1 Answers1

2

You can select Save () when you switch your account to send email, which will be saved in the draft box of the new account.

Code:

import win32com.client as win32

def send_mail():
    outlook_app = win32.Dispatch('Outlook.Application')

    # choose sender account
    send_account = None
    for account in outlook_app.Session.Accounts:
        if account.DisplayName == 'sender@hotmail.com':
            send_account = account
            break

    mail_item = outlook_app.CreateItem(0)   # 0: olMailItem

    # mail_item.SendUsingAccount = send_account not working
    # the following statement performs the function instead
    mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, send_account))

    mail_item.Recipients.Add('receipient@outlook.com')
    mail_item.Subject = 'Test sending using particular account'
    mail_item.BodyFormat = 2   # 2: Html format
    mail_item.HTMLBody = '''
        <H2>Hello, This is a test mail.</H2>
        Hello Guys. 
        '''

    mail_item.Save()


if __name__ == '__main__':
    send_mail()

Here's a bit of black magic here. Setting mail_item.SendUsingAccount directly won't work. The return value is none. Always send mail from the first email account. You need to call the method of oleobj_.Invoke().

Updated:

Oleobj document: https://github.com/decalage2/oletools/wiki/oleobj

Similar case: python win32com outlook 2013 SendUsingAccount return exception

Strive Sun
  • 5,988
  • 1
  • 9
  • 26
  • Thanks for your answer. For my reference, could you link documentation for the `mail_item._oleobj_.Invoke()` method, or provide a short description of the inputs? – user 123342 Oct 30 '19 at 01:20
  • nice. but how do I save email as draft from my 2nd outlook account? This picks my default/primary account. How do I choose the 2nd account as sender email address? – The Great Jul 29 '22 at 08:11
  • In the `outlook_app.Session.Accounts`, I see only account displayed. – The Great Jul 29 '22 at 08:15