sendgrid / sendgrid-python

The Official Twilio SendGrid Python API Library
https://sendgrid.com
MIT License
1.53k stars 711 forks source link

ICS file from string example #977

Open JoueBien opened 3 years ago

JoueBien commented 3 years ago

There doesn't seem to be an example of how to use FileContent with string data. Therefore I just wanted to drop an example for those looking to do the same

from sendgrid.helpers.mail import Email, Personalization, Mail, Attachment, FileContent, FileName, FileType, Disposition

# set up a reusable string
event_ics_string ="""BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
CLASS:PUBLIC
DTSTART:{}
DTEND:{}
LOCATION:{}
SUMMARY: Klyk | {}
DESCRIPTION:{}
STATUS:CONFIRMED
END:VEVENT
END:VCALENDAR"""

# new mail instance
mail = Mail()

# set up the string that is used for the file contence
ics = ""+event_ics_string
ics = ics.format(
    eventIsoStartString, 
    eventIsoEndString, 
    event_url,
    event_name,
    event_description
)

# convert to correct format for FileContent - becuase it's incapable of hadling a standard string 
data = base64.b64encode(bytes(ics, 'utf-8')).decode()

# set up file atachment
attachedFile = Attachment(
    file_content=FileContent(data),
    file_name= FileName('invite.ics'),
    file_type='text/calendar',
    disposition=Disposition('attachment')
)

# add file to mail
mail.add_attachment(attachedFile)

# continue with presonlisation and then send mail
sg.client.mail.send.post(request_body=mail.get())

of you looking for the date format

date_time_instance.strftime("%A %b %d at %k:%M %p")
JenniferMah commented 3 years ago

Hi @JoueBien thanks for taking the time to create this example! Would you mind opening a PR to add this to our use-cases directory.

JoueBien commented 3 years ago

@JenniferMah No problem. I've just finished updating my own doc so I'll add a PR over the next 7 days.

JenniferMah commented 3 years ago

Ok perfect! Just make sure to include issue #977 in your PR description so that it can be linked to this issue.