Send email with Outlook and Python

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

import win32com.client

s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon("Outlook2003")
    
Msg = o.CreateItem(0)
Msg.To = "recipient@domain.com"
    
Msg.CC = "more email addresses here"
Msg.BCC = "more email addresses here"
    
Msg.Subject = "The subject of you mail"
Msg.Body = "The main body text of you mail"
    
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
 
Msg.Send()

20 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.

    1. You have to remove the comma at the end of ‘mailTo’-line. This is leading to the error you get.

  3. Hi,
    My company using outlook mailer I want to sent mail for my corporate mail id (xys@company.com) using python.
    Please help me.

    1. Hi Venkat,

      Any one responded to this query, i need answer to update in my script. please help me

  4. com_error: (-2147352567, ‘Exception occurred.’, (4096, ‘Microsoft Outlook’, ‘Cannot add the attachment; no data source was provided.’, None, 0, -2147352567), None)

    I get this error message even though the path to the attachment is correct.

  5. Use this

    import win32com.client as win32
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.SentOnBehalfOfName = 'EMAIL'
    mail.To = 'EMAIL'
    mail.Subject = 'Message subject'
    mail.Body = 'Message body'
    mail.HTMLBody = 'HTML Message body' #this field is optional
    # To attach a file to the email (optional):
    attachment  = "Path to the attachment"
    mail.Attachments.Add(attachment)
    
    mail.Send()
    
  6. Hey, what if i need to send the email to more than one accounts at the same time (not using a FOR loop to send it)

  7. Thank you so much, Edson

    It works for me!

    Use this

    import win32com.client as win32
    outlook = win32.Dispatch(‘outlook.application’)
    mail = outlook.CreateItem(0)
    mail.SentOnBehalfOfName = ‘EMAIL’
    mail.To = ‘EMAIL’
    mail.Subject = ‘Message subject’
    mail.Body = ‘Message body’
    mail.HTMLBody = ‘HTML Message body’ #this field is optional
    # To attach a file to the email (optional):
    attachment = “Path to the attachment”
    mail.Attachments.Add(attachment)
    
    mail.Send()
    
  8. Great stuff, how to set confidentiality label (Azure information protection), like confidential, internal, restricted etc.? Thanks.

    mail.Sensitivity = 1

    mail.Confidentiality = “Internal”

    mail.Label = 1

    I tried all the 3, nothing seem to work

  9. hi, any help on setting the confidentiality label (Azure information protection) values?
    I am also kinda stuck on this step.

  10. This code is working fine if there are no issues in email ID. but it will stop in between if there is a bad email ID in list. How to skip that…

    import pandas as pd
    import win32com.client as win32
    outlook = win32.Dispatch(‘outlook.application’)

    df= pd.read_excel(r”C:\Auto Mail\Dump\Book.xlsx”)
    df=df[[“Created date”,”Vendor account”,”Number”,”Item number”, “Inventory quantity”,”Product name”,”E-mail”,”Orderer”]]
    df[‘E-mail’]=df[‘E-mail’].str.replace(‘,’,’;’)
    df[“Comments”]= “”
    df.rename(columns = {‘Created date’:’PO Date’, ‘Number’:’PO Number’,’Item number’:’Item Code’}, inplace = True)
    df=df[df[‘E-mail’].notnull()]
    df=df[df[“Inventory quantity”]>=1]

    # Split Vendor
    split_Vendor = df[‘Vendor account’].unique()

    for value in split_Vendor:
    df1=df[df[‘Vendor account’]== value]
    Unique_email = df1[‘E-mail’].unique()
    df1=df1[[“PO Date”,”PO Number”,”Item Code”, “Inventory quantity”,”Product name”,”Comments”]]
    mail = outlook.CreateItem(0)
    mail.To = Unique_email[0]

    mail.Subject = ‘Open PO pending for delivery’
    mail.HTMLBody = ”’\

    Hello,
    Please find the below open PO which is pending for delivery as per our system.
    Kindly confirm the delivery date for each line item by EOD.
    If material is already supplied then please ignore this mail.
    ”’ + df1.to_html(index=False) + ”’

    Kind Regards,
    Prashanth

    ”’
    mail.Send()

Leave a Reply to Pedro Silva Cancel 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.