def __get_mail(self, monitoring: Monitoring): """ メールを取得する Params ------ monitoring: Monitoring 監視設定オブジェクト """ config = Config() run_time = RunTime(monitoring.search_word) # メールボックスへの接続 credentials = (config.client_id, config.client_secret) token_backend = \ FileSystemTokenBackend( token_path=config.token_path, token_filename=config.token_file ) account = Account(credentials, token_backend=token_backend) mailbox = account.mailbox() # 件名と時刻でメールを絞り込む query = mailbox.new_query() \ .on_attribute('subject') \ .contains(monitoring.search_word) \ .on_attribute('receivedDateTime') \ .greater_equal(run_time.read()) messages = mailbox.get_messages(query=query, download_attachments=True) return messages
class TestMailBoxOauth(TestMailBoxBasicAuth): def setup_class(self): credentials = (CLIENT_ID, CLIENT_SECRET) self.account = Account(credentials, auth_method=AUTH_METHOD.OAUTH) self.mailbox = self.account.mailbox() self.inbox = self.mailbox.inbox_folder()
class TestMailBoxBasicAuth: def setup_class(self): credentials = (USERNAME, PASSWORD) self.account = Account(credentials, auth_method=AUTH_METHOD.BASIC) self.mailbox = self.account.mailbox() self.inbox = self.mailbox.inbox_folder() def test_get_inbox_mails(self): messages = self.inbox.get_messages(5) assert len(messages) != 0 def test_new_email_draft(self): msg = self.account.new_message() msg.subject = 'Test Msg' msg.body = 'A message test' msg.save_draft() drafts = self.mailbox.drafts_folder() q = drafts.new_query('subject').equals('Test Msg') messages = drafts.get_messages(1, query=q) assert len(messages) == 1 def test_update_email(self): drafts = self.mailbox.drafts_folder() q = drafts.new_query('subject').equals('Test Msg') messages = drafts.get_messages(1, query=q) message = messages[0] if messages else None message2 = None if message: message.to.add('*****@*****.**') message.save_draft() messages2 = drafts.get_messages(1, query=q) message2 = messages2[0] if messages2 else None assert messages and message2 and message2.to and message2.to[0].address == '*****@*****.**' def test_delete_email(self): drafts = self.mailbox.drafts_folder() q = drafts.new_query('subject').equals('Test Msg') messages = drafts.get_messages(1, query=q) if messages: messages[0].delete() messages = drafts.get_messages(1, query=q) assert len(messages) == 0
class TestMailBox: def setup_class(self): credentials = ("client id", "client secret") self.account = Account(credentials) self.mailbox = self.account.mailbox() self.mailbox.con = MockConnection() def teardown_class(self): pass def test_mailbox(self): assert self.mailbox.root
def __get_mailbox(self, monitoring: Monitoring): """ メールボックスを取得する """ config = Config() # メールボックスへの接続 credentials = (config.client_id, config.client_secret) token_backend = \ FileSystemTokenBackend( token_path=config.token_path, token_filename=config.token_file ) account = Account(credentials, token_backend=token_backend) mailbox = account.mailbox() for folder in monitoring.search_directory: mailbox = mailbox.get_folder(folder_name=folder) return mailbox
def send_o365(api_key, secret, from_email, to_email, email_body, subject): credentials = (api_key, secret) tokenFile = "o365_token.txt" if not os.path.exists(os.path.exists(os.path.join(Path(__file__).parent, tokenFile))): logging.critical("o365 emailer cannot find token file. Sending emails will fail.") token_backend = FileSystemTokenBackend(token_path=Path(__file__).parent, token_filename=tokenFile) account = Account(credentials, token_backend=token_backend, scopes=['message_send']) if not account.authenticate(): #if not account.is_authenticated(scopes=['message_send']): account.authenticate() logging.critical("o365 emailer is not authenticated. Requires manual investigation.") example_mailbox = account.mailbox(resource=from_email) m = example_mailbox.new_message() m.to.add(to_email) m.subject = subject m.body = email_body m.send()
def get_o365_mail(emailfrom, start_date, end_date): scopes = ['basic', 'mailbox'] token_backend = FileSystemTokenBackend(token_path='.', token_filename='o365_token.txt') account = Account( scopes=scopes, credentials=('8cccb04f-b409-4d04-888b-20321dcc14b7', secret_config.o365_secret), token_backend=token_backend ) if not account.is_authenticated: # will check if there is a token and has not expired # ask for a login # console based authentication See Authentication for other flows account.authenticate() if account.is_authenticated: account.connection.refresh_token() my_mailbox = account.mailbox() my_inbox = my_mailbox.inbox_folder() try: converted_start_date = datetime.strptime(start_date, '%Y-%m-%d') converted_end_date = datetime.strptime(end_date, '%Y-%m-%d') except Exception as e: print("Could not convert start_date or end_date into a datetime.datetime ") raise e inbox_query = my_mailbox.new_query().on_attribute("from").contains(emailfrom) inbox_query = inbox_query.chain("and").on_attribute("created_date_time").greater_equal(converted_start_date) inbox_query = inbox_query.chain("and").on_attribute("created_date_time").less_equal(converted_end_date) messages = list() for message in my_inbox.get_messages(download_attachments=True, query=inbox_query): messages.append(message) return messages print("hammertime")
import yaml import pyodbc import pandas as pd from O365 import Account conf = yaml.load(open('conf/credentials.yml')) credentials = (conf['client']['client_id'], conf['client']['client_secret']) account = Account(credentials) mailbox = account.mailbox() inbox = mailbox.inbox_folder() conn = pyodbc.connect(conf['database']['cnxn']) # Store the sql query from the script sqlQuery = '' with open('data_governance.sql', 'r') as dg: for line in dg: if line.strip() == 'GO': break else: sqlQuery += line # Execute the query and read the returned table into a Pandas data frame data = pd.io.sql.read_sql(sqlQuery, conn) unique_owner = data['CommercialOwner'][47] leads = "\n" for row in data.itertuples():
load_dotenv() CLIENT_ID = os.environ.get('EMAIL_ID') CLIENT_SECRET = os.environ.get('EMAIL_SECRET') TENANT_ID = os.environ.get('TENANT_ID') SERVER_IP = os.environ.get('SERVER_IP') EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS') credentials = (CLIENT_ID, CLIENT_SECRET) account = Account(credentials, tenant_id=TENANT_ID, auth_flow_type='credentials') if account.authenticate(scopes=['https://graph.microsoft.com/.default']): while True: email, token = input().split() mailbox = account.mailbox(EMAIL_ADDRESS) m = mailbox.new_message() m.to.add(email) m.subject = 'Cyberhawks Email Confirmation Test!' m.body = """ <html> <body> Please <a href=\"http://""" + str( SERVER_IP) + "/" + str( token ) + """\">follow this link</a> to confirm your discord account.</p> </body> </html> """ m.send()
This script must be run on its own, outside the Azure Function app and the environment before you deploy. After you've obtained an AppID and Secret from Azure's GRAPH API, plug them and your email address in. Run the script. It should create a file o365_token.txt in the same directory as this script This file will have the access token inside that your Azure Function app will need to authenticate with Graph and send emails. See the detailed o365 library help or further instructions in the readme. ''' from O365 import Account, FileSystemTokenBackend from pathlib import Path appID = "Your App ID from Azure" c_secret = "Your client secret from Azure" from_email = "*****@*****.**" to_email = "*****@*****.**" token_backend = FileSystemTokenBackend(token_path=Path(__file__).parent, token_filename='o365_token.txt') credentials = (appID, c_secret) account = Account(credentials, token_backend=token_backend) if not account.authenticate(): account.authenticate() print("o365 emailer is not authenticated. Requires manual investigation.") example_mailbox = account.mailbox(resource=from_email) m = example_mailbox.new_message() m.to.add(to_email) m.subject = "This is a test setup email" m.body = "This is the body of a test setup email" m.send()