Sending emails from outlook using python - python

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.

Related

Python generated *.msg file

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)

Error "Invalid Time Format" when using pychatkit

I am trying to code a homework list script that sends the homework to a group chat every day but I keep getting a invalid time format error because of pywhatkit. The error message only disappears when I delete the +65 but another error message will pop up saying that there is no country code for the number. I'm not sure how to solve it since I am trying to send to a group chat and not a phone number.
import pywhatkit
import datetime
# Dictionary to store the homework assignments and their due dates
homework_dict = {}
# Function to add a homework assignment to the dictionary
def add_homework(assignment, due_date):
homework_dict\[assignment\] = due_date
# Function to delete homework assignments that are due one day before the actual due date
def delete_overdue_homework():
# Check the current date
now = datetime.datetime.now()
# Calculate the date one day before the current date
yesterday = now - datetime.timedelta(days=1)
# Delete any assignments that are due on the calculated date
for assignment, due_date in homework_dict.items():
if due_date == yesterday.date():
del homework_dict\[assignment\]
# Function to send the homework list to the WhatsApp group chat
def send_homework_list():
# Check the current date
now = datetime.datetime.now()
# Initialize the message with the current date
message = "Homework of the day (" + now.strftime("%B %d, %Y") + "):\\n"
# Add each homework assignment to the message
for assignment, due_date in homework_dict.items():
\# If the due date has not passed, add the assignment to the message
if due_date \>= now.date():
message += " - " + assignment + "\\n"
# Calculate the hour to send the message (current hour + 18)
send_hour = (now.hour + 18) % 24
# Send the message to the WhatsApp group chat
pywhatkit.sendwhatmsg("+65 Homework List", send_hour, 0, message)
# Add some homework assignments for testing
add_homework("Math worksheet", datetime.date(2023, 1, 10))
add_homework("Science reading", datetime.date(2023, 1, 11))
add_homework("English essay", datetime.date(2023, 1, 15))
# Send the homework list to the WhatsApp group chat at 6:00 PM every day
while True:
delete_overdue_homework()
send_homework_list()
# Wait for 24 hours before sending the list again
time.sleep(24*60*60)
When I used 18, 0, for 6PM so I tried a different solution but it still shows as an error.

Python Outlook - Add date to email

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.

How can I add an email to an existing calendar entry using exchangelib?

I have an existing calendar event already scheduled.
I am trying to add a number of emails to that existing event, but when I run this function it adds a new event.
I need to be able to: find the event, add the specified email to the event, have the email added get the invitation.
(I'm new to python so try not to judge harshly)
def updateInvite(pEmail,pSubj,iY, iM, iD, iHH, iMM):
pytz_tz = pytz.timezone('America/New_York')
tz = EWSTimeZone.localzone()
items = account.calendar.view(
start=tz.localize(EWSDateTime(iY, iM, iD, iHH, iMM)),
end=tz.localize(EWSDateTime(iY, iM, iD, iHH + 2, iMM)),
)`
for item in items:
sEventSubj = item.subject
item.save(update_fields=['required_attendees'])
Is called with
pEmail = 'name.last#company.com'
sSubj = 'Invite Test Meeting with Teams link'
iY = 2020
iD = 29
iM = 4
iHH = 16
iMM = 30
updateInvite(pEmail, sSubj, iY, iM, iD, iHH, iMM)
To do this, use an item attachment. Find the message you would like to attach to your calendar item and create an item attachment for it:
from exchangelib import ItemAttachment
# Create some filter to get the emails you want to attach
messages = account.inbox.all()[:5]
# Create a filter go get your calendar item
item = account.calendar.get(subject='Hello Python')
for message in messages:
# Create the attachment and give it a name
attachment = ItemAttachment(name='msg %s' % msg.id[:8], item=message)
item.attach(attachment)

Reading Emails From Outlook with Python & Specifying a Date Range

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)

Categories