I am trying to read emails from Outlook using a specific date range as well as other criteria - sender, subject etc. However, I am unsure as to how to specify a date range within which Python can search for the emails. This is what I have so far which generates the type error below:
if subject in message.subject and date in message.senton.date():
TypeError: argument of type 'datetime.date' is not iterable
import win32com.client
import datetime
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(18).Folders.Item("xxxxx")
messages = inbox.Items
date = datetime.date.today()
subject = "xxxxxxx"
for message in messages:
if subject in message.subject and date in message.senton.date():
print(message.senton.time())
I would like to search for emails within a specific date range, as well as be able to use more than one criteria to search. E.g specify the subject as well as sender etc. But I am not sure how, I am new to Python so please help!
Try this
if subject in message.subject and date == message.senton.date():
print(message.senton.time())
print(message.sender)
Edit:
if you want date range you can use datetime to define the date range
start = message.senton.date() - timedelta(days=10)
end = message.senton.date() + datetime.timedelta(days=10) # 20 days date range
if subject in message.subject and date > start and date < end:
print(message.senton.time())
print(message.sender)
instead of looping through every message, outlook provides an api to query the exact subject:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.Folders.Item(3).Folders['Inbox'].Folders['My Folder']
filt = "#SQL=""http://schemas.microsoft.com/mapi/proptag/0x0037001f"" = '{0}'".format(subject)
messages=inbox.Items.Restrict(filt)
Related
I'm Jan and it's my first post here and the following code is also my first python code. So please don't judge me, if the code is not well shaped :) and don't wonder I had to reduce my mail body.
With the following code I try to generate several msg file depending on a user list called "customer_names". The idea is to iterate through this list and to adjust the email body espacially the placeholder for "Customer". The rest of the body content is not so important. Everything works good except the iteration through the list. I have a suggestion that I may need to increment the index for the list in the loop. Do you have any ideas.
import win32com.client as win32
import datetime
import random
# List of customer names
customer_names = ['Name1','Name2','Name3']
current_customer_index = 0
# List of email providers
email_providers = ['provider1', 'provider2', 'provider3']
# set up the Outlook application
outlook = win32.Dispatch('outlook.application')
# create a new email
mail = outlook.CreateItem(0)
# set the subject and recipients
mail.Subject = "Request for Customer Information"
mail.To = "user#emailprovider.net"
# Message body for the email
message = f"Dear User,\n\nThe information we require from [Customer] is as follows:\n\n- Email Address: [Email Address] \n\nWe kindly request that you send the requested information to us within [number of days] days. \n\n Kind regards."
# set the number of days for the customer to respond
num_days = 7
# set the importance of the email to normal
mail.Importance = 1 # 0=Low, 1=Normal, 2=High
# set the sensitivity of the email to normal
mail.Sensitivity = 0 # 0=Normal, 1=Personal, 2=Private, 3=Confidential
# set the read receipt option to true
mail.ReadReceiptRequested = True
# add a reminder for the sender to follow up in 3 days
mail.FlagRequest = "Follow up"
mail.FlagDueBy = (datetime.date.today() + datetime.timedelta(days=3)).strftime('%m/%d/%Y')
# Generate a random email
for i in range(len(customer_names)):
customer = customer_names[i]
message_with_data = message.replace("[Customer]", customer)
message_with_data = message_with_data.replace("[number of days]", str(num_days))
mail.Body = message_with_data
file_name = "Request_" + customer + ".msg"
file_path = "C:/Users/user/Desktop/Email/" + file_name
mail.SaveAs(file_path)
I have automated an outlook email with a python script. What I'd like to do now is enter next weeks date in the body of the email.
Is there any function that will allow me to do this?
For example I want to send an email and in the email I want the ask the recipient to respond by the 29th of April (Exactly a week from todays date). Is there a way I can read todays date and then print out a date that is 7 days later in the email?
Sample code:
import win32com.client as client
import pathlib
import pandas as pd
outlook = client.Dispatch('Outlook.Application')
#Mail item
message = outlook.CreateItem(0)
df = pd.read_excel(r'Desktop\Review.xlsx',index_col=False,sheet_name='Review', usecols = "A:H")
#Display message
body = df.to_html()
message.Display()
message.To = "Mick.callnan#something.com"
message.Subject = "Review"
message.HTMLBody = "Hi All, <br> <br>Please respond by this day next week **Enter date here**
#message.Send()
import datetime
# how many days allowance?
N = 7
# assign the deadline date
deadline = datetime.date.today() + datetime.timedelta(days=N)
# on its own, it already works...
print(f"Please respond by {deadline}.")
# prints out Please respond by 2021-04-29.
# but perhaps you want to format it
s = deadline.strftime("%d %b %Y")
print(f"Please respond by {s}.")
# prints out Please respond by 29 Apr 2021.
By the way, please check out https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior on your own for the format codes.
I am trying to use the restrict method to search for emails where the subject equals a certain string, however, this string changes slightly everyday since the sender adds the current date. I am trying to use a variable which would contain the current date and insert it into the restrict method.
I keep getting an invalid syntax error message specifically with regards to the Restrict line.
from datetime import datetime, timedelta
received_dt = datetime.now()
received_dt = received_dt.strftime('%Y-%m-%d')
subject_search_string = "Daily Statement" + recevied_dt
msg = msg.Restrict("[Subject] = " subject_search_string)
The subject value must be single-quoted:
msg = msg.Restrict("[Subject] = '" subject_search_string "'")
I am new to Python. I am scanning Outlook inbox looking for a specific subject (YES). If I find that subject, get the sender email and check if that sender is in my emailing list, if not, add them to my emailing list.
I am stuck with the IF statement comparing the sender with what I have in my dataframe. EmailList.xlsx has 1 column "Name" and 8 entries "LastName, FirstName I"
import win32com.client
import os
import pandas as pd
get_path = os.getcwd()
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
EmailList = (pd.read_excel("EmailList.xlsx", sheet_name='ABC', index_col=0))
EmailList.info() #<<-- I can see my dataframe, column name and number of entries.
a=len(messages)
if a > 0:
for messages2 in messages:
subject = messages2.Subject
if "YES" in subject:
sender = messages2.Sender
print(subject) #<<-- Works fine, I see the subject
print(sender) #<<-- Works fine, I see the sender
if EmailList ['Name'] == sender: <<-- does not work
if EmailList ['Name'].str.contains(sender).any(): <<-- does not work
print("Your are already subscribed")
else:
print("append DF")
Any ideas? I am guessing there is something with the "sender" string, but I cannot figure it out.
SOLVED!!
sender = messages2.SenderName
&
if EmailList['Name'].str.contains(sender).any():
I am trying to send meeting invites from outlook using python. I also want to reflect that in the outlook calendar of the receiver. I am using the following code
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
def sendRecurringMeeting():
appt = outlook.CreateItem(1) # AppointmentItem
appt.Start = "2018-11-14 15:30" # yyyy-MM-dd hh:mm
appt.Subject = "Important"
appt.Duration = 60 # In minutes (60 Minutes)
appt.Location = "Floor 5"
appt.MeetingStatus = 1 # 1 - olMeeting; Changing the appointment to meeting. Only after changing the meeting status recipients can be added
appt.Recipients.Add("mabc#abc.com") # Don't end ; as delimiter
appt.Recipients.Add("xyz#xyz.com")
appt.ReminderSet = True
appt.ReminderMinutesBeforeStart = 15
# Set Pattern, to recur every day, for the next 5 days
pattern = appt.GetRecurrencePattern()
pattern.RecurrenceType = 0
pattern.Occurrences = "1"
appt.Save()
appt.Send()
sendRecurringMeeting()
Here I am trying to send meeting invites from outlook with Python. Generally when we send a meeting invite, It starts showing in their calendar that you have a meeting today at the mentioned time. By using the above code, I am able to send a meeting invite but it is not showing in their calendar i.e it is not giving reminders.