Send email with Outlook and Python

A simple example to send emails via Outlook and Python win32com.

2 Replies to “Send email with Outlook and Python”

  1. I wrote code like this

    import win32com.client as win32
    import psutil
    import os
    import subprocess

    # Drafting and sending email notification to senders. You can add other senders’ email in the list
    def send_notification():

    outlook = win32.Dispatch(‘Outlook.Application’)

    mail = outlook.CreateItem(0x0)
    mail.To = ‘abc@abc.com’,
    # mail.Subject = ‘Sent through Python’
    # mail.body = ‘This email alert is auto generated. Please do not respond.’
    # mail.send

    def open_outlook():
    try:
    subprocess.call([‘C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE’])
    os.system(‘C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE’);
    except:
    print(“Outlook didn’t open successfully”)

    for item in psutil.pids():
    p = psutil.Process(item)
    if p.name() == “OUTLOOK.EXE”:
    flag = 1
    break
    else:
    flag = 0

    if (flag == 1):
    send_notification()
    else:
    open_outlook()
    send_notification()

    and the error:
    Traceback (most recent call last):
    File “C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py”, line 33, in
    send_notification()
    File “C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py”, line 12, in send_notification
    mail.To = ‘abc@abc.com’,
    File “C:\Users\satz\PycharmProjects\PYWork\venv\lib\site-packages\win32com\client\dynamic.py”, line 565, in __setattr__
    self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
    pywintypes.com_error: (-2147352567, ‘Exception occurred.’, (4096, u’Microsoft Outlook’, u’The object does not support this method.’, None, 0, -2147352567), None)

  2. Hi,

    What if i want to change “from” of email?

    Do you know something like
    mail. from=”abc@..com” or mail.sender. None of them works for me.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.