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

Advertisement

32 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)

    • Hi Sathish,

      Please remove the “,”(coma) after “‘abc@abc.com’,” code works absolutely fine.

      Thanks Deepesh for your code.-/\-

      • Thank you, Nagendra for coming back and helping others. Appreciate it! Did your code work after your problem? If it is, please reply what changes you made so that others can be benefited.

        • Thanks Deepesh,

          Yeah problem has resolved now. Please let me know if any suggestion to improve more.

          Here is my code with few changes as below.In my case subprocess.call was failed even after specifying the exact path so i have used
          os.system(‘start OUTLOOK.EXE’) instead of
          “subprocess.call([‘C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Outlook 2010\Outlook.exe’]);
          os.system(“C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Outlook 2010\Outlook.exe”)”.

          Also added few lines to send attachments
          attachment1 = “C:\Study Stuff\Pyhton Scripts/shutdown.py”
          attachment2 = “C:\Study Stuff\Pyhton Scripts/automatic mail.py”
          mail.Attachments.Add(attachment1)
          mail.Attachments.Add(attachment2)
          if you want to know which case (upper/lower) does your application i.e. xxxxxxxx.exe is using by going into TaskManaager and Details tab

          Hope this information is useful to every one.

          import win32com.client as win32
          import win32api
          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 = ‘asd@gmail.com’
          mail.cc = ‘abc@gmail.com’
          attachment1 = “C:\Study Stuff\Pyhton Scripts/shutdown.py”
          attachment2 = “C:\Study Stuff\Pyhton Scripts/automatic mail.py”
          mail.Attachments.Add(attachment1)
          mail.Attachments.Add(attachment2)
          mail.Subject = ‘Sent through Python’
          mail.body = ‘This email alert is auto generated. Please do not respond.’
          mail.send
          print(‘Congrats mail hass been sent successfully’)

          # Open Outlook.exe. Path may vary according to system config
          # Please check the path to .exe file and update below

          def open_outlook():
          try:
          os.system(‘start OUTLOOK.EXE’)
          #subprocess.call([‘start OUTLOOK.EXE’]);
          #os.system(“C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office\Microsoft Outlook 2010\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()

          *********************************************************************************************************************************
          Also I would like to know how can i schedule an automatic mail at particular point of time?

          below is the code i have tried executing but it is sending mail only after executing that to it is sending same mail more than once.Could you please help me in scheduling this task?

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

          def send_notification():
          while True:
          localtime = time.asctime( time.localtime(time.time()) )
          #print (“local current time :”, localtime)
          #print (localtime)
          lst1 = localtime.split(‘ ‘)
          if(lst1[3] == ’17:07:00’):
          outlook = win32.Dispatch(‘Outlook.Application’)
          mail = outlook.CreateItem(0)
          mail.To = ‘asd@gmail.com’
          mail.cc = ‘abc@gmail.com’
          attachment1 = “C:\Study Stuff\Pyhton Scripts/shutdown.py”
          attachment2 = “C:\Study Stuff\Pyhton Scripts/automatic mail.py”
          mail.Attachments.Add(attachment1)
          mail.Attachments.Add(attachment2)
          mail.Subject = ‘Sent through Python’
          mail.body = ‘This email alert is auto generated. Please do not respond.’
          mail.send
          print(‘Congrats mail has been sent successfully’)

  10. Hi Deepesh,

    I am a New Bee to Python.
    could you please help in resolving below issue. I have already installed pypiwin32 using pip install pypiwin32,i am getting the same error. No module named ‘win32api’

    File “C:/Users/anage/OneDrive/Desktop/automatic mail.py”, line 1, in
    import win32com.client as win32
    File “C:\Users\anage\AppData\Local\Programs\Python\Python37\lib\site-packages\win32com\__init__.py”, line 5, in
    import win32api, sys, os
    ModuleNotFoundError: No module named ‘win32api’
    >>>

  11. Hi Deepesh,

    I am new to python and refer your code to send automatic mail. but its not working for me getting this error
    C:\Users\U6062308\PycharmProjects\python\venv\Scripts\python.exe C:/python/Python_session_examples/mail_test.py
    Traceback (most recent call last):
    File “C:/python/Python_session_examples/mail_test.py”, line 1, in
    import win32com.client as win32
    ModuleNotFoundError: No module named ‘win32com’

    Process finished with exit code 1

    i am using python 3.6 version and use this command for installing pip (pip install pypiwin32) still facing above error

    can you please look into it and suggest me how to move forward.

    Thanks in advance

  12. Hello, very helpful code.

    How can we just generate the mail before it automatically sent out? I would like to “double check” the email and click “SEND” in outlook by my own.

    Thanks!!!

  13. Hey Nagendra and Deepesh,
    when I tried executing this code I got the following error:

    Traceback (most recent call last):
    File “check.py”, line 16, in
    mail.Send()
    File “”, line 2, in Send
    pywintypes.com_error: (-2147467260, ‘Operation aborted’, None, None)

    need your help!
    Thanks in advance.

    • with mail.send

      Traceback (most recent call last):
      File “check.py”, line 14, in
      mail.send
      File “C:\Users\nikhil1.bantia\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py”, line 516, in __getattr__
      ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
      pywintypes.com_error: (-2147467260, ‘Operation aborted’, None, None)

  14. Hi Depeesh,

    I have tried similar code like this and it woks fine.
    But only issue is mails will go only when my outlook is open.
    So, Is there a way to send emails directly by giving username and password to the code

  15. Hi All,

    I need one help to configure notification mail using python script:

    My requirement is to get notification whenever i am getting mail in outlook but mail count should be 10(every 10 counts of mail) I should be getting notification.
    If some one guide me how to proceed with this requirement, it will be great.

    Thanks in Advance.

  16. Hi Deepesh, very beautifully explained and written down the code. I am working on a similar automation where i need to copy charts from different worksheets of same workbook and paste them into the email body. here’s the code along with your suggested email code.

    please suggest how should I paste the charts in the email body.

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

    wb = opx.load_workbook(‘D:\My Analytics Projects\Python Excel Work\poc python.xlsx’)

    i=0
    for ws in wb.worksheets:
    print(ws)
    xlchart = ws._charts.copy()
    print(xlchart)
    i+=0

    wb.close()

    def send_notification():
    outlook = win32.Dispatch(‘Outlook.Application’)

    mail = outlook.CreateItem(0)
    mail.To = ‘amitkumar.sharma6@genpact.com’
    mail.cc = ‘amitkumar.sharma6@genpact.com’
    # attachment1 = “C:\Study Stuff\Pyhton Scripts/shutdown.py”
    # attachment2 = “C:\Study Stuff\Pyhton Scripts/automatic mail.py”
    # mail.Attachments.Add(attachment1)
    # mail.Attachments.Add(attachment2)
    mail.Subject = ‘Sent through python test file’
    mail.body = ‘This email alert is auto generated. Please do not respond.’
    mail.send

    def open_outlook():
    try:
    subprocess.call([‘C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Outlook 2016’])
    os.system(‘C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Outlook 2016’)
    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()

  17. Hi Deepesh,

    I am working on a small automation where excel charts can be copied and pasted into an email body. Below is my code, the charts are getting copied as well , just can u pls suggest how do i paste those charts in the body of the email.

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

    wb = opx.load_workbook(‘D:\My Analytics Projects\Python Excel Work\poc python.xlsx’)

    i=0
    for ws in wb.worksheets:
    print(ws)
    xlchart = ws._charts.copy()
    print(xlchart)
    i+=0

    wb.close()

    def send_notification():
    outlook = win32.Dispatch(‘Outlook.Application’)

    mail = outlook.CreateItem(0)
    mail.To = ‘amitkumar.sharma6@genpact.com’
    mail.cc = ‘amitkumar.sharma6@genpact.com’
    # attachment1 = “C:\Study Stuff\Pyhton Scripts/shutdown.py”
    # attachment2 = “C:\Study Stuff\Pyhton Scripts/automatic mail.py”
    # mail.Attachments.Add(attachment1)
    # mail.Attachments.Add(attachment2)
    mail.Subject = ‘Sent through python test file’
    mail.body = ‘This email alert is auto generated. Please do not respond.’
    mail.send

    def open_outlook():
    try:
    subprocess.call([‘C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Outlook 2016’])
    os.system(‘C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Outlook 2016’)
    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()

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 )

Facebook photo

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

Connecting to %s