Define mailbox to which to save an email - win32client python

自作多情 提交于 2020-01-14 01:35:28

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/58602116/define-mailbox-to-which-to-save-an-email-win32client-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!