Search code examples
pythongoogle-apigoogle-calendar-apigoogle-api-python-client

How to add attendees email from list in Google Calendar API


I have trouble adding emails from a list which has some user input emails into the event. Below is a function I made which will create an event;

    def submit():
        summary = title.get()
        location = local.get()
        s_date = start_date.get()
        s_time = start_time.get()
        final_s_date = s_date + "T" + s_time + ":00"
        e_date = end_date.get()
        e_time = end_time.get()
        final_e_date = e_date + "T" + e_time + ":00"
        service2 = get_calendar_api()
        event = {
            'summary': summary,
            'location': location,
            'description': 'Empty',
            'start': {
                'dateTime': final_s_date,
                'timeZone': 'Asia/Kuala_Lumpur',
            },
            'end': {
                'dateTime': final_e_date,
                'timeZone': 'Asia/Kuala_Lumpur',
            },
            'attendees': [
                {'email': 'lpage@example.com'},
            ],
        }
        # print(attends) -> ['example1@example.com', 'example2@example.com', 'example3@example.com']
        service2.events().insert(calendarId='primary', body=event).execute()

I have a list "attends" which holds the user input emails and I am not sure how I can extract the emails in the list and then pass the emails into the event object so I can add attendees. Below is the "attends" list.

['example1@example.com', 'example2@example.com', 'example3@example.com']

I am also not great at Python :')


Solution

  • In your script, when attends is declaread as attends = ['example1@example.com', 'example2@example.com', 'example3@example.com'], how about the following modification?

    From:

    service2.events().insert(calendarId='primary', body=event).execute()
    

    To:

    event["attendees"] = [*event["attendees"], *[{"email": e} for e in attends]] # Added
    service2.events().insert(calendarId='primary', body=event).execute()
    

    In this modification, attends = ['example1@example.com', 'example2@example.com', 'example3@example.com'] is added. So, the final values of attendees are 'attendees': [{'email': 'lpage@example.com'}, {'email': 'example1@example.com'}, {'email': 'example2@example.com'}, {'email': 'example3@example.com'}].

    If you want to replace the existing email with attends, please modify as follows.

    event["attendees"] = [{"email": e} for e in attends]
    service2.events().insert(calendarId='primary', body=event).execute()
    

    In this case, the values of attendees are 'attendees': [{'email': 'example1@example.com'}, {'email': 'example2@example.com'}, {'email': 'example3@example.com'}].