30
votes

I have a script that automatically creates and sends emails sends emails using the simple function below:

def Emailer(text, subject, recipient):
    import win32com.client as win32   

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    mail.send

But how do I open this email in an Outlook window so that it can be manually edited and sent?

Ideally, I'd like something like this:

def __Emailer(text, subject, recipient, auto=True):
    import win32com.client as win32   

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    if auto:
        mail.send
    else:
        mail.open # or whatever the correct code is
4

4 Answers

28
votes

Call mail.Display(True) instead of mail.send

10
votes

tldr: Use mail.Display(False) instead of mail.Display(True)

mail.Display(False) will still display the window. If you use mail.Display(True) the scripts stops until the window is closed. So use mail.Display(False) this will open the window and your python script will move on to the next command. It is also useful to know that you can use mail.save() to save as draft in the draft folder.

Visit https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/mailitem-display-method-outlook to read more on this

6
votes

I like the solution :) But I want to add some infos:

Using the solution, it is probably the best way to add a mail input with Html format for modification.

Also add the file from the working directory...

#requirements.txt add for py 3 -> pypiwin32

def Emailer(text, subject, recipient):
    import win32com.client as win32
    import os

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.HtmlBody = text
    ###

    attachment1 = os.getcwd() +"\\file.ini"

    mail.Attachments.Add(attachment1)

    ###
    mail.Display(True)

MailSubject= "Auto test mail"
MailInput="""
#html code here
"""
MailAdress="[email protected];[email protected]"

Emailer(MailInput, MailSubject, MailAdress ) #that open a new outlook mail even outlook closed.
4
votes

Here is another option with saving the mail on disk first:

import webbrowser

mail.SaveAs(Path=save_path)
webbrowser.open(save_path)

This way the mail opens maximized.