예제 #1
1
파일: EwsApi.py 프로젝트: cccmir/EmailTools
    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')
예제 #2
0
    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)
예제 #3
0
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
예제 #5
0
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()
예제 #6
0
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")
예제 #7
0
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()
예제 #8
0
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
예제 #9
0
파일: PyExchange.py 프로젝트: tjandy/Inlook
 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()
예제 #10
0
 def test_sessionpool(self):
     # First, empty the calendar
     start = EWSDateTime(2011,
                         10,
                         12,
                         8,
                         tzinfo=self.account.default_timezone)
     end = EWSDateTime(2011,
                       10,
                       12,
                       10,
                       tzinfo=self.account.default_timezone)
     self.account.calendar.filter(
         start__lt=end, end__gt=start,
         categories__contains=self.categories).delete()
     items = []
     for i in range(75):
         subject = 'Test Subject %s' % i
         item = CalendarItem(
             start=start,
             end=end,
             subject=subject,
             categories=self.categories,
         )
         items.append(item)
     return_ids = self.account.calendar.bulk_create(items=items)
     self.assertEqual(len(return_ids), len(items))
     ids = self.account.calendar.filter(start__lt=end, end__gt=start, categories__contains=self.categories) \
         .values_list('id', 'changekey')
     self.assertEqual(ids.count(), len(items))
    def create_meeting(self, username, start_time, end_time, subject, body,
                       required_attendees, optional_attendees):
        """Create a meeting object"""
        account = self.connect_to_account(
            username, impersonation=(username != self.email))

        if required_attendees:
            required_attendees = [
                ra.strip() for ra in required_attendees.split(',')
            ]
        if optional_attendees:
            optional_attendees = [
                oa.strip() for oa in optional_attendees.split(',')
            ]

        tz = EWSTimeZone.timezone('Etc/GMT')

        meeting = CalendarItem(
            account=account,
            folder=account.calendar,
            start=EWSDateTime.from_datetime(
                datetime.datetime.fromtimestamp(start_time / 1000, tz=tz)),
            end=EWSDateTime.from_datetime(
                datetime.datetime.fromtimestamp(end_time / 1000, tz=tz)),
            subject=subject,
            body=body,
            required_attendees=required_attendees,
            optional_attendees=optional_attendees)
        return meeting
예제 #12
0
    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
예제 #13
0
    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()
예제 #14
0
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)
예제 #15
0
def generate_items(n):
    start = tz.localize(EWSDateTime(2000, 3, 1, 8, 30, 0))
    end = tz.localize(EWSDateTime(2000, 3, 1, 9, 15, 0))
    tpl_item = CalendarItem(
        start=start,
        end=end,
        body='This is a performance optimization test of server %s intended to find the optimal batch size and '
             'concurrent connection pool size of this server.' % config.protocol.server,
        location="It's safe to delete this",
        categories=categories,
    )
    for j in range(n):
        item = copy.copy(tpl_item)
        item.subject = 'Performance optimization test %s by exchangelib' % j,
        yield item
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 generate_items(count):
    start = datetime.datetime(2000, 3, 1, 8, 30, 0, tzinfo=tz)
    end = datetime.datetime(2000, 3, 1, 9, 15, 0, tzinfo=tz)
    tpl_item = CalendarItem(
        start=start,
        end=end,
        body=
        f'This is a performance optimization test of server {account.protocol.server} intended to find the '
        f'optimal batch size and concurrent connection pool size of this server.',
        location="It's safe to delete this",
        categories=categories,
    )
    for j in range(count):
        item = copy.copy(tpl_item)
        item.subject = f'Performance optimization test {j} by exchangelib',
        yield item
예제 #18
0
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
예제 #19
0
def calitems():
    i = 0
    start = tz.localize(EWSDateTime(2000, 3, 1, 8, 30, 0))
    end = tz.localize(EWSDateTime(2000, 3, 1, 9, 15, 0))
    item = CalendarItem(
        subject='Performance optimization test %s by pyexchange' % i,
        start=start,
        end=end,
        body=
        'This is a performance optimization test of server %s intended to find the optimal batch size and '
        'concurrent connection pool size of this server.' %
        config.protocol.server,
        location="It's safe to delete this",
        categories=categories,
    )
    while True:
        itm = copy.copy(item)
        itm.subject = 'Test %s' % i
        i += 1
        yield itm
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"]
    }
예제 #21
0
# testroom4 -> 测试会议室3

room_list = [
    '*****@*****.**', '*****@*****.**',
    '*****@*****.**'
]
user_list = [
    '*****@*****.**', '*****@*****.**', '*****@*****.**',
    '*****@*****.**', '*****@*****.**', '*****@*****.**'
]

item = CalendarItem(
    account=user_one,
    folder=user_one.calendar,
    start=user_one.default_timezone.localize(EWSDateTime(2021, 1, 25, 17, 00)),
    end=user_one.default_timezone.localize(EWSDateTime(2021, 1, 25, 18, 00)),
    location="*****@*****.**",
    subject="Meeting Test",
    body="Test 1",
    required_attendees=room_list + user_list)


def modify():
    import random
    attendee_number = random.randint(1, 6)
    print("修改会议")
    print("随机" + str(attendee_number) + "个参会人")
    attendee = random.sample(user_list, attendee_number)
    for item in user_one.calendar.all().order_by('-datetime_received')[:1]:
        # 打印信息
        print(item.subject)
예제 #22
0
year = 2012
month = 3
day = 20

n = 1000

calitems = []
for i in range(0, n):
    start = tz.localize(EWSDateTime(year, month, day, 8, 30))
    end = tz.localize(EWSDateTime(year, month, day, 9, 15))
    calitems.append(
        CalendarItem(
            start=start,
            end=end,
            subject='Performance test %s' % i,
            body='Hi from PerfTest',
            location='devnull',
            categories=categories,
        ))

t2 = datetime.now()
delta = t2 - t1
print(('Time to build %s items: %s (%s / sec)' % (len(calitems), delta,
                                                  (n / (delta.seconds or 1)))))


def avg(delta, n):
    d = (delta.seconds * 1000000 + delta.microseconds) / 1000000
    return n / (d if d else 1)

예제 #23
0
            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()
예제 #24
0
pytz_tz = pytz.timezone('Europe/Copenhagen')
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
예제 #25
0
                       server="192.168.10.118",
                       credentials=credentials,
                       auth_type=NTLM)

r1 = Account(primary_smtp_address='*****@*****.**',
             credentials=credentials,
             autodiscover=False,
             config=config,
             access_type=DELEGATE)

item = CalendarItem(
    account=r1,
    folder=r1.calendar,
    start=r1.default_timezone.localize(EWSDateTime(2021, 1, 27, 17, 00)),
    end=r1.default_timezone.localize(EWSDateTime(2021, 1, 27, 18, 00)),
    location="testroom1",
    subject="meeting test",
    body="test",
    required_attendees=[
        '*****@*****.**', '*****@*****.**',
        '*****@*****.**'
    ])


def modify():
    for item in r1.calendar.all().order_by('-datetime_received')[:1]:
        item.subject = "修改会议测试"
        item.end = r1.default_timezone.localize(
            EWSDateTime(2021, 1, 27, 17, 30))
        item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY)

예제 #26
0
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)
예제 #27
0
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

# credentials = Credentials(username='******', password='******')
credentials = Credentials(username='******', password='******')
config = Configuration(retry_policy=FaultTolerance(max_wait=3600), server="192.168.10.118", credentials=credentials, auth_type=NTLM)

user_one = Account(primary_smtp_address='*****@*****.**', credentials=credentials, autodiscover=False, config=config, access_type=DELEGATE)
user_two = Account(primary_smtp_address='*****@*****.**', credentials=credentials, autodiscover=False, config=config, access_type=DELEGATE)


item_1 = CalendarItem(
    account = user_one,
    folder = user_one.calendar,
    start = user_one.default_timezone.localize(EWSDateTime(2021, 1, 21, 17, 00)),
    end = user_one.default_timezone.localize(EWSDateTime(2021, 1, 21, 18, 00)),
    location = "testroom1",
    subject = "Meeting Test",
    body = "Test 1",
    required_attendees = ['*****@*****.**', '*****@*****.**']
)

item_2 = CalendarItem(
    account = user_two,
    folder = user_two.calendar,
    start = user_two.default_timezone.localize(EWSDateTime(2021, 1, 21, 17, 00)),
    end = user_two.default_timezone.localize(EWSDateTime(2021, 1, 21, 18, 00)),
    location = "TestRoom2",
    subject = "Meeting Test 2",
    body = "Test 2",
    required_attendees = ['*****@*****.**', '*****@*****.**']
)
예제 #28
0
def GetEvents():
    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. "today" first gets the date object, then sets it to beginning of day.
    today = date.today()
    tomorrow = date.today() + timedelta(days=1)

    ## Get Calendar Items
    dayEventsView = account.calendar.view(start=tz.localize(EWSDateTime(today.year, today.month, today.day)),end=tz.localize(EWSDateTime(tomorrow.year, tomorrow.month, tomorrow.day)))
    calendarItems = dayEventsView.all()

    for item in calendarItems:
      tmpCalendarItem = CalendarItem()
      tmpCalendarItem.account = item.account
      tmpCalendarItem.adjacent_meeting_count = item.adjacent_meeting_count
      tmpCalendarItem.allow_new_time_proposal = item.allow_new_time_proposal
      tmpCalendarItem.appointment_reply_time = item.appointment_reply_time
      tmpCalendarItem.appointment_sequence_number = item.appointment_sequence_number
      tmpCalendarItem.attachments = item.attachments
      tmpCalendarItem.body = item.body
      tmpCalendarItem.categories = item.categories
      tmpCalendarItem.changekey = item.changekey
      tmpCalendarItem.conference_type = item.conference_type
      tmpCalendarItem.conflicting_meeting_count = item.conflicting_meeting_count
      tmpCalendarItem.conversation_id = item.conversation_id
      tmpCalendarItem.culture = item.culture
      tmpCalendarItem.datetime_created = item.datetime_created
      tmpCalendarItem.datetime_received = item.datetime_received
      tmpCalendarItem.datetime_sent = item.datetime_sent
      tmpCalendarItem.deleted_occurrences = item.deleted_occurrences
      tmpCalendarItem.display_cc = item.display_cc
      tmpCalendarItem.display_to = item.display_to
      tmpCalendarItem.duration = item.duration
      tmpCalendarItem.effective_rights = item.effective_rights
      tmpCalendarItem.end = item.end
      tmpCalendarItem.extern_id = item.extern_id
      tmpCalendarItem.first_occurrence = item.first_occurrence
      tmpCalendarItem.folder = item.folder
      tmpCalendarItem.has_attachments = item.has_attachments
      tmpCalendarItem.headers = item.headers
      tmpCalendarItem.importance = item.importance
      tmpCalendarItem.in_reply_to = item.in_reply_to
      tmpCalendarItem.is_all_day = item.is_all_day
      tmpCalendarItem.is_associated = item.is_associated
      tmpCalendarItem.is_cancelled = item.is_cancelled
      tmpCalendarItem.is_draft = item.is_draft
      tmpCalendarItem.is_from_me = item.is_from_me
      tmpCalendarItem.is_meeting = item.is_meeting
      tmpCalendarItem.is_online_meeting = item.is_online_meeting
      tmpCalendarItem.is_recurring = item.is_recurring
      tmpCalendarItem.is_resend = item.is_resend
      tmpCalendarItem.is_response_requested = item.is_response_requested
      tmpCalendarItem.is_submitted = item.is_submitted
      tmpCalendarItem.is_unmodified = item.is_unmodified
      tmpCalendarItem.item_class = item.item_class
      tmpCalendarItem.item_id = item.item_id
      tmpCalendarItem.last_modified_name = item.last_modified_name
      tmpCalendarItem.last_modified_time = item.last_modified_time
      tmpCalendarItem.last_occurrence = item.last_occurrence
      tmpCalendarItem.legacy_free_busy_status = item.legacy_free_busy_status
      tmpCalendarItem.location = item.location
      tmpCalendarItem.meeting_request_was_sent = item.meeting_request_was_sent
      tmpCalendarItem.meeting_workspace_url = item.meeting_workspace_url
      tmpCalendarItem.mime_content = item.mime_content
      tmpCalendarItem.modified_occurrences = item.modified_occurrences
      tmpCalendarItem.my_response_type = item.my_response_type
      tmpCalendarItem.net_show_url = item.net_show_url
      tmpCalendarItem.optional_attendees = item.optional_attendees
      tmpCalendarItem.organizer = item.organizer
      tmpCalendarItem.original_start = item.original_start
      tmpCalendarItem.parent_folder_id = item.parent_folder_id
      tmpCalendarItem.recurrence = item.recurrence
      tmpCalendarItem.reminder_due_by = item.reminder_due_by
      tmpCalendarItem.reminder_is_set = item.reminder_is_set
      tmpCalendarItem.reminder_minutes_before_start = item.reminder_minutes_before_start
      tmpCalendarItem.required_attendees = item.required_attendees
      tmpCalendarItem.resources = item.resources
      tmpCalendarItem.sensitivity = item.sensitivity
      tmpCalendarItem.size = item.size
      tmpCalendarItem.start = item.start
      tmpCalendarItem.subject = item.subject
      tmpCalendarItem.text_body = item.text_body
      tmpCalendarItem.type = item.type
      tmpCalendarItem.uid = item.uid
      tmpCalendarItem.unique_body = item.unique_body
      events.append(tmpCalendarItem)

    return(events)
예제 #29
0
    ExtendedProperty,
)
from exchangelib.items import (
    SEND_TO_ALL_AND_SAVE_COPY,
    SEND_ONLY_TO_CHANGED,
)


class CalendarItemID(ExtendedProperty):
    distinguished_property_set_id = 'PublicStrings'
    property_name = 'NCR Calendar ID'
    property_type = 'Integer'


# Create a custom calendar property to make searching for items easier
CalendarItem.register('ncr_calendar_item_id', CalendarItemID)


class CalendarAPI:
    """API to create and edit invitations."""
    def __init__(self):
        """Init class."""
        self.account = self.connect()

        self._calendar_time = None
        self._tz = None

    def connect(self):

        credentials = Credentials(settings.EMAIL_HOST_USER,
                                  settings.EMAIL_HOST_PASSWORD)
    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)