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.
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 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.
I've been trying to make a python script to send a happy birthday email on a given date, that notifies me who it sent an email to via text message.
I have 3 files.
First I have a brithdays.csv file which I enter all the birthday data that is going to use.
Here's an example of what's inside the file:
name,email,year,month,day
Ivy,Testemail#mail.com,1,3,25
Rose,Testemail#mail.com,1,3,28
Kimberly,Testemail#mail.com,1,4,10
Then I have a letter template which the script reads and replaces [NAME] with the name in the CSV file :
Greetings,
Im wishing [NAME] a very happy birthday! [NAME], 😊 I hope you enjoy your day and wishing you more life.
Thank you,
And then I have my actual code
############## IMPORTS ##############
import smtplib
import datetime as dtime
import pandas as pd
import random
from time import strftime
from email.mime.text import MIMEText
############## Reading Data and Check Current Day & Month ##############
# READ CSV BIRTHDAY FILE
df = pd.read_csv("birthdays.csv")
# PRINT CURRENT DAY
current_day = dtime.datetime.now().day
current_month = dtime.datetime.now().month
##################ENTER LOGIN HERE#############################
LOGIN = "EMAIL"
PASS = "PASSWORD"
############## LOGIC ##############
# save the rows that has the current day in new variable
new_df = df.loc[df['day'] == current_day]
# check the length of new_df of the current month so if the result is larger than 1
# so there is birthdays on this day
if len(new_df.loc[new_df['month'] == current_month]) > 0:
# check the length of people having birthday in this day
for i in range(len(new_df.loc[new_df['month'] == current_month])):
# OPEN BIRTHDAY TEMPLATE
with open(f"./letter_1.txt") as letter_file:
# READING FILE
letter_contents = letter_file.read()
#CREATE NAME VARIABLE
name = df["name"][i]
# replace [NAME] with actual name on the data
if len(new_df["name"]) > 1:
the_letter = letter_contents.replace("[NAME]", new_df["name"][i])
the_email = new_df["email"][i]
else:
the_letter = letter_contents.replace("[NAME]", new_df["name"].item())
the_email = new_df["email"].item()
# SMTPLIB LOGIN TO SEND EMAIL
# CONNECTION
with smtplib.SMTP("smtp.outlook.com") as con:
# START
con.starttls()
# LOGIN
con.login(user=LOGIN, password=PASS)
# create the msg
msg = MIMEText(the_letter, 'html')
msg["From"] = LOGIN
msg["To"] = the_email
msg["Subject"] = "Happy Birthday " + name + "!!!"
msg["Cc"] = "CC EMAILS"
# SEND EMAIL
con.send_message(msg)
#SENDS TEXT MESSAGE CONFIRMATION
msg = MIMEText ("Sent Happy Birthday Email to " + name + " on " + str(text.strftime('%Y-%m-%d %H:%M:%S %p')))
msg["From"] = LOGIN
msg["To"] = "VERIZONPHONENUMBER#vtext.com"
# SEND TEXT
con.send_message(msg)
# LOGS OUT OF EMAIL
con.quit()
I think the issue lies in Line 45 where I create the name variable.
My issue is that every time it sends an email, the name in the Subject of the email and in the text message I receive it's the first name of the list.
For example if I run the script, the email would look something like this
Happy Birthday Ivy!!!
Greetings,
Im wishing Rose a very happy birthday! Rose, 😊 I hope you enjoy your day and wishing you more life.
I'm trying to make the name that appears on the subject match with the name that appears on the body of text.
msg = MIMEText ("Sent Happy Birthday Email to " + name + " on " + str(text.strftime('%Y-%m-%d %H:%M:%S %p')))
Here you are using the name variable when generating the body but earlier in your code you have:
name = df["name"][i]
Which grabs the name from the unfiltered DataFrame but you use the filtered DataFrame to generate the subject line here:
# replace [NAME] with actual name on the data
if len(new_df["name"]) > 1:
the_letter = letter_contents.replace("[NAME]", new_df["name"][i])
the_email = new_df["email"][i]
else:
the_letter = letter_contents.replace("[NAME]", new_df["name"].item())
the_email = new_df["email"].item()
The i-th element in the filtered DataFrame might not be the i-th element in your original DataFrame so you need to declare name as follows:
name = new_df["name"][i]
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.
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)