Auto Send Email Through Outlook via Python Code – Topbullets.com

Topbullets.comI wrote an article on How to send email through ASP.NET and it helped a lot of people. Automating such processes always save lot of time and manual intervention. Currently in my project one process takes 45 minutes to run and one needs to look out at screen continuously for any error or if code stops in between. For that I wrote a python code which track the process and send email notification instantly if code stops or runs completely. The article can also be useful for someone who is looking for a python code to know which windows applications are running or open any Windows application using Python.
First of all there are lots of SMTP servers which can be used to send email. Google, Yahoo and Hotmail everyone provided SMTP details. You can easily find python code on the same but in my case I am using Outlook app which is Windows default email application.
The code is written is 3 major segments. 1st segment would raise flag when our process stops or runs successfully, 2nd will check if outlook is running or not and then 3rd will send email notification. I won’t paste 1st segment as it depends on your requirement. You can pass one variable and alter its value based on the outcome and then call any functions. FYI, you can add if/else before line 19 and change ’email body’ accordingly. The below code is well commented. One can easily understand the logic behind and use it. If you have any doubt or suggestion please feel free to comment below.

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 21 15:36:00 2016

@author: Deepesh.Singh
"""

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(0)
    mail.To = 'abc@xzs.com; bhm@ert.com', 
    mail.Subject = 'Sent through Python'
    mail.body = 'This email alert is auto generated. Please do not respond.'
    mail.send
    
# Open Outlook.exe. Path may vary according to system config
# Please check the path to .exe file and update below
    
def open_outlook():
    try:
        subprocess.call(['C:\Program Files\Microsoft Office\Office15\Outlook.exe'])
        os.system("C:\Program Files\Microsoft Office\Office15\Outlook.exe");
    except:
        print("Outlook didn't open successfully")

# Checking if outlook is already opened. If not, open Outlook.exe and send email
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()

The article can be helpful for:
1. Send email through Python code
2. How to check if windows application is running or not in Python
3. How to open windows application through Python code
4. Find all running programs in Python

Signature

Deepesh Singh
logo

Advertisements

12 thoughts on “Auto Send Email Through Outlook via Python Code – Topbullets.com

  1. Thanks for the code. To test this code, can I copy this script into my C drive and run it on command prompt?
    If yes, I tried it already and hitting the following error:

    Traceback (most recent call last):
    File “sendemail.py”, line 1, in
    import win32com.client as win32
    File “C:\Python27\lib\site-packages\win32com\__init__.py”, line 5, in
    import win32api, sys, os
    ImportError: DLL load failed: %1 is not a valid Win32 application.

    Can you please tell me how to fix this?

  2. Hi Singh,
    sorry to bother you.
    I used your sample code to verify the auto send mail function, but i can’t send out the mail until reopening the outlook again. have you met this problem before?

  3. Hi Singh,
    sorry to bother you.
    I used your sample code to verify the auto send mail function, but i can’t send out the mail until reopening the outlook again. have you met this problem before?
    many thanks.

  4. Hi Deepesh, thanks for the solution. It basically works for me, except that when it runs a password prompt pops up momentarily and dismisses itself after a few seconds (which is after my program finished running). The email gets sent out successfully anyway.

    Any idea why or how to get rid of it? I’m running my program on a work machine with a corporate account.

    Thanks!

  5. Also, it seems that `subprocess.call` or `os.system` each worked alone. Why do we need both?

    Incidentally, whether I use both or just one of them, I do get the error “Outlook didn’t open successfully” ever time.

  6. Hi Deepesh,
    When i try to test the above mentioned code, getting the below error at line 15 in the above code.
    outlook = win32.Dispatch(‘outlook.application’)
    SyntaxError : invalid character in identifier

    can you help me in getting rid of this error?

  7. This is what worked for me:

    import win32com.client
    from win32com.client import Dispatch, constants
    import psutil
    import os
    import subprocess

    const=win32com.client.constants

    # Drafting and sending email notification to senders. You can add other senders’ email in the list
    def send_notification():
    #s = win32.Dispatch(“Mapi.Session”)
    olMailItem = 0x0
    obj = win32com.client.Dispatch(“Outlook.Application”)
    newMail = obj.CreateItem(olMailItem)
    newMail.Subject = “Test Email!!”
    newMail.Body = “I AM IN THE BODY\nSO AM I!!!”
    newMail.To = “abc@abc.com”

  8. Although I keep getting the error below when Outlook is not open. Scripts works fine when Outlook is already open.

    Traceback (most recent call last):
    File “email.py”, line 34, in
    p = psutil.Process(item)
    File “C:\Users\bhavesh.dodia\AppData\Local\Programs\Python\Python36-32\lib\site-packages\psutil\__init__.py”, line 341, in __init__
    self._init(pid)
    File “C:\Users\bhavesh.dodia\AppData\Local\Programs\Python\Python36-32\lib\site-packages\psutil\__init__.py”, line 381, in _init
    raise NoSuchProcess(pid, None, msg)
    psutil._exceptions.NoSuchProcess: psutil.NoSuchProcess no process found with pid 12252

  9. Hi Deepesh

    I tried 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 I have Python 2.7 Installed and got this error
    C:\Users\satz\PycharmProjects\PYWork\venv\Scripts\python.exe C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py
    Traceback (most recent call last):
    File “C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py”, line 34, in
    send_notification()
    File “C:/Users/satz/PycharmProjects/PYWork/Sample/EmailSample1.py”, line 13, 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)

Please leave your valuable comment.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s