def createAppointment(self, sendAppointment: SendAppointment): required_recipients = [] optional_recipients = [] for attendee in sendAppointment.requiredAttendees.split(';'): if attendee == "": continue required_recipients.append(attendee) for attendee in sendAppointment.optionalAttendees.split(';'): if attendee == "": continue optional_recipients.append(attendee) calendar_item = CalendarItem( account=self.account, folder=self.account.calendar, start=self.account.default_timezone.localize( EWSDateTime.from_datetime(sendAppointment.startTime)), end=self.account.default_timezone.localize( EWSDateTime.from_datetime(sendAppointment.endTime)), subject=sendAppointment.subject, body=sendAppointment.body, required_attendees=required_recipients, optional_attendees=optional_recipients) # 'SendToNone', 'SendOnlyToAll', 'SendToAllAndSaveCopy calendar_item.save(send_meeting_invitations='SendToAllAndSaveCopy')
def handle_create(self, reservation): if not reservation.reserver_email_address: return if not reservation.reserver_email_address.endswith( settings.OUTLOOK_EMAIL_DOMAIN): return unit_address = reservation.resource.unit.address_postal_full if reservation.resource.unit.address_postal_full else reservation.resource.unit.street_address manager = store.items.get(self.id) appointment = CalendarItem( account=manager.account, folder=manager.calendar, subject='Reservation created', body='You have created an reservation', start=ToEWSDateTime(reservation.begin), end=ToEWSDateTime(reservation.end), categories=[], location=unit_address, required_attendees=[ Attendee(mailbox=Mailbox( email_address=reservation.reserver_email_address), response_type='Accept') ]) Mailbox.get_field_by_fieldname( 'routing_type').supported_from = EXCHANGE_2016 appointment.save() self.create_respa_outlook_reservation( appointment=appointment, reservation=reservation, email=reservation.reserver_email_address)
def create_invitation( self, ncr_calendar_item_id, attendee, header, body, start_time=None, end_time=None, ): """Create an outlook invitation.""" # create a meeting request and send it out calendar_item = CalendarItem( account=self.account, folder=self.account.calendar, is_online_meeting=True, ncr_calendar_item_id=ncr_calendar_item_id, reminder_minutes_before_start=15, reminder_is_set=True, subject=self.header_prefix + header, body=body, required_attendees=[attendee], ) if start_time: calendar_item.start = self.get_calendar_time(start_time) if end_time: calendar_item.start = self.get_calendar_time(end_time) calendar_item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) return calendar_item
def make_a_reservation(preferences, timeslot): logger.info("Trying to make a reservation for {0} minutes.".format(timeslot)) now = tz.localize(EWSDateTime.now()) now = now.replace(minute=(now.minute - (now.minute % 5))) # round down to nearest 5 start_time = now.replace(second=0, microsecond=0) end_time = now.replace(second=0, microsecond=0) + timedelta(minutes=timeslot) logger.debug("Reserving for " + str(start_time) + " - " + str(end_time)) try: credentials = Credentials(username=preferences["username"], password=preferences["password"]) config = Configuration(service_endpoint=preferences["server"], credentials=credentials, auth_type=NTLM) account = Account(primary_smtp_address=preferences["email"], config=config, autodiscover=False, access_type=DELEGATE) item = CalendarItem(folder=account.calendar, subject='Pikavaraus', body='Made with Naurunappula at ' + str(now), start=start_time, end=end_time) except requests.exceptions.RequestException as e: # failure in data communication logger.exception("Exception while contacting the server.") return False if not check_availability(preferences, timeslot): return False try: item.save() return True except Exception as e: return False
def miniprogram_booking_roomCode_post(roomCode, appointment): # noqa: E501 # 添加预约信息 db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) learner = weapp.getLearner() if not learner: db_session.remove() return {'code': -1001, 'message': '没有找到对应的Learner'}, 200 room_account = Account( primary_smtp_address=('*****@*****.**' % roomCode), credentials=credentials, config=config ) startDateTime = room_account.default_timezone.localize(EWSDateTime( appointment['startYear'], appointment['startMonth'], appointment['startDay'], appointment['startHour'], appointment['startMinute'] )) endDateTime = room_account.default_timezone.localize(EWSDateTime( appointment['endYear'], appointment['endMonth'], appointment['endDay'], appointment['endHour'], appointment['endMinute'] )) try: item = CalendarItem( account=room_account, folder=room_account.calendar, start=startDateTime, end=endDateTime, subject=appointment['subject'], body=appointment['description'], ) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) db_session.add(orm.BookingNotes_db( changekey=item.changekey, bookedByID=learner.id, bookedByName=learner.familyName + learner.givenName )) db_session.commit() except Exception as e: db_session.remove() return {'code': -2004, 'message': '房间预约失败', 'log': str(e)}, 200 db_session.remove() return {'code': 0, 'message': 'success'}, 200
def bookMeeting(arg1, arg2): calendarIteration() startTime = str(arg1) endTime = str(arg2) if (any(x in range(int(startTime)+1,int(endTime)) for x in busyTimesFlat)): eel.alertBusy() else: item = CalendarItem(folder=account.calendar, subject='Booked on meeting room screen', start=tz.localize(EWSDateTime(year, month, day, int(startTime[:2]), int(startTime[-2:]))), end=tz.localize(EWSDateTime(year, month, day, int(endTime[0:2]), int(endTime[2:4])))) item.save() calendarIteration() eel.redirectMain()
def create_event(customer, body, date, open_men, messaged, location): item = CalendarItem( account=myaccount, folder=reservations_calendar, # account & folder required. subject="(N) " + customer + " • OPEN: " + open_men + messaged, body=body, start=date, # start & end required end=date, location=location) item.save() # This gives the item an item_id and a changekey # item.subject = "(N) " + customer item.save() # When the items has an item_id, this will update the item
def send_outlook_invitation(header="Invitation", body="Please come to my meeting", attendee=None, start_time=None, end_time=None): """Sends an outlook invitation.""" logger.info("Sent outlook invitation") tz = EWSTimeZone.timezone('Europe/Stockholm') start_time = parser.parse(start_time) end_time = parser.parse(end_time) credentials = Credentials(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) config = Configuration(server='outlook.office365.com', credentials=credentials) account = Account(primary_smtp_address=settings.EMAIL_HOST_USER, config=config, autodiscover=False, access_type=DELEGATE) if os.environ['ENVIRONMENT_MODE'] in ['UAT', 'DEV']: header_prefix = '*** TEST SYSTEM (env {}), NO REAL DATA *** | '.\ format(os.environ['ENVIRONMENT_MODE']) else: header_prefix = '' # create a meeting request and send it out calendar_item = CalendarItem( account=account, folder=account.calendar, start=tz.localize(EWSDateTime(start_time.year, start_time.month, start_time.day, start_time.hour + 1, start_time.minute)), end=tz.localize(EWSDateTime(end_time.year, end_time.month, end_time.day, end_time.hour + 2, end_time.minute)), subject=header_prefix + header, body=body, required_attendees=[attendee] ) calendar_item.save( send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) logger.info("Sent calendar invitation")
def main(): parser = argparse.ArgumentParser(description='Synchronize ICS to Exchange') parser.add_argument('ics', help="URL of the ICS") parser.add_argument('username', help="EWS username") parser.add_argument('--password', help="EWS password") parser.add_argument('mail', help="EWS primary SMTP mail address") parser.add_argument('--server', help="EWS server") args = parser.parse_args() if not args.password: args.password = getpass() c = Calendar(requests.get(args.ics).text) credentials = Credentials(username=args.username, password=args.password) config = None autodiscover = True if args.server: config = Configuration(server=args.server, credentials=credentials) autodiscover = False my_account = Account(primary_smtp_address=args.mail, credentials=credentials, access_type=DELEGATE, config=config, autodiscover=autodiscover) for i in list(c.timeline): start = EWSDateTime.from_string(str(i.begin)) end = EWSDateTime.from_string(str(i.end)) found = False for calendar_item in my_account.calendar.filter(start__lt=end, end__gt=start): if calendar_item.text_body and args.ics in calendar_item.text_body and i.uid in calendar_item.text_body: found = True break if found: continue item = CalendarItem(account=my_account, folder=my_account.calendar, start=start, end=end, subject=i.name, body="{}\nics2ews: {}\nuid: {}".format( i.description, args.ics, i.uid), location=i.location) item.save()
def addAgenda(self,fromDatetime,toDatetime,location,subject,detail,reminderSet,reminder): item = CalendarItem( account=self.account, folder=self.account.calendar, start=fromDatetime, end=toDatetime, subject=subject, body=detail, location=location, reminder_is_set=reminderSet, reminder_minutes_before_start=reminder # required_attendees=['*****@*****.**', '*****@*****.**'] ) # item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) item.save()
def make_a_reservation(timeslot): logger.info("Trying to make a reservation for {0} minutes.".format(timeslot)) now = tz.localize(EWSDateTime.now()) start_time = tz.localize(EWSDateTime(now.year, now.month, now.day, now.hour, now.minute, 0, 0)) end_time = tz.localize(EWSDateTime(now.year, now.month, now.day, now.hour, now.minute, 0, 0) + timedelta(minutes=timeslot)) item = CalendarItem(folder=account.calendar, subject='Pikavaraus', body='Made with Naurunappula at '+ str(now), start=start_time, end=end_time) try: item.save() logger.info("Reservation successful.") return True except Exception as e: logger.info("Reservation failed: {0}".format(e)) return False
def CreateCalendarEvent(subject,start,end): events = [] ews_url = account.protocol.service_endpoint ews_auth_type = account.protocol.auth_type primary_smtp_address = account.primary_smtp_address tz = EWSTimeZone.timezone('America/Denver') ## Get reference date objects startDate = datetime.strptime(start,"%Y-%m-%dT%H:%M:%S.%fZ") endDate = datetime.strptime(end,"%Y-%m-%dT%H:%M:%S.%fZ") tomorrow = date.today() + timedelta(days=1) item = CalendarItem( folder=account.calendar, subject=subject, start= tz.localize(EWSDateTime(startDate.year, startDate.month, startDate.day, startDate.hour, startDate.minute)), end=tz.localize(EWSDateTime(endDate.year, endDate.month, endDate.day, endDate.hour, endDate.minute)) ) item.save() return(item)
def create_Calender_item( self, subject, body, ): ''' creates Calendar item uses the global startTime and endTime :param str _subject: Subject of the calendar entry :param str _body: content of the calendar entry ''' startTime = self._startTime endTime = self._endTime a = self._account newCalenderItem = CalendarItem(start=startTime, end=endTime, folder=a.calendar, subject=subject, body=body) newCalenderItem.save()
def createExchangeItem(objExchangeAccount, strTitle, strLocn, strStartDate, strEndDate, strInviteeSMTP): print("Creating item {} which starts on {} and ends at {}".format( strTitle, strStartDate, strEndDate)) objStartDate = parser.parse(strStartDate) objEndDate = parser.parse(strEndDate) item = CalendarItem(account=objExchangeAccount, folder=objExchangeAccount.calendar, start=objExchangeAccount.default_timezone.localize( EWSDateTime(objStartDate.year, objStartDate.month, objStartDate.day, objStartDate.hour, objStartDate.minute)), end=objExchangeAccount.default_timezone.localize( EWSDateTime(objEndDate.year, objEndDate.month, objEndDate.day, objEndDate.hour, objEndDate.minute)), subject=strTitle, reminder_minutes_before_start=30, reminder_is_set=True, location=strLocn, body="", required_attendees=[strInviteeSMTP]) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY)
def booking_roomCode_post(roomCode, appointment): # noqa: E501 # 添加预约信息 db_session = None if "DEVMODE" in os.environ: if os.environ["DEVMODE"] == "True": db_session = orm.init_db(os.environ["DEV_DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) else: db_session = orm.init_db(os.environ["DATABASEURI"]) validation_result = wxLogin.validateUser() if not validation_result["result"]: db_session.remove() return {"error": "Failed to validate access token"}, 401 learner = db_session.query(orm.Learner_db).filter( orm.Learner_db.openid == validation_result["openid"]).one_or_none() if not learner.validated: db_session.remove() return {"error": "Learner not validated"}, 401 room_account = Account(primary_smtp_address=('*****@*****.**' % roomCode), credentials=credentials, config=config) startDateTime = room_account.default_timezone.localize( EWSDateTime(appointment['startYear'], appointment['startMonth'], appointment['startDay'], appointment['startHour'], appointment['startMinute'])) endDateTime = room_account.default_timezone.localize( EWSDateTime(appointment['endYear'], appointment['endMonth'], appointment['endDay'], appointment['endHour'], appointment['endMinute'])) try: item = CalendarItem( account=room_account, folder=room_account.calendar, start=startDateTime, end=endDateTime, subject=appointment['subject'], body=appointment['description'], ) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) db_session.add( orm.BookingNotes_db(changekey=item.changekey, bookedByID=learner.id, bookedByName=learner.familyName + learner.givenName)) db_session.commit() except Exception as e: db_session.remove() return { "error": str(e) }, 400, { "Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"] } db_session.remove() return { 'message': 'success' }, 201, { "Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"] }
Credentials, EWSDateTime, EWSTimeZone, Configuration, CalendarItem ) from exchangelib.items import SEND_TO_ALL_AND_SAVE_COPY tz = EWSTimeZone.timezone('Europe/Stockholm') EMAIL_HOST="smtp.office365.com" EMAIL_HOST_USER="******" EMAIL_HOST_PASSWORD="******" credentials = Credentials(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) config = Configuration(server='outlook.office365.com', credentials=credentials) account = Account(primary_smtp_address=EMAIL_HOST_USER, config=config, autodiscover=False, access_type=DELEGATE) # create a meeting request and send it out calendar_item = CalendarItem( account=account, folder=account.calendar, start=tz.localize(EWSDateTime(2018, 8, 22, 13, 30)), end=tz.localize(EWSDateTime(2018, 8, 22, 14, 30)), subject="Greetings from the rating platform", body="Please come to my meeting, it will be supergöy!", required_attendees=['*****@*****.**', '*****@*****.**'] ) calendar_item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY)
def method(request): try: mail = request.META['mail'] second_name = request.META['sn'] except: mail = "N\D" second_name = "N\D" mydb = mysql.connector.connect(host=dbhost, user=dbuser, passwd=dbpwd, database=dbdatabase, charset=dbcharset) mycursor = mydb.cursor() dep = request.POST['dep_id'] room = request.POST['room_id'] sd = request.POST['start'] ed = request.POST['end'] p_mail = request.POST['p_mail'] x = p_mail.split("-") x.pop() x.append(mail) sd_year = int(sd[0:4]) sd_month = int(sd[5:7]) sd_day = int(sd[8:10]) sd_hour = int(sd[11:13]) - 1 sd_minute = int(sd[14:16]) ed_year = int(ed[0:4]) ed_month = int(ed[5:7]) ed_day = int(ed[8:10]) ed_hour = int(ed[11:13]) - 1 ed_minute = int(ed[14:16]) time = datetime.now() if (int(ed[8:10]) != int(sd[8:10])) or ( (int(ed[11:13]) - int(sd[11:13])) > 2) or ( (int(ed[11:13]) - int(sd[11:13])) == 2 and (int(ed[14:16]) - int(sd[14:16]) == 30)) or ( (int(sd[8:10]) < int(time.strftime("%d"))) and (int(sd[5:7]) == int(time.strftime("%m")))) or (int( sd[5:7]) < int(time.strftime("%m"))) or ( (int(sd[8:10])) == int(time.strftime("%d")) and (int(sd[11:13]) < (int(time.strftime("%H")) + 1))) or ( (int(sd[8:10])) == int(time.strftime("%d")) and (int(sd[11:13]) == (int(time.strftime("%H")) + 1)) and (int(sd[14:16]) < (int(time.strftime("%M"))))): slQ = "SELECT * FROM Building WHERE id = %(id)s" mycursor.execute(slQ, {'id': request.POST.get('dep_id')}) dep = mycursor.fetchall() slQ = "SELECT * FROM Room WHERE id = %(id)s" mycursor.execute(slQ, {'id': request.POST.get('room_id')}) room = mycursor.fetchall() mycursor.close() mydb.close() context = { 'dep': dep, 'sala': room, 'start': '', 'end': '', 'sd': '', 'ed': '', 'mail': mail, 'second_name': second_name, } return render(request, 'reserva.html', context=context) type = 6 name = 'Reserva' participants = 1 slQ = "SELECT * FROM Event" mycursor.execute(slQ) get_events = mycursor.fetchall() if get_events != []: id = get_events[-1][0] + 1 else: id = 1 day = datetime.strptime(sd[0:4] + sd[5:7] + sd[8:10], "%Y%m%d").date() sdTime = datetime.strptime(sd[11:13] + ':' + sd[14:16] + ":00", "%H:%M:%S") edTime = datetime.strptime(ed[11:13] + ':' + ed[14:16] + ":00", "%H:%M:%S") duration = edTime - sdTime insert_stmt = ( "INSERT INTO Event (id, name, startTime, endTime, duration , day, eventType, numberPeople , isOwner, classroom) " "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)") data = (id, name, sdTime, edTime, duration, day, type, participants, 0, room) mycursor.execute(insert_stmt, data) mydb.commit() slQ = "SELECT * FROM Event WHERE classroom = %(id)s" mycursor.execute(slQ, {'id': room}) get_events = mycursor.fetchall() slQ = "SELECT * FROM Room WHERE id = %(id)s" mycursor.execute(slQ, {'id': room}) room = mycursor.fetchall() sala = room[0][1] mycursor.close() mydb.close() events = [] for e in get_events: sd = datetime(e[5].year, e[5].month, e[5].day) ed = datetime(e[5].year, e[5].month, e[5].day) events += [(e[0], e[1], sd + e[2], ed + e[3], e[6], e[7], 11, e[9])] context = { 'events': events, 'dep_id': dep, 'room_name': sala, 'mail': mail, 'second_name': second_name, } #Exchange credentials = Credentials('*****@*****.**', "2020roomdeti") a = Account('*****@*****.**', credentials=credentials, autodiscover=True) for email in x: if email != "": if sd_minute == 0 and ed_minute == 0: item = CalendarItem( account=a, folder=a.calendar, start=a.default_timezone.localize( EWSDateTime(sd_year, sd_month, sd_day, sd_hour, 00)), end=a.default_timezone.localize( EWSDateTime(ed_year, ed_month, ed_day, ed_hour, 00)), subject="Reserva de sala via (DetiRoom Web)", body="Foi convidado para o evento na sala " + sala + " do departamento 4, das " + str(sd_hour + 1) + ":00 ás " + str(ed_hour + 1) + ":00", required_attendees=[email]) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) elif sd_minute == 0 and ed_minute != 0: item = CalendarItem( account=a, folder=a.calendar, start=a.default_timezone.localize( EWSDateTime(sd_year, sd_month, sd_day, sd_hour, 00)), end=a.default_timezone.localize( EWSDateTime(ed_year, ed_month, ed_day, ed_hour, ed_minute)), subject="Reserva de sala via (DetiRoom Web)", body="Foi convidado para o evento na sala " + sala + " do departamento 4, das " + str(sd_hour + 1) + ":00 ás " + str(ed_hour + 1) + ":" + str(ed_minute), required_attendees=[email]) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) elif sd_minute != 0 and ed_minute == 0: item = CalendarItem( account=a, folder=a.calendar, start=a.default_timezone.localize( EWSDateTime(sd_year, sd_month, sd_day, sd_hour, sd_minute)), end=a.default_timezone.localize( EWSDateTime(ed_year, ed_month, ed_day, ed_hour, 00)), subject="Reserva de sala via (DetiRoom Web)", body="Foi convidado para o evento na sala " + sala + " do departamento 4, das " + str(sd_hour + 1) + ":" + str(sd_minute) + " ás " + str(ed_hour + 1) + ":00", required_attendees=[email]) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) else: item = CalendarItem( account=a, folder=a.calendar, start=a.default_timezone.localize( EWSDateTime(sd_year, sd_month, sd_day, sd_hour, sd_minute)), end=a.default_timezone.localize( EWSDateTime(ed_year, ed_month, ed_day, ed_hour, ed_minute)), subject="Reserva de sala via (DetiRoom Web)", body="Foi convidado para o evento na sala " + sala + " do departamento 4, das " + str(sd_hour + 1) + ":" + str(sd_minute) + " ás " + str(ed_hour + 1) + ":" + str(ed_minute), required_attendees=[email]) item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) return render(request, 'horario_book_c.html', context=context)
inters = "" salles = "" if x['salles']: for salle in x['salles']: if " " in salle['nomSalle']: salle['nomSalle'] = salle['nomSalle'].split(" ")[0] if "-" in salle['nomSalle']: salle['nomSalle'] = salle['nomSalle'].split("-")[0] salles += salle['nomSalle'] + " - " salles = salles[:-3] if x['intervenants']: for inter in x['intervenants']: inters += inter['nom'] + " " + inter['prenom'] if inter['adresseMail'] != "": inters += " - " + inter['adresseMail'] inters += "\n" if not account.calendar.filter(start__gte=startEWS, end__lte=endEWS, subject=x['title']): counter += 1 if not blank: item = CalendarItem(folder=folder, categories=["Bot Calendrier"], subject=x['title'], start=startEWS, end=endEWS, body=inters, location=salles) item.save() if counter > 1: print str(counter) + " evenements ajoutes." else: print str(counter) + " evenement ajoute." browser.quit()
py_dt = pytz_tz.localize(datetime(2017, 12, 11, 10, 9, 8)) ews_now = EWSDateTime.from_datetime(py_dt) ###Creating, updating, deleting, sending, moving, archiving # Here's an example of creating a calendar item in the user's standard calendar. If you want to # access a non-standard calendar, choose a different one from account.folders[Calendar]. # # You can create, update and delete single items: from exchangelib import Account, CalendarItem, Message, Mailbox, FileAttachment, HTMLBody from exchangelib.items import SEND_ONLY_TO_ALL, SEND_ONLY_TO_CHANGED from exchangelib.properties import DistinguishedFolderId a = Account(...) item = CalendarItem(folder=a.calendar, subject='foo') item.save() # This gives the item an 'id' and a 'changekey' value item.save(send_meeting_invitations=SEND_ONLY_TO_ALL ) # Send a meeting invitation to attendees # Update a field. All fields have a corresponding Python type that must be used. item.subject = 'bar' # Print all available fields on the 'CalendarItem' class. Beware that some fields are read-only, or # read-only after the item has been saved or sent, and some fields are not supported on old # versions of Exchange. print(CalendarItem.FIELDS) item.save() # When the items has an item_id, this will update the item item.save(update_fields=[ 'subject' ]) # Only updates certain fields. Accepts a list of field names. item.save(send_meeting_invitations=SEND_ONLY_TO_CHANGED ) # Send invites only to attendee changes item.delete() # Hard deletinon