示例#1
0
    def getAccount(self):
        self.logger.debug('%s. getAccount starts', __name__)
        try:
            username = self.cfg.get('EWS', 'username')
            password = self.cfg.get('EWS', 'password')
            authType = self.cfg.get('EWS', 'auth_type')
            credentials = Credentials(username=username, password=password)

            ews_server = self.cfg.get('EWS', 'server')
            smtp_address = self.cfg.get('EWS', 'smtp_address')

            if authType == 'NTLM':
                config = Configuration(server=ews_server,
                                       credentials=credentials,
                                       auth_type=NTLM)
            elif authType == 'None':
                #O365 does not use NTLM auth
                config = Configuration(server=ews_server,
                                       credentials=credentials,
                                       auth_type=None)
            else:
                raise ValueError(authType)

            account = Account(primary_smtp_address=smtp_address,
                              config=config,
                              autodiscover=False,
                              access_type=DELEGATE)

            return account
        except ValueError:
            self.logger.error('authType not supported: %s', authType)
            raise
        except Exception as e:
            self.logger.error('Failed to get account', exc_info=True)
            raise
示例#2
0
    def authenticate(self, username, password, server, build, account,
                     verifyssl):
        """
        Authenticates to Exchange server
        """

        BaseProtocol.USERAGENT = "Shuffle Automation"
        if not verifyssl or verifyssl.lower().strip() == "false":
            BaseProtocol.HTTP_ADAPTER_CLS = RootCAAdapter

        processed_build = None
        if type(build) == str:
            try:
                processed_build = [int(x) for x in build.split(".")]
                if len(build) == 0:
                    build = None
                elif len(build) < 2 or len(build) > 4:
                    return {
                        "account":
                        None,
                        "error":
                        "Build requires at least major and minor version [Eg. 15.1], at most 4 number [Eg. 15.0.1.2345]",
                    }
            except ValueError:
                return {
                    "account":
                    None,
                    "error":
                    "Build needs to be a sequence of numbers dot separated, not %s"
                    % build,
                }

        try:
            credentials = Credentials(username, password)
            if processed_build:
                version = Version(build=Build(*processed_build))
                config = Configuration(server=server,
                                       credentials=credentials,
                                       version=version)
            else:
                config = Configuration(server=server, credentials=credentials)

            account = Account(account,
                              config=config,
                              autodiscover=False,
                              access_type=DELEGATE)
            account.root.refresh()

        except (exchangelib.errors.TransportError, Exception) as error:
            return {
                "account": None,
                "error": "Can't connect to Exchange server: %s" % (error),
            }

        return {"account": account, "error": False}
示例#3
0
    def _generate_state(self, sm):
        service_account = Credentials(
                username=self._admin_user, password=self._admin_password)
        config = Configuration(
                retry_policy=FaultTolerance(max_wait=1800),
                service_endpoint=self._server,
                credentials=service_account if self._server else None)

        try:
            account = Account(
                    primary_smtp_address=self.address,
                    credentials=service_account,
                    config=config,
                    autodiscover=not bool(self._server),
                    access_type=IMPERSONATION)
        except ErrorNonExistentMailbox as e:
            raise ResourceUnavailableError(self, e.args)

        try:
            yield account
        finally:
            # XXX: we should, in principle, close account.protocol here, but
            # exchangelib seems to keep a reference to it internally and so
            # waits forever if we do
            pass
def Email(self,to, subject, body,email_type, attachments=None):
    creds = Credentials(username=self.localVariable["__EMAILEX__"],
                        password=self.localVariable["__EMAILEX_PASSWORD__"])
    config = Configuration(server='outlook.office365.com',credentials=creds)
    account = Account(
        primary_smtp_address=self.localVariable["__EMAILEX__"],
        config=config,
        # credentials=creds,
        autodiscover=False,
        access_type=DELEGATE
    )
    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(body),
        to_recipients = [Mailbox(email_address=to)]
    )
    if attachments:
        m.attach(attachments)
    if email_type==1 and to in list(self.localStore.keys()):
        print("清除 %s" % to)
        self.localStore.pop(to)
    try:
        m.send()
        if email_type == 0:
            message = u"验证码已发送邮箱!"
        else:
            message = u"证书已发送邮箱!"
        return message
    except:
        message = u"发送失败!"
        return message
示例#5
0
def ews_account():

    # TODO:  get from a keychain
    #ews_password = None
    # ews_password = input( "Password: "******"master" )
    if ews_password is None:
        ews_password = input( "Password: "******"master", ews_password  )

    credentials = Credentials(
        os.environ.get( "EWS_ACCOUNT" ),
        ews_password
    )

    config = Configuration(
        server=os.environ.get( "EWS_SERVER" ),
        has_ssl=True,
        credentials=credentials
    )

    a = Account(
        primary_smtp_address=os.environ.get( "EWS_SMTP_ADDRESS" ),
        credentials=credentials,
        config=config
    )

    return a
示例#6
0
    def ews_config_setup(cls, user, domain, password):
        """Authenticates with Outlook EWS and returns the account objected created with the passed credentials.
        (From: "https://github.com/mikesiegel/ews-crack")

        :param user:     (String) the user you wish to authenticate, (for the email '*****@*****.**', just pass 'test' as the user)
        :param domain:   (String) the domain of the user to authenticate
        :param password: (String) the password of the user to authenticate

        :return:         (Account,Config) returns the account object returned from EWS and the config details
        """
        try:
            config = Configuration(
                server='outlook.office365.com/EWS/Exchange.asmx',
                credentials=Credentials(username="******".format(user, domain),
                                        password=password))

            account = Account(primary_smtp_address="{}@{}".format(
                user, domain),
                              autodiscover=False,
                              config=config,
                              access_type=DELEGATE)

        except UnauthorizedError:
            print("Bad password")
            return None, None

        except CASError:
            print("CAS Error: User {} does not exist.".format(user))
            return None, None

        return account, config
示例#7
0
def send_email(title='报警邮件',
               recervers='*****@*****.**',
               msg='content',
               file_name=''):
    try:
        credentials = Credentials(username, password)
        config = Configuration(server=r_server, credentials=credentials)
        account = Account(username,
                          autodiscover=False,
                          config=config,
                          access_type=DELEGATE)

    except Exception as e:
        print('错误: {0}'.format(e))
        sys.exit(1)

    m = Message(
        account=account,
        subject=title,
        body=HTMLBody(msg),
        to_recipients=[Mailbox(email_address=x) for x in recervers.split(',')])
    if file_name:
        with open(os.path.abspath(r"../work_flow/sre.xls"), "rb") as f:
            cont = f.read()
        attchF = FileAttachment(name='值班表.xls', content=cont)
        m.attach(attchF)
        m.send_and_save()
    else:
        m.send()
示例#8
0
def acctSetup(params):

    server = params.get('server')
    email = params.get('email')
    password = params.get('password')
    shared = params.get('delegated')

    try:
        config = Configuration(server=server,
                               credentials=Credentials(email, password))

        if params.get('delegated'):
            account = Account(primary_smtp_address=shared,
                              autodiscover=False,
                              config=config,
                              access_type=DELEGATE)
        else:
            account = Account(primary_smtp_address=email,
                              autodiscover=False,
                              config=config,
                              access_type=DELEGATE)

        return account
    except Exception as e:
        print(e)
示例#9
0
def send_with_exchange(username, password, server, address, content,
                       subject='', to_recipients=[], attachements=[]):
    credentials = Credentials(username=username, password=password)
    config = Configuration(server=server, credentials=credentials)
    account = Account(
        primary_smtp_address=address,
        autodiscover=False,
        config=config,
        credentials=credentials,
        access_type=DELEGATE)

    _to_recipients = []
    for item in to_recipients:
        _to_recipients.append(Mailbox(email_address=item['email']))

    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(content),
        to_recipients=_to_recipients)

    if attachements:
        for item in attachements:
            with open(item['src'], 'rb') as f:
                img_attach = FileAttachment(name=item['name'], content=f.read())
            m.attach(img_attach)
    m.send()
示例#10
0
    def getAccount(self):
        self.logger.info('%s. getAccount starts', __name__)

        try:
            username = self.cfg.get('EWS', 'username')
            password = self.cfg.get('EWS', 'password')
            credentials = Credentials(username=username, password=password)

            ews_server = self.cfg.get('EWS', 'server')
            smtp_address = self.cfg.get('EWS', 'smtp_address')

            config = Configuration(server=ews_server,
                                   credentials=credentials,
                                   auth_type=NTLM)
            #auth_type=NTLM,
            #verify_ssl='/home/dc/exchange.crt')

            account = Account(primary_smtp_address=smtp_address,
                              config=config,
                              autodiscover=False,
                              access_type=DELEGATE)

            return account
        except Exception as e:
            self.logger.error('Failed to get account', exc_info=True)
            raise
示例#11
0
def connection(process_name, tasks, result_multi, return_dict):
    #print('[%s] evaluation routine starts' % process_name)
    while True:
        new_value = tasks.get()
        #print(type(new_value))
        if type(new_value) == int:
            #print('[%s] evaluation routine quits' % process_name)
            result_multi.put(-1)
            break
        else:
            User = new_value[0]
            Password = new_value[1]
            Server_ads = new_value[2]
            start_time = new_value[3]
            x = new_value[4]
            #print(User,Password,Server_ads)
            credentials = Credentials(User, Password)
            try:

                config = Configuration(server=Server_ads,
                                       credentials=credentials,
                                       auth_type='basic')
                print("\x1b[6;30;42m" + "Success" + "\x1b[0m" + " for :" +
                      User + " and Password:  "******"%H:%M:%S",
                                             time.gmtime(elapsed_time))
                print("Time spend:" + elapsed_time)
                return_dict[x] = "Success"
                result_multi.put("Success")

            except Exception, e:
                print(str(e) + " USER: "******" password: "******"end")
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)
示例#13
0
def bulk_send_exchange_email(from_addr: str, sub: str, account: str,
                             pwd: str, user_name: str, names_list: str,
                             content_file: str, sheet: str, signature: str):
    """

    Sends email using Exchange

    :param from_addr: 
    :param sub: 
    :param account:
    :param pwd:
    :param user_name:
    :param content_file:
    :param names_list:
    :param sheet:
    :param signature:
    :return: 
    """
    recipients = spreadsheet_data(names_list, sheet)
    body = content_from_file(content_file)
    signature = content_from_file(signature)
    creds = Credentials(user_name, pwd)
    config = Configuration(server=account, credentials=creds)
    account = Account(primary_smtp_address=from_addr,
                      autodiscover=False, access_type=DELEGATE, config=config)
    for item in recipients:
        complete_email = 'Hello ' + item['First_Name'] + '\n\n' + body + '\n' + signature
        email_address = item['Email_Address']
        msg = Message(
            account=account,
            folder=account.sent,
            subject=sub,
            body=complete_email,
            to_recipients=[Mailbox(email_address=email_address)])
        msg.send_and_save()
示例#14
0
def send_exchange_email(from_addr: str, to_addr: str, sub: str, body: str,
                        account: str, pwd: str, user_name: str):
    """

    Sends email using Exchange

    :param from_addr: 
    :param to_addr: 
    :param sub: 
    :param body: 
    :param account:
    :param pwd:
    :param user_name:
    :return: 
    """
    creds = Credentials(user_name, pwd)
    config = Configuration(server=account, credentials=creds)
    account = Account(primary_smtp_address=from_addr,
                      autodiscover=False, access_type=DELEGATE, config=config)
    msg = Message(
        account=account,
        folder=account.sent,
        subject=sub,
        body=body,
        to_recipients=[Mailbox(email_address=to_addr)])
    msg.send_and_save()
示例#15
0
def get_exchange_events(server: str, domain: Optional[str], username: str,
                        password: str, range_start: datetime,
                        range_end: datetime) -> List[CalendarEvent]:
    """Connect to exchange calendar server and get events within range."""
    # load exchange module if necessary
    from exchangelib import Credentials, Configuration, Account, DELEGATE
    from exchangelib import EWSDateTime, EWSTimeZone

    # setup access
    full_username = r'{}\{}'.format(domain, username) if domain else username
    account = Account(primary_smtp_address=username,
                      config=Configuration(server=server,
                                           credentials=Credentials(
                                               full_username, password)),
                      autodiscover=False,
                      access_type=DELEGATE)

    # collect event information within given time range
    events: List[CalendarEvent] = []
    localzone = EWSTimeZone.localzone()
    local_start = localzone.localize(EWSDateTime.from_datetime(range_start))
    local_end = localzone.localize(EWSDateTime.from_datetime(range_end))
    for item in account.calendar.filter(  ##pylint: disable=no-member
            start__range=(local_start, local_end)).order_by('start'):
        events.append(
            CalendarEvent(title=item.subject,
                          start=item.start,
                          end=item.end,
                          duration=(item.end - item.start).seconds / 3600,
                          categories=item.categories))
    return events
示例#16
0
 def initialize_exchange_client(self, password=None):
     acc_credentials = Credentials(username=self.email_address, password=password)
     version = Version(build=Build(config.EXCHANGE_VERSION['major'], config.EXCHANGE_VERSION['minor']))
     acc_config = Configuration(service_endpoint=config.EXCHANGE_URL, credentials=acc_credentials,
                                auth_type='basic', version=version, retry_policy=FaultTolerance(max_wait=300))
     self.exchange_client = Account(primary_smtp_address=self.email_address, config=acc_config,
                                    autodiscover=True, access_type='delegate')
示例#17
0
def searchDelegates(params, fparser):

    server = params.get('server')
    email = params.get('email')
    password = params.get('password')

    if isinstance(fparser.get("galList"), (str)):
        fname = ''.join(fparser.get("galList"))
        fname = fname.split(' ')
    else:
        fname = fparser.get("galList")

    print('[+] Checking Where Compromised User Has Access' + '\n')

    for shared in fname:
        try:
            config = Configuration(server=server,
                                   credentials=Credentials(email, password))

            account = Account(primary_smtp_address=shared,
                              autodiscover=False,
                              config=config,
                              access_type=DELEGATE)

            folderInbox = account.inbox
            #print(folderInbox.permission_set)
            for s in folderInbox.permission_set.permissions:
                if s.permission_level != 'None':
                    print('User: {} has {} permissions on {}\'s Inbox'.format(
                        email, s.permission_level, shared))

        except Exception as e:
            if 'The specified object was not found in the store., The process failed to get the correct properties' not in str(
                    e):
                print(e)
示例#18
0
def EmailAccountAuthByNtlmHash(username, ntlmhash, email, server=None, flag=True):
    try:
        if flag:
            hash = ntlmhash if ntlmhash.find(":") > 0 else "00000000000000000000000000000000:%s"%str(ntlmhash)
            print("[+] 账号:%s 认证口令NTLM-Hash:%s"%(str(username), str(hash)))
        else:
            hash = ntlmhash
    except Exception as hashexception:
        print("[-] NTLM-Hash值输入错误!")
        raise hashexception
    try:
        credentials = Credentials(username, hash)
    except Exception as credexception:
        print("[-] 凭据生成错误!")
        raise credexception
    try:
        if server == None:
            email = Account(email, credentials=credentials, autodiscover=True)
            print("[+] 邮箱账号认证登录成功")
            return email
        else:
            config = Configuration(server, credentials)
            email = Account(primary_smtp_address=email, config=config, autodiscover=False)
            return email
    except Exception as error:
        print("[+] 账号连接或认证失败")
        return None
    def connect_to_account(self, primary_smtp_address, impersonation=False):
        """Connect to specified account and return it"""

        # Don't check certificates
        if not self.verify_cert:
            BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

        # Decide whether or not to use impersonation access
        access_type = IMPERSONATION if impersonation else DELEGATE

        # Use credentials to get account
        try:
            credentials = Credentials(username=self.username,
                                      password=self.password)
            config = Configuration(server=self.server, credentials=credentials)
            account = Account(primary_smtp_address=primary_smtp_address,
                              config=config,
                              autodiscover=self.verify_cert,
                              access_type=access_type)
        except ErrorNonExistentMailbox:
            raise NoMailboxError(primary_smtp_address)
        except ConnectionError:
            raise ServerConnectionError(self.server)
        except UnauthorizedError:
            raise CredentialsError()
        except ErrorImpersonateUserDenied:
            raise ImpersonationError(self.username, primary_smtp_address)
        return account
示例#20
0
 def test_close(self):
     proc = psutil.Process()
     ip_addresses = {
         info[4][0]
         for info in
         socket.getaddrinfo('example.com', 80, socket.AF_INET,
                            socket.SOCK_DGRAM, socket.IPPROTO_IP)
     }
     self.assertGreater(len(ip_addresses), 0)
     protocol = Protocol(
         config=Configuration(service_endpoint='http://example.com',
                              credentials=Credentials('A', 'B'),
                              auth_type=NOAUTH,
                              version=Version(Build(15, 1)),
                              retry_policy=FailFast()))
     session = protocol.get_session()
     session.get('http://example.com')
     self.assertEqual(
         len({
             p.raddr[0]
             for p in proc.connections() if p.raddr[0] in ip_addresses
         }), 1)
     protocol.release_session(session)
     protocol.close()
     self.assertEqual(
         len({
             p.raddr[0]
             for p in proc.connections() if p.raddr[0] in ip_addresses
         }), 0)
示例#21
0
def run_with_start_menu():
    user_select = input("Menu:\n "
                        "[1] Update all submissions \n "
                        "[2] Rerun quote analysis on database \n "
                        "[3] Set last updated timestamp to 2018-03-01"
                        "[5] Get list of messages new since last database update \n "
                        "[0] Devtest \n "
                        ">>")
    if user_select == "1":
        main()
    elif user_select == "2":
        log.info("Initializing database re-analysis")
        reanalyze_all()
    elif user_select == "3":
        timestamp = '2018-03-01-00-00-00'
        db.set_timestamp(timestamp)
    elif user_select == '5':
        with open(os.path.join(script_directory, 'credentials', 'CREDENTIALS.json')) as j:
            text = j.readline()
            d = json.loads(text)
        credentials = Credentials(username=d["UID"], password=d["PWD"])
        log.info("Accessing Exchange credentials")
        config_office365 = Configuration(server="outlook.office365.com", credentials=credentials)
        account = Account(primary_smtp_address="*****@*****.**", config=config_office365,
                          autodiscover=False, access_type=DELEGATE)
        latest_database_update = db.get_timestamp()
        print('Database latest updated ' + latest_database_update)
        new_messages = get_new_messages("Americas", account, from_datetime=latest_database_update)
        for message in new_messages:
            print("Subject: {} Sent: {}".format(message.subject, message.datetime_sent))
        print("All done. Bye")
    else:
        print(user_select)
        print('Invalid selection. Please restart and try again')
示例#22
0
    def authorize(
        self,
        username: str,
        password: str,
        autodiscover: bool = True,
        access_type: str = "DELEGATE",
        server: str = None,
        primary_smtp_address: str = None,
    ) -> None:
        """Connect to Exchange account

        :param username: account username
        :param password: account password
        :param autodiscover: use autodiscover or set it off
        :param accesstype: default "DELEGATE", other option "IMPERSONATION"
        :param server: required for configuration options
        :param primary_smtp_address: by default set to username, but can be
            set to be different than username
        """
        kwargs = {}
        kwargs["autodiscover"] = autodiscover
        kwargs["access_type"] = (DELEGATE if access_type.upper() == "DELEGATE"
                                 else IMPERSONATION)
        kwargs["primary_smtp_address"] = (primary_smtp_address if
                                          primary_smtp_address else username)
        self.credentials = Credentials(username, password)
        if server:
            self.config = Configuration(server=server,
                                        credentials=self.credentials)
            kwargs["config"] = self.config
        else:
            kwargs["credentials"] = self.credentials

        self.account = Account(**kwargs)
示例#23
0
def authenticate_by_email():
    global user_ip
    if not request.json or not 'email' in request.json:
        abort(400)
    data = request.json
    email = data['email']
    password = data['password']
    username = data['username']
    try:
        credentials = Credentials(email, password)
        config = Configuration(server='email.msb.com.vn', credentials=credentials)
        account = Account(email, config=config, autodiscover=False)
        logger.info(str(security_rule.query_rules('(?i)Allow SEVPN for %s'% username)))
        logger.info(user_ip)
        security_rule.update_rule_by_description(
            description = '(?i)Allow SEVPN for %s'% username, 
            ipRanges = '%s/32'%user_ip
        )
        return 'Rule updated', 200
    except UnauthorizedError:
        return 'Unauthorized', 403
    except TransportError:
        return 'Server Not Found', 404
    except Exception as e:
        logger.info(type(e))
        logger.info(e)
        return 'Unknown Errors', 500
示例#24
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
示例#25
0
def send_email(content, exchange_host, mailbox, mail_user, mail_password,
               dest_address):
    """
    Sends an email to dest_address containing the list of potential malicious new domains.
    """
    from exchangelib import DELEGATE, Account, Configuration, Credentials, Message, Mailbox

    message = "Found the following potential malicious new domains: {}".format(
        content)

    creds = Credentials(username=mail_user, password=mail_password)
    serverconfig = Configuration(server=exchange_host, credentials=creds)
    account = Account(primary_smtp_address=mailbox,
                      credentials=creds,
                      autodiscover=False,
                      config=serverconfig,
                      access_type=DELEGATE)

    if account:
        print("Authenticated as {} to O365 succeeded.".format(mail_user))
    else:
        print("Authentication to O365 mailbox as {} has failed.".format(
            mail_user))
        sys.exit(-1)

    m = Message(account=account,
                subject='New domain alert',
                body=message,
                to_recipients=[
                    Mailbox(email_address=dest_address),
                ])
    m.send()

    print("Email has been sent to {}.".format(dest_address))
示例#26
0
def prepare():
    if NON_SECURE:
        BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

    if not USE_PROXY:

        def remove_from_dict(d, key):
            if key in d:
                del d[key]

        import os

        remove_from_dict(os.environ, 'HTTP_PROXY')
        remove_from_dict(os.environ, 'http_proxy')
        remove_from_dict(os.environ, 'HTTPS_PROXY')
        remove_from_dict(os.environ, 'https_proxy')

        os.environ['NO_PROXY'] = EWS_SERVER

    version = get_version(VERSION_STR)
    credentials = Credentials(username=USERNAME, password=PASSWORD)
    config_args = {
        'credentials': credentials,
        'auth_type': get_auth_method(AUTH_METHOD_STR),
        'version': version
    }
    if 'http' in EWS_SERVER.lower():
        config_args['service_endpoint'] = EWS_SERVER
    else:
        config_args['server'] = EWS_SERVER
    config = Configuration(**config_args)
    return config
示例#27
0
def folders(search, delegate):
    """
        Print exchange file structure.
    """
    credentials = Credentials(tbestate.username, tbestate.password)

    if delegate:
        username = delegate
    else:
        username = tbestate.username

    if tbestate.exch_host:
        config = Configuration(server=tbestate.exch_host,
                               credentials=credentials)
        account = Account(username,
                          config=config,
                          autodiscover=False,
                          access_type=DELEGATE)
    else:
        account = Account(username,
                          credentials=credentials,
                          autodiscover=True,
                          access_type=DELEGATE)

    # pylint: disable=maybe-no-member
    account.root.refresh()

    if search:
        for branches in account.root.glob(search):
            click.secho(f'{branches.tree()}')
            click.secho(f'-------------------------------------\n', dim=True)
    else:
        click.secho(f'{account.root.tree()}')
        click.secho(f'-------------------------------------\n', dim=True)
示例#28
0
def process_faxes(mail_server, fax_journal_account, fax_journal_password,
                  fax_storage_repo):
    """
    Function to run through mailbox and process fax items
    """
    exchange_credentials = Credentials(username=fax_journal_account,
                                       password=fax_journal_password)
    exchange_conn_config = Configuration(server=mail_server,
                                         credentials=exchange_credentials)
    exchange_account = Account(primary_smtp_address=fax_journal_account,
                               config=exchange_conn_config,
                               autodiscover=False,
                               access_type=DELEGATE)
    datetime_today = datetime.datetime.strptime(
        str(datetime.datetime.utcnow()).split(" ")[0],
        "%Y-%m-%d").strftime("%d%m%Y")
    if not os.path.exists(os.path.join(fax_storage_repo, datetime_today)):
        print "Does not exist"
        os.makedirs(os.path.join(fax_storage_repo, datetime_today))
    for i in exchange_account.inbox.all():
        fax_info = {}
        fax_info['message_id'] = i.message_id
        fax_info['subject'] = i.subject
        fax_info['datetime_sent'] = str(i.datetime_sent)
        fax_info['to_recipient'] = i.to_recipients[0].email_address
        fax_info['datetime_received'] = str(i.datetime_received)
        fax_info['sender'] = i.sender.email_address

        fax_path = os.path.join(CONFIGURATION['fax_storage_repo'],
                                datetime_today, fax_info['message_id'][1:-1])
        if not os.path.exists(fax_path):
            os.makedirs(fax_path)
        attachments_path = os.path.join(fax_path, 'attachments')
        if not os.path.exists(attachments_path):
            os.makedirs(os.path.join(fax_path, 'attachments'))
        meta_path = os.path.join(fax_path, 'meta.json')
        with open(meta_path, 'w') as outfile:
            json.dump(fax_info, outfile)
        for attachment in i.attachments:
            if isinstance(attachment, FileAttachment):
                attachment_path = os.path.join(attachments_path,
                                               attachment.name)
                with open(attachment_path, 'wb') as f:
                    f.write(attachment.content)
        encoded_html_body = i.body.encode('utf-8')
        html_body_path = os.path.join(fax_path, 'body.html')
        with open(html_body_path, 'wb+') as f:
            f.write(encoded_html_body)
        print fax_info['message_id'] + " completed."
        if not session.query(Fax).filter(
                Fax.message_id == i.message_id).first():
            fax_sql_record = Fax(subject=fax_info['subject'],
                                 message_id=fax_info['message_id'],
                                 path_to_folder=fax_path,
                                 datetime_received=i.datetime_received,
                                 sender=fax_info['sender'],
                                 to_recipient=fax_info['to_recipient'])
            session.add(fax_sql_record)
    session.commit()
示例#29
0
def connect(server: str, e_mail: str, username: str, password: str, auth_type=NTLM, access_type=DELEGATE) -> Account:
    """
    Get Exchange account connection with server
    """
    creds = Credentials(username=username, password=password)
    config = Configuration(server=server, credentials=creds, auth_type=auth_type)
    return Account(primary_smtp_address=e_mail, autodiscover=True,
                   config=config, credentials=creds, access_type=access_type)
示例#30
0
    def test_protocol_instance_caching(self, m):
        # Verify that we get the same Protocol instance for the same combination of (endpoint, credentials)
        m.get('https://example.com/EWS/types.xsd', status_code=200)
        base_p = Protocol(config=Configuration(
            service_endpoint='https://example.com/Foo.asmx', credentials=Credentials('A', 'B'),
            auth_type=NTLM, version=Version(Build(15, 1)), retry_policy=FailFast()
        ))

        for i in range(10):
            p = Protocol(config=Configuration(
                service_endpoint='https://example.com/Foo.asmx', credentials=Credentials('A', 'B'),
                auth_type=NTLM, version=Version(Build(15, 1)), retry_policy=FailFast()
            ))
            self.assertEqual(base_p, p)
            self.assertEqual(id(base_p), id(p))
            self.assertEqual(hash(base_p), hash(p))
            self.assertEqual(id(base_p._session_pool), id(p._session_pool))