Search code examples
pythonwinapipywin32

Define mailbox to which to save an email - win32client python


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?


Solution

  • 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