Skip to content

Instantly share code, notes, and snippets.

@nanda-dash
Forked from ITSecMedia/outlook_email.py
Last active April 20, 2021 11:26
Show Gist options
  • Save nanda-dash/8e7d723eb5a22dcc97bf32203adb9fa3 to your computer and use it in GitHub Desktop.
Save nanda-dash/8e7d723eb5a22dcc97bf32203adb9fa3 to your computer and use it in GitHub Desktop.
Python: Create an Email with Outlook
# -*- coding: utf-8 -*-
"""
@author: unknown
"""
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@xyz.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()
# http://itsecmedia.com/blog/post/2016/python-send-outlook-email/
import win32com.client
from win32com.client import Dispatch, constants
const=win32com.client.constants
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "I AM SUBJECT!!"
# newMail.Body = "I AM\nTHE BODY MESSAGE!"
newMail.BodyFormat = 2 # olFormatHTML https://msdn.microsoft.com/en-us/library/office/aa219371(v=office.11).aspx
newMail.HTMLBody = "<HTML><BODY>Enter the <span style='color:red'>message</span> text here.</BODY></HTML>"
newMail.To = "email@demo.com"
attachment1 = r"C:\Temp\example.pdf"
newMail.Attachments.Add(Source=attachment1)
newMail.display()
newMail.send()
@ivancans
Copy link

ivancans commented Oct 8, 2019

Hi,
Why does adding "r" in front of "C:\Temp\example.pdf" works but without, it doesn't?

@bitknol
Copy link

bitknol commented May 6, 2020

Hi,
Why does adding "r" in front of "C:\Temp\example.pdf" works but without, it doesn't?

@ivancans, "r" stands for raw string which accepts special characters. Otherwise you need to use double back slash to recognize '\' as a character in the file path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment