Skip to content

Instantly share code, notes, and snippets.

@nathanganser
Created November 6, 2023 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanganser/87636c31dee8869ec0bd9b46739e2ec8 to your computer and use it in GitHub Desktop.
Save nathanganser/87636c31dee8869ec0bd9b46739e2ec8 to your computer and use it in GitHub Desktop.
Working function that adds calendar event to calendar (ICS / Calendar / Outlook / Gmail)
def send_appointment(attendee_email, organiser_email, subj, description, location, start_hour, start_minute):
# Timezone to use for our dates - change as needed
tz = pytz.timezone("Europe/London")
start = tz.localize(dt.datetime.combine(datetime.utcnow(), dt.time(start_hour, start_minute, 0)))
# Build the event itself
cal = icalendar.Calendar()
cal.add('prodid', '-//My calendar application//example.com//')
cal.add('version', '2.0')
cal.add('method', "REQUEST")
event = icalendar.Event()
event.add('attendee', attendee_email)
event.add('organizer', organiser_email)
event.add('status', "confirmed")
event.add('category', "Event")
event.add('summary', subj)
event.add('description', description)
event.add('location', location)
event.add('dtstart', start)
event.add('dtend', tz.localize(dt.datetime.combine(datetime.utcnow(), dt.time(start_hour + 1, start_minute, 0))))
event.add('dtstamp', tz.localize(dt.datetime.combine(datetime.utcnow(), dt.time(6, 0, 0))))
event['uid'] = uuid.uuid4() # Generate some unique ID
event.add('priority', 5)
event.add('sequence', 1)
event.add('created', tz.localize(dt.datetime.now()))
# Add a reminder
alarm = icalendar.Alarm()
alarm.add("action", "DISPLAY")
alarm.add('description', "Reminder")
event.add_component(alarm)
cal.add_component(event)
# Build the email message and attach the event to it
msg = MIMEMultipart("alternative")
msg["Subject"] = subj
msg["From"] = organiser_email
msg["To"] = attendee_email
msg["Content-class"] = "urn:content-classes:calendarmessage"
msg.attach(MIMEText(description))
filename = "invite.ics"
part = MIMEBase('text', "calendar", method="REQUEST", name=filename)
part.set_payload(cal.to_ical())
encode_base64(part)
part.add_header('Content-Description', filename)
part.add_header("Content-class", "urn:content-classes:calendarmessage")
part.add_header("Filename", filename)
part.add_header("Path", filename)
msg.attach(part)
smtp = smtplib.SMTP('smtp.postmarkapp.com', 587)
smtp.starttls()
smtp.login(os.environ['POSTMARK_KEY'], os.environ['POSTMARK_KEY'])
# Send the email out
smtp.sendmail(msg["From"], [msg["To"]], msg.as_string())
smtp.quit()
send_appointment("nathan.ganser@interspark.com", "test@autogmail.com", "Meeting test", "What a day\nGreat.", "https://zoom.com/9989898", 10, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment