def __init__(self, credentials, user, export_path, mail_ending,
                 start_date=None, amqp_info=None):
        logger.info('Start New MailboxScan: {}'.format(user))
        exchange_credentials = ServiceAccount(username=credentials[0],
                                              password=credentials[1])
        username = user + mail_ending
        self.start_date = start_date
        if self.start_date is None:
            self.export_path = Path(export_path + username)
        else:
            self.export_path = Path(export_path + username + '_' +
                                    str(self.start_date))
        self.current_path = None

        self.actual_exported_mails = 0
        self.amqp_info = amqp_info
        self.amqp_data = amqp_info[2]
        self.amqp_data['start_time'] = time.time()
        self.update_amqp()

        try:
            self.account = Account(primary_smtp_address=username,
                                   credentials=exchange_credentials,
                                   autodiscover=True,
                                   access_type=IMPERSONATION)
            self.account.root.refresh()
            logger.info('{}: Init complete'.format(username))
        except ErrorNonExistentMailbox:
            logger.error('No such user: {}'.format(username))
            self.account = None
def get_account():
    credentials = ServiceAccount(username=USERNAME, password=PASSWORD)
    config = Configuration(server=SERVER, credentials=credentials)
    return Account(primary_smtp_address=EMAIL,
                   config=config,
                   autodiscover=False,
                   access_type=DELEGATE)
Пример #3
0
def connect_test(password,
                 email,
                 access_type,
                 user=None,
                 win=None,
                 server=None,
                 *args,
                 **kwargs):
    if user and win:
        credentials = ServiceAccount(username="******".format(user, win),
                                     password=password,
                                     max_wait=__max_timeout__)
    elif user and win is None:
        credentials = ServiceAccount(username=user,
                                     password=password,
                                     max_wait=__max_timeout__)
    else:
        credentials = ServiceAccount(username=email,
                                     password=password,
                                     max_wait=__max_timeout__)

    access_type = DELEGATE if "DELEGATE" in access_type else IMPERSONATION

    if server:
        config = Configuration(server=server, credentials=credentials)

        user_account = Account(primary_smtp_address=email,
                               credentials=credentials,
                               autodiscover=False,
                               access_type=access_type,
                               config=config)
    else:
        user_account = Account(primary_smtp_address=email,
                               credentials=credentials,
                               autodiscover=True,
                               access_type=access_type)

    ewl_url = user_account.protocol.service_endpoint
    ews_auth_type = user_account.protocol.auth_type
    primary_smtp_address = user_account.primary_smtp_address

    return ewl_url, ews_auth_type, primary_smtp_address, user_account
def connect_to_server():

    credentials = ServiceAccount(username='******',
                                 password='******')
    config = Configuration(server='win9595.tcsmfdm.com',
                           credentials=credentials)
    account = Account(primary_smtp_address="*****@*****.**",
                      config=config,
                      autodiscover=False,
                      access_type=DELEGATE)
    return account
Пример #5
0
    def beforefetch(self):
        self.usercreds = ServiceAccount(
            username=self.userinfo[
                'ServiceAccountEmail'],  # Or [email protected] for O365
            password=self.userinfo['ServiceAccountPassword'])
        self.config = Configuration(server='outlook.office365.com',
                                    credentials=self.usercreds)

        emaillist = requests.get(config.API_ENDPOINT +
                                 'api/metadata/emaillist?UserId=' +
                                 str(self.userid))
        emaillist = json.loads(emaillist.text)
        self.__fetchmails(emaillist)
 def __init__(self, username, password, smtp_address, server):
     self.username = username
     self.password = password
     self.credentials = ServiceAccount(
         username=self.username,
         password=self.password)
     self.config = Configuration(
         server=server,
         credentials=self.credentials)
     self.account = Account(
         primary_smtp_address=smtp_address,
         config=self.config,
         autodiscover=False,
         access_type=DELEGATE)
Пример #7
0
def ews_smailer_error(subject, body):
    def send_email(account, subject, body, recipients, attachments=None):
        to_recipients = []
        for recipient in recipients:
            to_recipients.append(Mailbox(email_address=recipient))
        #####Create message#####
        m = Message(account=account,
                    folder=account.sent,
                    subject=subject,
                    body=body,
                    to_recipients=to_recipients)

        #####attach files#####
        for attachment_name, attachment_content in attachments or []:
            file = FileAttachment(name=attachment_name,
                                  content=attachment_content)
            m.attach(file)
        m.send_and_save()
        logger.info("Email sent successfully")

    ##### Create and configure logger #####
    logging.basicConfig(filename="newfile.log",
                        format='%(asctime)s %(message)s',
                        filemode='w')

    ##### Creating an object #####
    logger = logging.getLogger()

    ##### Setting the threshold of logger to DEBUG #####
    logger.setLevel(logging.DEBUG)
    logger.info("Function for sending email for error reporting is called")

    cfg = ConfigParser()
    cfg.read("config.ini")
    key = cfg['mail']['key']
    key = bytes(key, 'utf-8')
    passw = bytes(cfg['mail']['password'], 'utf-8')
    print(type(key))
    f = Fernet(key)
    credentials = ServiceAccount(username=cfg['mail']['id'],
                                 password=f.decrypt(passw).decode("utf-8"))

    config = Configuration(server="outlook.office365.com",
                           credentials=credentials)
    account = Account(primary_smtp_address=cfg['mail']['id'],
                      config=config,
                      autodiscover=False,
                      access_type=DELEGATE)

    send_email(account, subject, body, [cfg['internal']['id']], attachments=[])
Пример #8
0
def connect(email,
            password,
            service_endpoint=None,
            auth_type=None,
            access_type=None,
            user=None,
            win_domain=None,
            *args,
            **kwargs):
    access_type = DELEGATE if "DELEGATE" in access_type else IMPERSONATION

    if user and win_domain:
        creds = ServiceAccount(username="******".format(win_domain, user),
                               password=password,
                               max_wait=__max_timeout__)
    elif user and win_domain is None:
        creds = ServiceAccount(username=user,
                               password=password,
                               max_wait=__max_timeout__)
    else:
        creds = ServiceAccount(username=email,
                               password=password,
                               max_wait=__max_timeout__)

    if access_type is not None and auth_type is not None and service_endpoint is not None:
        conf = Configuration(service_endpoint=service_endpoint,
                             credentials=creds,
                             auth_type=auth_type)
        account = Account(primary_smtp_address=email,
                          config=conf,
                          autodiscover=False,
                          access_type=access_type)
    else:
        account = Account(primary_smtp_address=email,
                          autodiscover=True,
                          credentials=creds)
    return account
Пример #9
0
def initAccount():
    global account
    info = None

    try:
        info = getCouchDoc()
    except Exception as e:
        raise Exception("unable to get couch doc: {}".format(e))

    uname = os.getenv("EXCHANGE_PROXY_USERNAME")
    pw = os.getenv("EXCHANGE_PROXY_PASSWORD")

    print("creating service account with uname: {}, password: {}".format(uname, pw))

    credentials = ServiceAccount(username=uname, password=pw)
    try:
        resource = info["resource"]
        if not resource:
            raise Exception("resource not set in config doc")

        autodiscover = info["autodiscover-url"]
        if not autodiscover:
            raise Exception("autodiscover-url not set in config doc")

        access = info["access-type"]
        if not access:
            raise Exception("access-type not set in config doc")
    except KeyError as e:
        raise Exception("missing key {} in config doc".format(e))
    except Exception as e:
        raise Exception(e)

    # split domain and resource id
    split = resource.rsplit("@", 1)
    if len(split) != 2 or not split[1]:
        raise Exception("badly formatted resource (got: {}, expected: <resource_id>@<domain>)".format(resource))

    accesstype = IMPERSONATION if access == 'impersonation' else DELEGATE

    # populate autodiscover cache with correct server, because Office365 TLS cert is broken
    # https://github.com/ecederstrand/exchangelib/issues/337
    protocol = exchangelib.autodiscover.AutodiscoverProtocol(
            service_endpoint=autodiscover,
            credentials=credentials, auth_type='basic')
    exchangelib.autodiscover._autodiscover_cache[(split[1], credentials)] = protocol

    account = Account(primary_smtp_address=resource, credentials=credentials, autodiscover=True, access_type=accesstype)
    print("Exchange account successfully set up")
Пример #10
0
 def __init__(self, sensor_service, config):
     super(ItemSensor, self).__init__(sensor_service=sensor_service, config=config)
     self._logger = self.sensor_service.get_logger(name=self.__class__.__name__)
     self._stop = False
     self._store_key = 'exchange.item_sensor_date_str'
     self._timezone = EWSTimeZone.timezone(config['timezone'])
     self._credentials = ServiceAccount(
         username=config['username'],
         password=config['password'])
     self.primary_smtp_address = config['primary_smtp_address']
     self.sensor_folder = config['sensor_folder']
     try:
         self.server = config['server']
         self.autodiscover = False
     except KeyError:
         self.autodiscover = True
Пример #11
0
 def __init__(self, config):
     super(BaseExchangeAction, self).__init__(config)
     api_url = os.environ.get('ST2_ACTION_API_URL', None)
     token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
     self.client = Client(api_url=api_url, token=token)
     self._credentials = ServiceAccount(
         username=config['username'],
         password=config['password'])
     self.timezone = EWSTimeZone.timezone(config['timezone'])
     try:
         server = config['server']
         autodiscover = False
     except KeyError:
         autodiscover = True
     cache = self._get_cache()
     if cache:
         config = Configuration(
             service_endpoint=cache.ews_url,
             credentials=self._credentials,
             auth_type=cache.ews_auth_type)
         self.account = Account(
             primary_smtp_address=cache.primary_smtp_address,
             config=config,
             autodiscover=False,
             access_type=DELEGATE
         )
     else:
         if autodiscover:
             self.account = Account(
                 primary_smtp_address=config['primary_smtp_address'],
                 credentials=self._credentials,
                 autodiscover=autodiscover,
                 access_type=DELEGATE)
         else:
             config = Configuration(
                 server=server,
                 credentials=self._credentials)
             self.account = Account(
                 primary_smtp_address=config['primary_smtp_address'],
                 config=config,
                 autodiscover=False,
                 access_type=DELEGATE)
         self._store_cache_configuration()
Пример #12
0
    def __init__(self, email, server, username, password, forward_email=None, enableFaultTolerance=False):
        if enableFaultTolerance:
            credentials = ServiceAccount(
                username=username,
                password=password
            )
        else:
            credentials = Credentials(
                username=username,
                password=password
            )

        self.account = Account(
            primary_smtp_address=email,
            config=Configuration(
                server=server,
                credentials=credentials,
            ),
            autodiscover=False,
            access_type=DELEGATE,
        )
        self.forward_email = forward_email
Пример #13
0
images_Directory = "/home/pi/Pictures"
replacements_Directory = "/home/pi/Pictures/Replacements"
# pulls all image files and dates to the images dict from the data.py file
images = catalog

# variables
failed_body = "There was an error fulfilling your request. be sure to check the formatting of your " \
              "subject line and that the date is not passed or improperly formatted. Format should be date in XX/XX/XXXX" \
              "\nExample: 02/12/2099" \
              "\n\nFor list of files and their names, send a message or reply to this message with the subject line 'files'\n" \
              "If the file youre attempting to update is not in that list of files it cannot be added or updated at this time."
update_success = "The requested changes have been made"
noAttachment_body = "There was an error fulfilling your request. There was no attached image to update."

# exchangelib login's
credentials = ServiceAccount(username='******',
                             password='******')
account = Account(primary_smtp_address='*****@*****.**',
                  credentials=credentials,
                  autodiscover=True,
                  access_type=DELEGATE)


# send messages...
def sendMessage(recipient, subject, body):
    try:
        m = Message(account=account,
                    folder=account.sent,
                    subject=subject,
                    body=body,
                    to_recipients=[Mailbox(email_address=recipient)])
    except Exception as e:
def getEmailObject(email_username,email_password,email_server,email_smtp):
    credentials = ServiceAccount(username=email_username, password=email_password)
    config = Configuration(server=email_server, credentials=credentials)
    account = Account(primary_smtp_address=email_smtp, config=config, autodiscover=False, access_type=DELEGATE)
    return account
Пример #15
0
password = os.environ.get("EXCHANGE_PASSWORD")
username = os.environ.get("EXCHANGE_USERNAME")
outgoing_email_address = os.environ.get("EXCHANGE_OUTGOING_ADDRESS")
soundfile = os.environ.get("NOTIFICATION_SOUND")
exchange_server = os.environ.get("EXCHANGE_SERVER")

if soundfile != "":
    # load a sound file
    pygame.mixer.pre_init()
else:
    print("Skipping loading of soundfile")

print("Initiating connection to exchange...")
# If you want to enable the fault tolerance, create credentials as a service account instead:
credentials = ServiceAccount(username=username, password=password)

# Set up a target account and do an autodiscover lookup to find the target EWS endpoint:
account = Account(primary_smtp_address=outgoing_email_address, credentials=credentials,
                  autodiscover=True, access_type=DELEGATE)

config = Configuration(server=exchange_server, credentials=credentials, auth_type=NTLM)

last_number_of_emails = account.inbox.unread_count

print("Waiting for emails... Press CTRL+C to stop")

try:
    while True:
        # Update the counters
        account.inbox.refresh()
Пример #16
0
def get_accounts(logger=None, **config):
    """
    get a list of working Exchange accounts

    This function expects that each Exchange account is described by the
    ``config`` argument as shown in the ``JSON`` snippet below.

    A full representation of the structure of the ``config`` argument as
    used in the :ref:`Mail Borg Client Application` is available in the
    :ref:`borg_client_config` section.

    .. code-block:: json

        {
            "smtp_address":"*****@*****.**",
            "domain_account":
                {
                    "domain":"PHSABC",
                    "username":"******",
                    "password":"******"
                },
                "exchange_autodiscover":true,
                "autodiscover_server":null
        }

    :arg dict config:

       a :class:`dictionary <dict>` that matches the structure described in
       :ref:`borg_client_config` (or the relevant portions thereof)

       As used in the :ref:`Mail Borg Client Application`, the ``config``
       argument is provided via an :attr:`WitnessMessages.config` instance
       attribute

    :arg logger:

        logging facility; Usually provided by the caller the logger
        data is provided by the calling function but this function is capable
        of creating a :class:`_Logger` instance if needed

    :type logger: :class:`_Logger`


    :returns:
        :class:`list` of :class:`exchangelib.Account` objects
        An :class:`exchangelib.Account` object is only created if this
        module was able to connect to the EWS end point using the provided
        credentials.

        If an Exchange account entry in the ``config`` argument cannot be used
        to create a valid :class:`exchangelib.Account` instance, an error
        will be logged and there will be no matching entry in the return.

        If none of the Exchange account entries in the ``config`` argument can
        be used to create a valid :class:`exchangelib.Account` instance,
        an error will be logged and the function will return ``None``

    """
    if not config:
        config = load_config()

    if logger is None:
        logger = _Logger()

    accounts = []

    exchange_accounts = config.get('exchange_client_config').\
        get('exchange_accounts')
    for exchange_account in exchange_accounts:
        if not validate_email_to_ascii(
                exchange_account.get('smtp_address'), logger=logger, **config):
            continue

        credentials = ServiceAccount(
            username='******'.format(
                exchange_account.get('domain_account').get('domain'),
                exchange_account.get('domain_account').get('username')),
            password=exchange_account.get('domain_account').get('password'))

        exc_config = None
        if not exchange_account.get('exchange_autodiscover', True):
            exc_config = Configuration(
                server=exchange_account.get('autodiscover_server'),
                credentials=credentials)

        try:
            if exchange_account.get('exchange_autodiscover', True):
                accounts.append(
                    Account(primary_smtp_address=exchange_account.get(
                        'smtp_address'),
                            credentials=credentials,
                            autodiscover=True,
                            access_type=DELEGATE))
            else:
                accounts.append(
                    Account(primary_smtp_address=exchange_account.get(
                        'smtp_address'),
                            config=exc_config,
                            autodiscover=False,
                            access_type=DELEGATE))
            logger.info(
                dict(
                    type='connection',
                    status='PASS',
                    wm_id=config.get('wm_id'),
                    message='connected to exchange',
                    account='{}\\{}, {}'.format(
                        exchange_account.get('domain_account').get('domain'),
                        exchange_account.get('domain_account').get('username'),
                        exchange_account.get('smtp_address'))))
        except Exception as err:  # pylint: disable=broad-except
            logger.err(
                dict(
                    type='connection',
                    status='FAIL',
                    wm_id=config.get('wm_id'),
                    message='cannot connect to exchange',
                    account='{}\\{}, {}'.format(
                        exchange_account.get('domain_account').get('domain'),
                        exchange_account.get('domain_account').get('username'),
                        exchange_account.get('smtp_address')),
                    exeption=str(err)))

    if not accounts:
        logger.err(
            dict(type='configuration',
                 status='FAIL',
                 wm_id=config.get('wm_id'),
                 account=None,
                 message=(
                     'no valid exchange account found in config for bot %s' %
                     config.get('host_name'))))
        return None

    return accounts
Пример #17
0
from exchangelib import Account, DELEGATE, Configuration, ServiceAccount
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
import urllib3
from bs4 import BeautifulSoup
from slack import slack_integration
import schedule
import time
import re
from bean import mail_bean
import methods

urllib3.disable_warnings()

BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

credentials = ServiceAccount(username='******',
                             password='******')
config = Configuration(server='win9595.tcsmfdm.com', credentials=credentials)
account = Account(primary_smtp_address="*****@*****.**",
                  config=config,
                  autodiscover=False,
                  access_type=DELEGATE)


def extract_new_structured_email():

    for new_structured_email in account.inbox.filter(
            is_read=False, subject__istartswith='[EXTERNAL] ALARM:'):

        subject_email = new_structured_email.subject
        from_email = new_structured_email.sender.email_address
        date_email = new_structured_email.datetime_received
Пример #18
0
from exchangelib import DELEGATE, Account, ServiceAccount, EWSDateTime, EWSTimeZone, CalendarItem, Configuration
import datetime
import time
from twilio.rest import Client
import html

# Twilio Credentials
account_sid = "#########"
auth_token = "#########"

client = Client(account_sid, auth_token)

# Exchange Credentials
credentials = ServiceAccount(username='******', password='******')
account = Account(primary_smtp_address='#########"',
                  credentials=credentials,
                  autodiscover=True,
                  access_type=DELEGATE)

# Cache Exchange Credentials. This prevents server timeout
ews_url = account.protocol.service_endpoint
ews_auth_type = account.protocol.auth_type
primary_smtp_address = account.primary_smtp_address
config = Configuration(service_endpoint=ews_url,
                       credentials=credentials,
                       auth_type=ews_auth_type)

# Create account
myaccount = Account(primary_smtp_address=primary_smtp_address,
                    config=config,
                    autodiscover=False,
Пример #19
0
        to_recipients.append(Mailbox(email_address=recipient))
    # Create message
    m = Message(account=account,
                folder=account.sent,
                subject=subject,
                body=body,
                to_recipients=to_recipients)

    # attach files
    for attachment_name, attachment_content in attachments or []:
        file = FileAttachment(name=attachment_name, content=attachment_content)
        m.attach(file)
    m.send_and_save()


credentials = ServiceAccount(username=cfg['user'], password=cfg['password'])

config = Configuration(server=cfg['server'], credentials=credentials)
account = Account(primary_smtp_address=cfg['smtp_address'],
                  config=config,
                  autodiscover=False,
                  access_type=DELEGATE)

# Read attachment
attachments = []
with open('filestorage/numbers-test-document.pdf', 'rb') as f:
    content = f.read()
attachments.append(('whatever.pdf', content))

# Send email
send_email(account,
Пример #20
0
except FileNotFoundError:
    print(
        'Copy settings.yml.sample to settings.yml and enter values for your test server'
    )
    raise

categories = ['perftest']
tz = EWSTimeZone.timezone('America/New_York')

verify_ssl = settings.get('verify_ssl', True)
if not verify_ssl:
    from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
    BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

config = Configuration(server=settings['server'],
                       credentials=ServiceAccount(settings['username'],
                                                  settings['password']))
print('Exchange server: %s' % config.protocol.server)

account = Account(config=config,
                  primary_smtp_address=settings['account'],
                  access_type=DELEGATE)

# Remove leftovers from earlier tests
account.calendar.filter(categories__contains=categories).delete()


# Calendar item generator
def generate_items(count):
    start = tz.localize(EWSDateTime(2000, 3, 1, 8, 30, 0))
    end = tz.localize(EWSDateTime(2000, 3, 1, 9, 15, 0))
    tpl_item = CalendarItem(
Пример #21
0
def ews_smailer(email, filename, list):
    def send_email(account, subject, body, recipients, attachments=None):
        to_recipients = []
        for recipient in recipients:
            to_recipients.append(Mailbox(email_address=recipient))
        #####Create message#####
        m = Message(account=account,
                    folder=account.sent,
                    subject=subject,
                    body=body,
                    to_recipients=to_recipients)

        #####attach files#####
        for attachment_name, attachment_content in attachments or []:
            file = FileAttachment(name=attachment_name,
                                  content=attachment_content)
            m.attach(file)
        m.send_and_save()
        logger.info("Email sent successfully")

    ##### Create and configure logger #####
    logging.basicConfig(filename="newfile.log",
                        format='%(asctime)s %(message)s',
                        filemode='w')

    ##### Creating an object #####
    logger = logging.getLogger()

    ##### Setting the threshold of logger to DEBUG #####
    logger.setLevel(logging.DEBUG)
    logger.info("Function for sending email is called")

    cfg = ConfigParser()
    cfg.read("config.ini")
    key = cfg['mail']['key']
    key = bytes(key, 'utf-8')
    print(type(key))
    passw = bytes(cfg['mail']['password'], 'utf-8')
    f = Fernet(key)
    print(f.decrypt(cfg['mail']['password']).decode("utf-8"))
    credentials = ServiceAccount(username=cfg['mail']['id'],
                                 password=f.decrypt(passw).decode("utf-8"))

    config = Configuration(server="outlook.office365.com",
                           credentials=credentials)
    account = Account(primary_smtp_address=cfg['mail']['id'],
                      config=config,
                      autodiscover=False,
                      access_type=DELEGATE)

    #####Read attachment#####
    attachments = []
    filename = filename + ".xlsx"
    with open(filename, 'rb') as f:
        content = f.read()
    attachments.append((filename, content))

    #####Send email#####
    body = '''
Hello,

Please find attached the utilization report of RBA script of\n
    PU : ''' + list[0] + '''
    DU : ''' + list[1] + '''
    Account : ''' + list[2] + '''
    Script name. : ''' + filename + '''


Thank You. 

Regards
RBA Utilization Reporter Team


Incase of any quesries contact us at [email protected]
    '''
    subject = "RBA Utilization Report - " + list[0] + "-" + list[
        1] + "-" + list[2] + "-" + filename
    send_email(account, subject, body, [email], attachments=attachments)