def __init__(self): """ Create CalendarSession object. You should set os variables before object creating: OFFICE_CLIENT_ID and OFFICE_CLIENT_SECRET. To get OFFICE_CLIENT_ID and OFFICE_CLIENT_SECRET you should follow the steps: 1. Login to https://apps.dev.microsoft.com/ 2. Create an app, note your OFFICE_CLIENT_ID 3. Generate a new password (OFFICE_CLIENT_SECRET) under "Application Secrets" section 4. Under the "Platform" section, add a new Web platform and set "http://localhost:5000" as the redirect URL 5. Under "Microsoft Graph Permissions" section, add the below delegated permissions: a) User.Read b) Files.ReadWrite c) Calendars.Read d) Mail.Send """ client_id = os.getenv('OFFICE_CLIENT_ID') client_secret = os.getenv('OFFICE_CLIENT_SECRET') CalendarConnection().oauth2(client_id, client_secret) self.session = Connection().oauth
def main(): if len(sys.argv) == 1: sys.stderr.write("Usage: %s BY VALUE\n" % sys.argv[0]) return 1 username = input("Username: "******"Password: ") authentication = (username, password) Connection.login(*authentication) inbox = FluentInbox() print(inbox.get_folder(by=sys.argv[1], value=sys.argv[2])) return 0
def main(): username = input("Username: "******"Password: ") authentication = (username, password) Connection.login(*authentication) inbox = FluentInbox() # If given arguments, treat them as folder_ids to use as parents if len(sys.argv) > 1: for folder_id in sys.argv[1:]: for folder in inbox.list_folders(parent_id=folder_id): print(folder['Id'], folder['DisplayName']) else: for folder in inbox.list_folders(): print(folder['Id'], folder['DisplayName']) return 0
def main(): if len(sys.argv) == 1: sys.stderr.write("Usage: %s 'subject to search for'\n" % sys.argv[0]) return 1 username = input("Username: "******"Password: "******"Subject:%s" % sys.argv[1]).fetch(count=1): print(message.moveToFolder(trash_folder['Id'])) return 0
def _authenticate(self): token_backend = FileSystemTokenBackend( token_path=os.path.dirname(os.path.realpath(__file__))) connection = Connection(config.credentials, scopes=['basic', 'Calendars.Read'], token_backend=token_backend) connection.refresh_token() account = Account(config.credentials, scopes=['basic', 'Calendars.Read'], token_backend=token_backend) if not account.is_authenticated: if account.authenticate(): print('Authenticated!') else: print('Authentication failed!') return self._schedule = account.schedule()
def authenticate_outlook(): # authenticate microsoft graph api credentials credentials = (config.outlook_client_id, config.outlook_client_secret) token_backend = FileSystemTokenBackend( token_path=config.outlook_token_path, token_filename=config.outlook_token_filename) account = Account(credentials, token_backend=token_backend) if not account.is_authenticated: # not authenticated, throw error account.authenticate(scopes=config.outlook_scopes) connection = Connection(credentials, token_backend=token_backend, scopes=config.outlook_scopes) connection.refresh_token() print("Authenticated Outlook.") return account
def main(): username = input("Username: "******"Password: "******"Inbox") # reset current folder as subfolder inbox.from_folder("Subfolder", parent_id=inbox.folder["Id"]) for msg in inbox.search("Subject:Urgent").fetch_first(10): print(msg.getSubject()) # reset current folder as a child folder of Subfolder inbox.from_folder("Sub_subfolder", parent_id=inbox.folder["Id"]) for msg in inbox.fetech_first(10): print(msg.getSubject()) return 0
def main(clientid, secret, recepient, subject, body): credentials = (clientid, secret) scopes = [ 'https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send' ] con = Connection(credentials, scopes=scopes) account = Account(credentials) m = account.new_message() m.to.add(recepient) m.subject = subject m.body = body m.send()
class CalendarSession: def __init__(self): """ Create CalendarSession object. You should set os variables before object creating: OFFICE_CLIENT_ID and OFFICE_CLIENT_SECRET. To get OFFICE_CLIENT_ID and OFFICE_CLIENT_SECRET you should follow the steps: 1. Login to https://apps.dev.microsoft.com/ 2. Create an app, note your OFFICE_CLIENT_ID 3. Generate a new password (OFFICE_CLIENT_SECRET) under "Application Secrets" section 4. Under the "Platform" section, add a new Web platform and set "http://localhost:5000" as the redirect URL 5. Under "Microsoft Graph Permissions" section, add the below delegated permissions: a) User.Read b) Files.ReadWrite c) Calendars.Read d) Mail.Send """ client_id = os.getenv('OFFICE_CLIENT_ID') client_secret = os.getenv('OFFICE_CLIENT_SECRET') CalendarConnection().oauth2(client_id, client_secret) self.session = Connection().oauth @staticmethod def _response_value_to_dict(response): try: return json.loads(response.text)['value'] except KeyError: # see response with error description print(response.text) return def get_filtered_events(self, date_from=None, date_to=None, categories=None, all_in_categories=True): """ Get events optionally filtered by dates or categories. If no parameters specified, show all user events. :param date_from: datetime.datetime object that allows to filter events starting later than date. :param date_to: datetime.datetime object that allows to filter events ending earlier than date. :param categories: iterable object (e.g. list/tuple) that contains str instances, allows to filter events with categories. Categories should have the same names as in Office Calendar :param all_in_categories: bool, that describes how to filter events with categories. If True -> select events that are included to all the categories. If False -> select events that are included to any of the categories. :return: list of events. Example: [ { 'body': { ... }, 'sensitivity': 'normal', 'webLink': 'https://iwanttesla.com', 'isReminderOn': True, 'isCancelled': False, 'hasAttachments': False, 'reminderMinutesBeforeStart': 15, 'organizer': { 'emailAddress': { 'name': 'Lyovkin Nikita', 'address': '*****@*****.**' } }, 'subject': 'Tesla', 'lastModifiedDateTime': '2018-03-07T23:50:28.3293115Z', 'bodyPreview': 'Tesla Model X', 'end': { 'timeZone': 'UTC', 'dateTime': '2018-03-08T00:30:00.0000000' }, 'originalEndTimeZone': 'FLE Standard Time', 'id': 'Tesla Model X', 'recurrence': None, 'start': { 'timeZone': 'UTC', 'dateTime': '2018-03-08T00:00:00.0000000' }, 'changeKey': 'twl/plKOAkObNwxjyq6r3gAAcw141g==', 'location': { 'displayName': '', 'address': { } }, 'onlineMeetingUrl': None, 'type': 'singleInstance', 'isOrganizer': True, 'importance': 'normal', 'isAllDay': False, 'attendees': [ ], 'categories': [ '\u0416\u0435\u043b\u0442\u0430\u044f \u043a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f' ], 'originalStartTimeZone': 'FLE Standard Time', 'createdDateTime': '2018-03-07T23:48:53.9415055Z', 'responseRequested': True, 'showAs': 'busy', 'iCalUId': '1.9 sec to 100 km/ph', 'seriesMasterId': None, 'responseStatus': { 'response': 'organizer', 'time': '0001-01-01T00:00:00Z' }, '@odata.etag': 'W/"twl/plKOAkObNwxjyq6r3gAAcw141g=="' }, { ... }, ... ] """ if date_to is not None and date_from is not None \ and date_from > date_to: print('date_from should be less than date_to param') return if date_from is not None and not isinstance(date_from, dt) \ or date_to is not None and not isinstance(date_to, dt): print('date_from and date_to params should ' 'be datetime.datetime instances') return if categories is not None \ and not isinstance(categories, collections.Iterable) \ and not all(isinstance(i, str) for i in categories): print('category param should be iterable with str instances') return filters = [] if date_from is not None: date_from = date_from.isoformat() filters.append("start/dateTime ge '" + date_from + "'") if date_to is not None: date_to = date_to.isoformat() filters.append("end/dateTime le '" + date_to + "'") if categories: delimeter = all_in_categories and ' and ' or ' or ' filter_categories = [] for category in categories: filter_categories.append("categories/any(a:a eq '" + category + "')") filters.append('(' + delimeter.join(filter_categories) + ')') params = filters and {'$filter': ' and '.join(filters)} or None response = self.session.get( 'https://graph.microsoft.com/v1.0/me/events', params=params) return self._response_value_to_dict(response)
def oauth2(client_id, client_secret, store_token=False, token_path='.o365_token'): """Connect to office 365 using specified Open Authentication protocol :param client_id: application_id generated by https://apps.dev.microsoft.com when you register your app :param client_secret: secret password key generated for your application :param store_token: whether or not to store the token in file system, so u don't have to keep opening the auth link and authenticating every time :param token_path: path to where the token should be saved to """ connection = Connection() connection.api_version = '2.0' connection.client_id = client_id connection.client_secret = client_secret if not store_token: delete_token(token_path) token = load_token(token_path) if not token: connection.oauth = OAuth2Session( client_id=client_id, redirect_uri='http://localhost:5000/', scope=[ 'User.Read', 'Files.ReadWrite', 'Calendars.Read', 'Mail.Send' ]) oauth = connection.oauth auth_url, state = oauth.authorization_url( url=Connection._oauth2_authorize_url, access_type='offline') try: webbrowser.open(auth_url) except: print('Please open' + auth_url + ' and authorize the application') serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: serversocket.bind(('localhost', 5000)) serversocket.listen(2) while True: connection, address = serversocket.accept() buf = connection.recv(1024) connection.close() if len(buf) > 0: break finally: serversocket.close() auth_resp = 'https://outlook.office365.com/owa/' + buf.split()[1] token = oauth.fetch_token(token_url=Connection._oauth2_token_url, authorization_response=auth_resp, client_secret=client_secret) os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = 'Y' save_token(token, token_path) else: connection.oauth = OAuth2Session(client_id=client_id, token=token) return connection
def get_inbox(): Connection.login(*(USERNAME, PASSWORD)) return FluentInbox()
def get_con_obj(): credentials = (conf['OFFICE_CLIENT_ID'], conf['OFFICE_CLIENT_SECRET']) scopes = Core.get_scopes() return Connection(credentials, scopes=scopes, token_backend=FileSystemTokenBackend(token_filename='o365_token.txt'))
path = BASEDIR / 'mrd/configuration.ini' if not path.exists(): print("No valid configuration file at", path.absolute()) print("Could not refresh token file") exit(0) config = ConfigParser() config.read(str(path)) items = dict(config.items('RoomInformation')) CLIENT_ID = items['client_id'] CLIENT_SECRET = items['client_secret'] scopes = ['offline_access', 'https://graph.microsoft.com/Calendars.ReadWrite'] path = BASEDIR / 'mrd/o365_token.txt' con = Connection(credentials=(CLIENT_ID, CLIENT_SECRET), scopes=scopes, token_file_name=path) if not con.check_token_file(): print("No valid token found at", path.absolute()) print("Please run 'scripts/generate_token.py' first...") else: con.get_session() con.refresh_token() token = json.load(path.absolute().open()) print("Successfully updated token in", path.absolute()) print("refresh_token=", token['refresh_token'])
if options.username and options.password: loadedFile.append([options.username, options.password]) url = 'https://outlook.office365.com/' tmpTitle = checkPage(url) if "Sign in to your account" not in tmpTitle: print "[!] Check your internet. Something went wrong." sys.exit() tmpBlackList = [] for x in loadedFile: username = x[0] password = x[1] try: if username not in blackList: Connection.login(username, password) inbox = FluentInbox() inbox.from_folder('Inbox').search('').fetch(count=1) print "[+] Valid credentials: " + username validCredList.append([username, password]) else: print "[+] Blacklisted credentials: " + username tmpBlackList.append(username) except Exception as e: print e print "[!] Invalid credentials: " + username tmpBlackList.append(username) if len(tmpBlackList) > len(blackList): print "[*] Updating blacklist.txt" blacklistFile = open("blacklist.txt", "w+")
'mars': 3, 'april': 4, 'maj': 5, 'juni': 6, 'juli': 7, 'augusti': 8, 'september': 9, 'oktober': 10, 'november': 11, 'december': 12 } UPDATE_FREQUENCY = 1440 prot = MSGraphProtocol() con = Connection((CLIENT_ID, CLIENT_SECRET)) def auth_user(): credentials = (CLIENT_ID, CLIENT_SECRET) scopes = ['basic', 'message_all'] account = Account(credentials) if not account.is_authenticated: account.authenticate(scopes=scopes) def string_to_date(regex_str): day = int(regex_str[0]) month = regex_str[1] time = regex_str[3].split(':')
config = ConfigParser() config.read(str(path)) items = dict(config.items('RoomInformation')) CLIENT_ID = items['client_id'] CLIENT_SECRET = items['client_secret'] MAIL_ID = items['id'] print("Generate token for id", CLIENT_ID, "with secret", CLIENT_SECRET) scopes = ['offline_access', 'https://graph.microsoft.com/Calendars.ReadWrite'] path = BASEDIR / "mrd/o365_token.txt" con = Connection(credentials=(CLIENT_ID, CLIENT_SECRET), scopes=scopes, token_file_name=path) if not con.check_token_file(): print( "No valid token found. Starting authentication process for <%s> ..." % MAIL_ID) if gen_token_file(con): print("Successfully stored token file at", path.absolute()) else: print("Failed to store token file") else: token = json.load(path.absolute().open()) print("Valid token found at", path.absolute()) print("access_token=", token['access_token']) print("expires_at=",