Sub createfolderandmovemail()
Dim olApp, mail, fldr As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim olmailitem As Outlook.MailItem
Dim count As Integer
Dim xDate As Date
Dim DateStart As Date
Dim DateEnd As Date
'get date 1 day back
DateStart = Date - 1
'get todays date
DateEnd = Date
Dim datetocheck As String
'MsgBox (xDate)
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com")
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
'Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("[Gmail]")
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("Inbox")
'lets try to access test under inbox
On Error Resume Next
Set fldr = olFolder.Folders("test")
'if test does not exist
If fldr Is Nothing Then
Set fldr = olFolder.Folders.Add("test")
End If
On Error GoTo 0
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
'Set olFolder = olFolder.Folders("Inbox")
'numeral
'Set itmemail = filteredList.Find("[Importance]=2") 'mail with high importance
'we can use a variable like this
'strFind = "[Importance]=2"
'boolean
'strFind = "[UnRead]=False"
'search by date and time
datetocheck = "[ReceivedTime] >= '" & Format(DateStart, "ddddd h:nn AMPM") & "' And [ReceivedTime] <= '" & Format(DateEnd, "ddddd h:nn AMPM") & "'"
MsgBox (datetocheck)
'For Each i In olFolder.Items.Restrict(datetocheck)
'
' ' If the email is an Outlook email
' If i.Class = olMail Then
'
' Set mi = i
' UserForm1.Show
' ' If there are more than 0 attachments, ie, if it finds an attachment
' If mi.Attachments.count > 0 Then
'
'
' For Each at In mi.Attachments
' 'Debug.Print mi.SenderName & " " & mi.ReceivedTime ' <- uncomment this part if you need to debug (remember to open the "immediate" window also
' ' Look for attachments that contain ".xls" (this will also pick up ".xlsx" and ".xlsm" etc
' If InStr(LCase(at.Filename), ".xls") > 0 Then
' ' Tell the script where to save the file and what details need to be appeneded to the file name to make it a unique name
' at.SaveAsFile "\\xxxx\xxxxx\xxxxx\" & Format(mi.ReceivedTime, "yyyy-mm-dd hh-nn-ss") & at.Filename
'
' Else
'
' ' literally do nothing (it's probably not needed but added just in case)
'
' End If
'
'
' Next at
'
' End If
'
' End If
' Next i
MsgBox (olFolder.Items.Restrict(datetocheck).count)
For i = olFolder.Items.Restrict(datetocheck).count To 1 Step -1
' If the email is an Outlook email
If olFolder.Items.Restrict(datetocheck).Item(i).Class = 43 Then
'Debug.Print i.Subject, i.SenderName, i.ReceivedTime
olFolder.Items.Restrict(datetocheck).Item(i).Move fldr
End If
Next i
End Sub
Friday, September 24, 2021
Create a subfolder and move filtered mails based on two date range in outlook using vba
Move filtered mails from a folder by date range to a different folder in a different way in outlook using vba
Sub movemailtoafolder_working()
Dim olApp, mail As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim olmailitem As Outlook.MailItem
Dim count As Integer
Dim xDate As Date
Dim DateStart As Date
Dim DateEnd As Date
'get date 1 day back
DateStart = Date - 1
'get todays date
DateEnd = Date
Dim datetocheck As String
'MsgBox (xDate)
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com")
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
'Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("[Gmail]")
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("Inbox")
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
'Set olFolder = olFolder.Folders("Inbox")
'numeral
'Set itmemail = filteredList.Find("[Importance]=2") 'mail with high importance
'we can use a variable like this
'strFind = "[Importance]=2"
'boolean
'strFind = "[UnRead]=False"
'search by date and time
datetocheck = "[ReceivedTime] >= '" & Format(DateStart, "ddddd h:nn AMPM") & "' And [ReceivedTime] <= '" & Format(DateEnd, "ddddd h:nn AMPM") & "'"
MsgBox (datetocheck)
'For Each i In olFolder.Items.Restrict(datetocheck)
'
' ' If the email is an Outlook email
' If i.Class = olMail Then
'
' Set mi = i
' UserForm1.Show
' ' If there are more than 0 attachments, ie, if it finds an attachment
' If mi.Attachments.count > 0 Then
'
'
' For Each at In mi.Attachments
' 'Debug.Print mi.SenderName & " " & mi.ReceivedTime ' <- uncomment this part if you need to debug (remember to open the "immediate" window also
' ' Look for attachments that contain ".xls" (this will also pick up ".xlsx" and ".xlsm" etc
' If InStr(LCase(at.Filename), ".xls") > 0 Then
' ' Tell the script where to save the file and what details need to be appeneded to the file name to make it a unique name
' at.SaveAsFile "\\xxxx\xxxxx\xxxxx\" & Format(mi.ReceivedTime, "yyyy-mm-dd hh-nn-ss") & at.Filename
'
' Else
'
' ' literally do nothing (it's probably not needed but added just in case)
'
' End If
'
'
' Next at
'
' End If
'
' End If
' Next i
MsgBox (olFolder.Items.Restrict(datetocheck).count)
For i = olFolder.Items.Restrict(datetocheck).count To 1 Step -1
' If the email is an Outlook email
If olFolder.Items.Restrict(datetocheck).Item(i).Class = 43 Then
'Debug.Print i.Subject, i.SenderName, i.ReceivedTime
olFolder.Items.Restrict(datetocheck).Item(i).Move olFolder.Folders("test")
End If
Next i
End Sub
Move mails filtered by date range to a specified folder in out using VBA
Sub movemailtofolder()
Dim ol As Object 'Outlook.Application
Dim ns As Object 'Outlook.Namespace
Dim inboxFol As Object 'Outlook.Folder
Dim subFol As Object 'Outlook.Folder
Dim itm As Object
Dim mi As Object 'Outlook.MailItem
Dim att As Object 'Outlook.Attachment
Dim fso As Object 'Scripting.FileSystemObject
Dim dirName As String
Dim xDate As Date
Dim DateStart As Date
Dim DateEnd As Date
'get date 1 day back
DateStart = Date - 1
'get todays date
DateEnd = Date
Dim datetocheck As String
'Some Set Ups
Set fso = CreateObject(Class:="Scripting.FileSystemObject")
Set ol = CreateObject(Class:="Outlook.Application")
Set ns = ol.GetNamespace("MAPI")
Set inboxFol = ns.Folders("allsourav@gmail.com").Folders("Inbox") 'olFolderInbox
Set subFol = inboxFol.Folders("test")
' dirName = "D:\XYZ"
' If Not fso.FolderExists(dirName) Then
' fso.CreateFolder dirName
' End If
'search by date and time
datetocheck = "[ReceivedTime] >= '" & Format(DateStart, "ddddd h:nn AMPM") & "' And [ReceivedTime] <= '" & Format(DateEnd, "ddddd h:nn AMPM") & "'"
MsgBox (datetocheck)
'Finding the search item from Oulook Inbox
For Each itm In inboxFol.Items.Restrict(datetocheck)
If itm.Class = 43 Then
Set mi = itm
' If mi.Attachments.count > 0 And InStr(mi.SenderEmailAddress, "xxxxxxx@inc.ae") Then
' 'Saving Attachments to a folder
' For Each att In mi.Attachments
' If Right(att.Filename, 4) = "xlsm" Then
' att.SaveAsFile dirName & "\" & Range("Ad2").Text & ".xlsm"
' End If
' Next att
' 'Move mail item to subfolder
' mi.Move subFol
' End If
mi.Move subFol
End If
Next itm
End Sub
Source:https://techcommunity.microsoft.com/t5/excel/vba-moving-a-mail-from-inbox-to-a-specific-folder/m-p/1926973
Thursday, September 23, 2021
Get messages sent on between now and last 10 days using restrict in outlook using python
import win32com.client
import os
import time
import datetime as dt
# this is set to the current time
date_time = dt.datetime.now()
# this is set to 10 days ago
oldDate = dt.datetime.now() - dt.timedelta(days=10)
#This is set to one minute ago
newDate = dt.datetime.now() - dt.timedelta(minutes = 1)
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
olFolder = outlook.Folders("allsourav@hotmail.com").Folders("Sent Items")
# retrieve all emails in the Sent Items, then sort them from most recently received to oldest (False will give you the reverse). Not strictly necessary, but good to know if order matters for your search
messages = olFolder.Items
messages.Sort("[ReceivedTime]", True)
# restrict to messages from the past hour based on ReceivedTime using the dates defined above.
# lastHourMessages will contain only emails with a ReceivedTime later than an hour ago
# The way the datetime is formatted DOES matter; You can't add seconds here.
last10DaysMessages = messages.Restrict("[ReceivedTime] >= '" +oldDate.strftime('%m/%d/%Y %H:%M %p')+"'")
print ("Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p'))
print ("Messages from the last 10 days in Sent Items folder:")
##for message in last10DaysMessages:
## print (message.subject,message.SentOn.strftime("%d-%m-%y"),message.ReceivedTime.strftime("%d-%m-%y"))
##
# GetFirst/GetNext will also work, since the restricted message list is just a shortened version of your full inbox.
print ("Using GetFirst/GetNext")
message = last10DaysMessages.GetFirst()
while message:
print (message.subject,message.SentOn.strftime("%d-%m-%y"),message.ReceivedTime.strftime("%d-%m-%y"))
message = last10DaysMessages.GetNext()
Source:https://www.py4u.net/discuss/161546
Filtering mails between two dates using restrict in outlook using vba
Sub findemail_working()
Dim olApp, mail As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim count As Integer
Dim xDate As Date
Dim DateStart As Date
Dim DateEnd As Date
'get date 1 day back
DateStart = Date - 1
'get todays date
DateEnd = Date
Dim datetocheck As String
'MsgBox (xDate)
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com")
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
'Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("[Gmail]")
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("Inbox")
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
'Set olFolder = olFolder.Folders("Inbox")
Dim itmemail As Outlook.MailItem
'numeral
'Set itmemail = filteredList.Find("[Importance]=2") 'mail with high importance
'we can use a variable like this
'strFind = "[Importance]=2"
'boolean
'strFind = "[UnRead]=False"
'search by date and time
datetocheck = "[ReceivedTime] >= '" & Format(DateStart, "ddddd h:nn AMPM") & "' And [ReceivedTime] <= '" & Format(DateEnd, "ddddd h:nn AMPM") & "'"
MsgBox (datetocheck)
'For Each i In olFolder.Items.Restrict(datetocheck)
'
' ' If the email is an Outlook email
' If i.Class = olMail Then
'
' Set mi = i
' UserForm1.Show
' ' If there are more than 0 attachments, ie, if it finds an attachment
' If mi.Attachments.count > 0 Then
'
'
' For Each at In mi.Attachments
' 'Debug.Print mi.SenderName & " " & mi.ReceivedTime ' <- uncomment this part if you need to debug (remember to open the "immediate" window also
' ' Look for attachments that contain ".xls" (this will also pick up ".xlsx" and ".xlsm" etc
' If InStr(LCase(at.Filename), ".xls") > 0 Then
' ' Tell the script where to save the file and what details need to be appeneded to the file name to make it a unique name
' at.SaveAsFile "\\xxxx\xxxxx\xxxxx\" & Format(mi.ReceivedTime, "yyyy-mm-dd hh-nn-ss") & at.Filename
'
' Else
'
' ' literally do nothing (it's probably not needed but added just in case)
'
' End If
'
'
' Next at
'
' End If
'
' End If
' Next i
For Each i In olFolder.Items.Restrict(datetocheck)
' If the email is an Outlook email
If i.Class = olMail Then
Debug.Print i.Subject, i.SenderName, i.ReceivedTime
End If
Next i
End Sub
Wednesday, September 22, 2021
Find emails between two dates in outlook using python
import sys, win32com.client as client, datetime
import datetime,time
# Connect with MS Outlook - must be open.
outlook=client.Dispatch("Outlook.Application")
d = (datetime.date.today() - datetime.timedelta (days=7)).strftime("%d-%m-%y")
print(d)
olFolder = outlook.GetNamespace("MAPI").Folders("allsourav@hotmail.com").Folders("Sent Items")
itmemail = outlook.Createitem(0)
messages = olFolder.Items
#to find mail in my sent items folder having a date which is 7 days ago
##
##for msg in messages:
## if(msg.SentOn.strftime("%d-%m-%y")==d):
## print (msg.Subject,msg.SentOn.strftime("%d-%m-%y"))
#to find a mail in between a time period
#print(datetime.datetime.now().strftime("%d/%m/%Y"))
#get current date in day/month/year format
xDate=datetime.datetime.now().strftime("%d/%m/%Y")
print(xDate)
#get current date in day/month/year format
xDate=datetime.date.today()
print(xDate)
#get two days back from today
days = datetime.timedelta(2)
xDate = xDate - days
print(xDate)
print(datetime.date.today()-datetime.timedelta(6))
print(datetime.date.today()-datetime.timedelta(10))
for msg in messages:
if (msg.SentOn.date()<(datetime.date.today()-datetime.timedelta(6))) and (msg.SentOn.date()>(datetime.date.today()-datetime.timedelta(10))) :
print (msg.Subject,msg.SentOn.strftime("%d-%m-%y"))
Find email by day in a folder in outlook using python
#here we are trying to find mails in my sent items folder 7 days ago
import sys, win32com.client as client, datetime
# Connect with MS Outlook - must be open.
outlook=client.Dispatch("Outlook.Application")
d = (datetime.date.today() - datetime.timedelta (days=7)).strftime("%d-%m-%y")
print(d)
olFolder = outlook.GetNamespace("MAPI").Folders("allsourav@hotmail.com").Folders("Sent Items")
itmemail = outlook.Createitem(0)
messages = olFolder.Items
for msg in messages:
if(msg.SentOn.strftime("%d-%m-%y")==d):
print (msg.Subject,msg.SentOn.strftime("%d-%m-%y"))
Monday, September 20, 2021
Find mail by date time,unread status or importance(high normal or low) in outlook using vba
Dim olApp, olAccts, olInspect, filteredList As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim count As Integer
Dim xDate As Date
'get yesterday date
xDate = Date - 2
'MsgBox (xDate)
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com")
'If (olFolder.Folders.count > 0) Then
' For Each Folder In olFolder.Folders
' MsgBox (Folder.Name)
'
' Next
'End If
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("[Gmail]")
If (olFolder.Folders.count > 0) Then
For Each Folder In olFolder.Folders
MsgBox (Folder.Name)
Next
End If
Set olFolder = olFolder.Folders("Sent Mail")
Dim itmemail As Outlook.MailItem
Set filteredList = olFolder.Items
'numeral
'Set itmemail = filteredList.Find("[Importance]=2") 'mail with high importance
'we can use a variable like this
'strFind = "[Importance]=2"
'boolean
'strFind = "[UnRead]=False"
'search by date and time
strFind = "[ReceivedTime] >= '" & CStr(xDate - 10) & " 12:00AM' AND [ReceivedTime] < '" & CStr(xDate - 1) & " 12:00AM'"
MsgBox (strFind)
Set itmemail = filteredList.Find(strFind)
While Not itmemail Is Nothing
Debug.Print itmemail.Subject, itmemail.SenderName, itmemail.ReceivedTime
Debug.Print itmemail.Body
On Error Resume Next
Set itmemail = filteredList.FindNext
Wend
End Sub
Accessing sub folders in outlook using vba
here I am trying to access a folder named test under inbox
Sub accessFolderbyName()
Dim olApp, olAccts, olInspect As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim count As Integer
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@hotmail.com").Folders("Inbox").Folders("test")
'Set olFolder = olFolder.Folders("test")
For Each msg In olFolder.Items
' MsgBox msg.Subject
Next
'now let us loop through the mail items in that folder
For Each itmmail In olFolder.Items
If itmmail.SentOnBehalfOfName = "allsourav@hotmail.com" Then
count = count + 1
End If
Next itmmail
MsgBox (count)
Dim itmcount As Integer
itmcount = olFolder.Items.count
MsgBox itmcount
count = 0
Dim x As Integer
'reading mail older to newer
For x = 1 To itmcount
If olFolder.Items(x).SentOnBehalfOfName = "allsourav@hotmail.com" Then
count = count + 1
End If
Next x
MsgBox (count)
count = 0
'reading mail in reverse order ,new to old
For x = itmcount To 1 Step -1
If olFolder.Items(x).SentOnBehalfOfName = "allsourav@hotmail.com" Then
count = count + 1
End If
Next x
MsgBox (count)
End Sub
Accessing a folder by name and looping through items inside it in outlook using python
import win32com.client as client
import datetime,time
from os import path
outlook=client.Dispatch("Outlook.Application")
count = 0
olFolder = outlook.GetNamespace("MAPI").Folders("allsourav@hotmail.com").Folders("Sent Items")
#now let us loop through the mail items in that folder
for itmmail in olFolder.Items:
if (itmmail.SentOnBehalfOfName =="allsourav@hotmail.com"):
count = count + 1
print(count)
##Dim itmcount As Integer
itmcount = olFolder.Items.count
print(itmcount)
count = 0
##Dim x As Integer
##
##'reading mail older to newer
##
for x in range(1,itmcount):
##
if (olFolder.Items(x).SentOnBehalfOfName == "allsourav@hotmail.com"):
count = count + 1
print(count)
##
count = 0
##'reading mail in reverse order ,new to old
##
for x in range(itmcount,1,-1):
if (olFolder.Items(x).SentOnBehalfOfName == "allsourav@hotmail.com"):
count = count + 1
##End If
##Next x
print(count)
Sunday, September 19, 2021
Accessing a folder by name and looping through items inside it in outlook using vba
Sub accessFolderbyName()
Dim olApp, olAccts, olInspect As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim count As Integer
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@hotmail.com").Folders("Sent Items")
'now let us loop through the mail items in that folder
For Each itmmail In olFolder.Items
If itmmail.SentOnBehalfOfName = "allsourav@hotmail.com" Then
count = count + 1
End If
Next itmmail
MsgBox (count)
Dim itmcount As Integer
itmcount = olFolder.Items.count
MsgBox itmcount
count = 0
Dim x As Integer
'reading mail older to newer
For x = 1 To itmcount
If olFolder.Items(x).SentOnBehalfOfName = "allsourav@hotmail.com" Then
count = count + 1
End If
Next x
MsgBox (count)
count = 0
'reading mail in reverse order ,new to old
For x = itmcount To 1 Step -1
If olFolder.Items(x).SentOnBehalfOfName = "allsourav@hotmail.com" Then
count = count + 1
End If
Next x
MsgBox (count)
End Sub
Access outlook folder by name using vba
Sub accessFolderbyName()
Dim olApp, olAccts, olInspect As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@hotmail.com").Folders("Sent Items")
End Sub
Saturday, September 18, 2021
Adding signature other than default in outlook using python
import win32com.client as client
import datetime,time
from os import path
from tkinter import *
from tkinter import filedialog
data=""
def openSig(filepath):
print(filepath)
file=open(filepath,'r')
sig=(file.read())
file.close()
return sig
def sendmail(data):
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
#below lines are for default signature
#currentSig = "<br/>Thank You<br/><br/>Sourav Bhattacharya"
#olInspect = message.GetInspector #activates email,prompts signature to appear,not display
#currentSig = message.HTMLBody #contains nothing but signature now
filepath=path.expandvars(r'%APPDATA%\Microsoft\Signatures\demo (allsourav@hotmail.com).htm')
currentSig=openSig(filepath)
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.BodyFormat = 2 #olFormatHTML
#message.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
#message.htmlbody="<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
message.htmlbody=data + "<br />" + currentSig
message.Save()
message.Display()
time.sleep(5)
#message.Send()
def openFile():
filepath = filedialog.askopenfilename(initialdir="C:\\Users\\allso\\Desktop\\outlook programming",
title="Open file okay?",
filetypes= (("text files","*.txt"),
("all files","*.*")))
print(filepath)
file=open(filepath,'r')
data=(file.read())
file.close()
sendmail(data)
window=Tk()
button=Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Adding signature other than default in outlook using VBA
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim txtHtmlDemo, currentSig As String
Dim olApp, olAccts, olInspect As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
'currentSig = "<br/>Thank You<br/><br/>Sourav Bhattacharya"
With olNewMail
'Default Signature
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
'Set olInspect = olNewMail.GetInspector 'activates email,prompts signature to appear,not display
'currentSig = .HTMLBody 'contains nothing but signature now
'get signature other than default
currentSig = GetBoiler(Environ("Appdata") & "\Microsoft\Signatures\demo (allsourav@hotmail.com).htm")
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
txtHtmlDemo = Application.GetOpenFilename()
.BodyFormat = 2 'olFormatHTML
'.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
'.HTMLBody = "<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
'.HTMLBody = Sheets("Sheet1").Range("htmlBody1")
.HTMLBody = GetBoiler(txtHtmlDemo) & "<br />" & currentSig
.Display
'.Send
End With
End Sub
Function GetBoiler(ByVal sFile As String) As String
'sFile = "C:\Users\allso\AppData\Roaming\Microsoft\Signatures\demo.htm"
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readAll
ts.Close
End Function
Friday, September 17, 2021
Adding default signature at the end of outlook mail using python
import win32com.client as client
import datetime,time
from tkinter import *
from tkinter import filedialog
data=""
def sendmail(data):
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
currentSig = "<br/>Thank You<br/><br/>Sourav Bhattacharya"
olInspect = message.GetInspector #activates email,prompts signature to appear,not display
currentSig = message.HTMLBody #contains nothing but signature now
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.BodyFormat = 2 #olFormatHTML
#message.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
#message.htmlbody="<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
message.htmlbody=data + "<br />" + currentSig
message.Save()
message.Display()
time.sleep(5)
#message.Send()
def openFile():
filepath = filedialog.askopenfilename(initialdir="C:\\Users\\allso\\Desktop\\outlook programming",
title="Open file okay?",
filetypes= (("text files","*.txt"),
("all files","*.*")))
print(filepath)
file=open(filepath,'r')
data=(file.read())
file.close()
sendmail(data)
window=Tk()
button=Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Adding default signature at the end of the mail in outlook using VBA
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim txtHtmlDemo, currentSig As String
Dim olApp, olAccts, olInspect As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
'currentSig = "<br/>Thank You<br/><br/>Sourav Bhattacharya"
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
Set olInspect = olNewMail.GetInspector 'activates email,prompts signature to appear,not display
currentSig = .HTMLBody 'contains nothing but signature now
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
txtHtmlDemo = Application.GetOpenFilename()
.BodyFormat = 2 'olFormatHTML
'.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
'.HTMLBody = "<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
'.HTMLBody = Sheets("Sheet1").Range("htmlBody1")
.HTMLBody = GetBoiler(txtHtmlDemo) & "<br />" & currentSig
.Display
'.Send
End With
End Sub
Function GetBoiler(ByVal sFile As String) As String
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readAll
ts.Close
End Function
Adding a custom signature in outlook mail using Python
import datetime,time
from tkinter import *
from tkinter import filedialog
data=""
def sendmail(data):
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
currentSig = "<br/>Thank You<br/><br/>Sourav Bhattacharya"
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.BodyFormat = 2 #olFormatHTML
#message.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
#message.htmlbody="<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
message.htmlbody=data + "<br />" + currentSig
message.Save()
message.Display()
time.sleep(5)
#message.Send()
def openFile():
filepath = filedialog.askopenfilename(initialdir="C:\\Users\\allso\\Desktop\\outlook programming",
title="Open file okay?",
filetypes= (("text files","*.txt"),
("all files","*.*")))
print(filepath)
file=open(filepath,'r')
data=(file.read())
file.close()
sendmail(data)
window=Tk()
button=Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Adding a custom signature in outlook mail using VBA
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim txtHtmlDemo, currentSig As String
Dim olApp, olAccts As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
currentSig = "<br/>Thank You<br/><br/>Sourav Bhattacharya"
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
txtHtmlDemo = Application.GetOpenFilename()
.BodyFormat = 2 'olFormatHTML
'.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
'.HTMLBody = "<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
'.HTMLBody = Sheets("Sheet1").Range("htmlBody1")
.HTMLBody = GetBoiler(txtHtmlDemo) & "<br />" & currentSig
.Display
'.Send
End With
End Sub
Function GetBoiler(ByVal sFile As String) As String
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readAll
ts.Close
End Function
Getting html of a mail from a text file in outlook using python
import win32com.client as client
import datetime,time
from tkinter import *
from tkinter import filedialog
data=""
def sendmail(data):
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.BodyFormat = 2 #olFormatHTML
#message.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
#message.htmlbody="<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
message.htmlbody=data
message.Save()
message.Display()
time.sleep(5)
#message.Send()
def openFile():
filepath = filedialog.askopenfilename(initialdir="C:\\Users\\allso\\Desktop\\outlook programming",
title="Open file okay?",
filetypes= (("text files","*.txt"),
("all files","*.*")))
print(filepath)
file=open(filepath,'r')
data=(file.read())
file.close()
sendmail(data)
window=Tk()
button=Button(text="Open",command=openFile)
button.pack()
window.mainloop()
Thursday, September 16, 2021
large sized html bodies in outlook mail using python
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim olApp, olAccts As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
.BodyFormat = 2 'olFormatHTML
'.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
'.HTMLBody = "<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
.HTMLBody = Sheets("Sheet1").Range("htmlBody1")
.Display
'.Send
End With
End Sub
Creating more complex html email in outlook using python
import win32com.client as client
import datetime,time
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.BodyFormat = 2 #olFormatHTML
#message.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
message.htmlbody="<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
message.Save()
message.Display()
time.sleep(5)
message.Send()
Creating more complex html email in outlook using VBA
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim olApp, olAccts As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
.BodyFormat = 2 'olFormatHTML
'.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
.HTMLBody = "<h2>Welcome To The Best Online HTML Web Editor!</h2><p style=""font-size: 1.5em;"">You can <strong style=""background-color: #317399; padding: 0 5px; color: #fff;"">type your text</strong> directly in the editor or paste it from a Word Doc, PDF, Excel etc.</p><p style=""font-size: 1.5em;"">The <strong>visual editor</strong> on the right and the <strong>source editor</strong> on the left are linked together and the changes are reflected in the other one as you type! <img src=""https://html5-editor.net/images/smiley.png"" alt=""smiley"" /></p>"
.Display
'.Send
End With
End Sub
Creating html mail in outlook using python
import win32com.client as client
import datetime,time
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.BodyFormat = 2 #olFormatHTML
message.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
message.Save()
message.Display()
time.sleep(5)
message.Send()
Creating html mail in outlook using VBA
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim olApp, olAccts As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
.BodyFormat = 2 'olFormatHTML
.HTMLBody = "<html><h2>The body <span style='color:red'>of <b>Our Email </b></span></h2> <body>Regular Stuff Here <br/> New Line </body></html>"
.Display
'.Send
End With
End Sub
Send outlook mail from non primary account using VBA
'Used with GetDefaultFolder of the NameSpace
Public Const olFolderCalendar = 9 'The Calendar folder.
Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderContacts = 10 'The Contacts folder.
Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
Public Const olFolderDrafts = 16 'The Drafts folder.
Public Const olFolderInbox = 6 'The Inbox folder.
Public Const olFolderJournal = 11 'The Journal folder.
Public Const olFolderJunk = 23 'The Junk E-Mail folder.
Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
Public Const olFolderNotes = 12 'The Notes folder.
Public Const olFolderOutbox = 4 'The Outbox folder.
Public Const olFolderSentMail = 5 'The Sent Mail folder.
Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
Public Const olFolderTasks = 13 'The Tasks folder.
Public Const olFolderToDo = 28 'The To Do folder.
Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.
Sub setoutlookNS()
Dim olApp, olAccts As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"
.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True
Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If
Next olAcct
'MsgBox (olApp.Session.Accounts.Count)
.Display
.Send
End With
End Sub
Wednesday, September 15, 2021
Send outlook mail from non primary account using python
import win32com.client as client
import datetime
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
From = None
for myEmailAddress in outlook.Session.Accounts:
if str(myEmailAddress)=="allsourav@gmail.com":
From = myEmailAddress
break
if From != None:
# This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
message._oleobj_.Invoke(*(64209, 0, 8, 0, From))
##message.SentOnBehalfOfName='"Sourav IT Faculty" <allsourav@gmail.com>'
##this method does not work with new version of outlook,it is for sending
##mail from non primary account set up in outlook
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
#cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
#cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
#print(cSendDate)
#message.DeferredDeliveryTime=cSendDate
message.Save()
message.Display()
message.Send()
Tuesday, September 14, 2021
Instruct outlook to send a mail in future in a predetermined time using python(deferred delivery)
import win32com.client as client
import datetime
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
message.Subject="Happy Birthday on 14.09.2021"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
#message.DeferredDeliveryTime="15/09/2021 01:31:05 AM"
#cSendDate=datetime.date.today() #todays date
#cSendDate=(datetime.date.today() + datetime.timedelta (days=1)).strftime("%d-%m-%y") #tomorrows date
#cSendDate=datetime.datetime.now() + datetime.timedelta(days=1) #1 day from current datetime
cSendDate=datetime.datetime.now() + datetime.timedelta(minutes=2) #2 minutes from now
cSendDate=cSendDate.strftime("%d/%m/%Y %H:%M:%S %p") #formats the date like the outlook wants it in "15/09/2021 01:31:05 AM" in this format
print(cSendDate)
message.DeferredDeliveryTime=cSendDate
message.Save()
message.Display()
#message.Send()
Error connecting outlook from python using pywin32 ,server execution failed solved
As it is mentioned in the below page if outlook and python both are running ,both need to run in same privilege mode,either both in normal user or administrator(elevated) mode.
https://stackoverflow.com/questions/12705249/error-connecting-to-outlook-via-com
Monday, September 13, 2021
Line break in a mail body with Win32Com
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
message.Subject="Happy Birthday"
message.Body="Wish you a happy birthday ,\n learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
message.Save()
message.Display()
#message.Send()
Set Importance ,read receipt and delivery receipt statuses in outlook mail using python
import win32com.client as client
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
message.Subject="Happy Birthday"
message.Body="Wish you a happy birthday ,learning outlook using python again"
message.Importance=2
message.ReadReceiptRequested=True
message.OriginatorDeliveryReportRequested=True
message.Save()
message.Display()
#message.Send()
Creating and sending a mail using default folder using outlook in python
import win32com.client as client
outlook=client.Dispatch("Outlook.Application")
#message=outlook.Createitem(0)
namespace=outlook.GetNameSpace('MAPI')
inbox=namespace.GetDefaultFolder(6)
message=inbox.items.add
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
message.Subject="Happy Birthday"
message.Body="Wish you a happy birthday ,learning outlook using python again"
message.Save()
message.Display()
message.Send()
Creating a mail and send it using outlook in python
install pywin32
pip install pywin32
import win32com.client as client
outlook=client.Dispatch("Outlook.Application")
message=outlook.Createitem(0)
#namespace=outlook.GetNameSpace('MAPI')
#inbox=namespace.GetDefaultFolder(6)
message.To="allsourav@gmail.com;allsourav2@gmail.com"
message.CC="souravandamiya@gmail.com"
message.BCC="allsourav2@gmail.com"
message.Subject="Happy Birthday"
message.Body="Wish you a happy birthday ,learning outlook using python"
#message.Save()
message.Display()
#message.Send()