Exemple #1
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)
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)
Exemple #3
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)
Exemple #4
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 test_autodiscover_from_account(self):
     from exchangelib.autodiscover import _autodiscover_cache
     _autodiscover_cache.clear()
     account = Account(
         primary_smtp_address=self.account.primary_smtp_address,
         credentials=self.account.protocol.credentials,
         autodiscover=True,
         locale='da_DK')
     self.assertEqual(account.primary_smtp_address,
                      self.account.primary_smtp_address)
     self.assertEqual(account.protocol.service_endpoint.lower(),
                      self.account.protocol.service_endpoint.lower())
     self.assertEqual(account.protocol.version.build,
                      self.account.protocol.version.build)
     # Make sure cache is full
     self.assertTrue((account.domain, self.account.protocol.credentials,
                      True) in _autodiscover_cache)
     # Test that autodiscover works with a full cache
     account = Account(
         primary_smtp_address=self.account.primary_smtp_address,
         credentials=self.account.protocol.credentials,
         autodiscover=True,
         locale='da_DK')
     self.assertEqual(account.primary_smtp_address,
                      self.account.primary_smtp_address)
     # Test cache manipulation
     key = (account.domain, self.account.protocol.credentials, True)
     self.assertTrue(key in _autodiscover_cache)
     del _autodiscover_cache[key]
     self.assertFalse(key in _autodiscover_cache)
     del _autodiscover_cache
Exemple #6
0
	def connect(self, url, email):
		ews_url = url# "http://*****:*****@serverchoice.com"
		credentials = Credentials(primary_smtp_address, 'topsecret')
		config = Configuration(service_endpoint=ews_url, credentials=credentials, auth_type=ews_auth_type)
		self.account = Account(
		    primary_smtp_address=primary_smtp_address, config=config, autodiscover=False, access_type=DELEGATE
		)
Exemple #7
0
 def connect_account(self,email,config=None):
     """
     param email: str, like [email protected]
     param config: Configuration
     return: Account object
     """
     if config==None:
         return Account(primary_smtp_address=email, config=self.config,autodiscover=False, access_type=DELEGATE)
     return Account(primary_smtp_address=email, config=config,autodiscover=False, access_type=DELEGATE)
def main():
    config_file_path = os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        'exchange-calendar-to-org.cfg')

    config = configparser.ConfigParser()
    config.read(config_file_path)

    email = config.get('Settings', 'email')
    try:
        server_url = config.get('Settings', 'server_url')
    except configparser.NoOptionError:
        server_url = None
    password = config.get('Settings', 'password')
    sync_days = int(config.get('Settings', 'sync_days'))
    org_file_path = config.get('Settings', 'org_file')
    tz_string = config.get('Settings', 'timezone_string')
    sslverify = config.getboolean('Settings', 'verify_ssl')

    tz = EWSTimeZone.timezone(tz_string)

    credentials = Credentials(username=email, password=password)

    if server_url is None:
        account = Account(
            primary_smtp_address=email,
            credentials=credentials,
            autodiscover=True,
            access_type=DELEGATE)
    else:
        server = Configuration(server=server_url, credentials=credentials, verify_ssl=sslverify)
        account = Account(
            primary_smtp_address=email,
            config=server,
            autodiscover=False,
            access_type=DELEGATE)

    now = datetime.datetime.now()
    end = now + datetime.timedelta(days=sync_days)

    items = account.calendar.filter(
        start__lt=tz.localize(EWSDateTime(end.year, end.month, end.day)),
        end__gt=tz.localize(EWSDateTime(now.year, now.month, now.day)), )

    text = []
    text.append('* Calendar')
    text.append('\n')
    for item in items:
        text.append(get_item_text(item, tz))
        text.append('\n')

    f = open(org_file_path, 'w')
    f.write(''.join(text))
Exemple #9
0
def fetch_free_busy(date, uid):
    acc = current_app.config['EXCHANGE_PROVIDER_ACCOUNT']
    creds = current_app.config['EXCHANGE_PROVIDER_CREDENTIALS']
    server = current_app.config['EXCHANGE_PROVIDER_SERVER']
    domain = current_app.config['EXCHANGE_DOMAIN']

    if not creds or not server or not domain:
        raise RuntimeError('Exchange provider not configured!')

    credentials = Credentials(*creds)
    configuration = Configuration(server=server,
                                  auth_type=NTLM,
                                  credentials=credentials)

    uid_account = Account(acc, config=configuration, autodiscover=False)
    accounts = [
        (uid_account, 'Organizer', False),
        (
            Account(f'{uid}@{domain}',
                    autodiscover=False,
                    config=configuration),
            'Optional',
            False,
        ),
    ]

    tz = uid_account.default_timezone
    start = utc.localize(datetime.combine(date, time.min)).astimezone(tz)
    end = start + timedelta(hours=24)

    results = []

    try:
        info = uid_account.protocol.get_free_busy_info(accounts=accounts,
                                                       start=start,
                                                       end=end)

        for busy_info in info:
            if busy_info.view_type == 'FreeBusyMerged':
                for event in busy_info.calendar_events or []:
                    overlap = find_overlap(date, event.start, event.end)
                    if event.busy_type in {'Busy', 'Tentative', 'OOF'
                                           } and overlap:
                        results.append(overlap)
    except (ErrorProxyRequestProcessingFailed, ErrorMailRecipientNotFound):
        # mailbox (probably) doesn't exist
        return []

    return [((start.hour, start.minute), (end.hour, end.minute))
            for start, end in results]
Exemple #10
0
 def setup(self):
     if self.autodiscover:
         self.account = Account(
             primary_smtp_address=self.primary_smtp_address,
             credentials=self._credentials,
             autodiscover=True,
             access_type=DELEGATE)
     else:
         config = Configuration(server=self.server,
                                credentials=self._credentials)
         self.account = Account(
             primary_smtp_address=self.primary_smtp_address,
             config=config,
             autodiscover=False,
             access_type=DELEGATE)
Exemple #11
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))
Exemple #12
0
def get_account(account_email):
    return Account(
        primary_smtp_address=account_email,
        autodiscover=False,
        config=config,
        access_type=ACCESS_TYPE,
    )
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)
Exemple #14
0
    def email(self, to, subject, body):
        """
        发送邮件
        :param to: 接收人
        :param subject: 邮件主题
        :param body: 邮件内容
        :return:
        """
        creds = Credentials(
            username=self.email_name,
            password=self.email_password
        )
        account = Account(
            primary_smtp_address=self.email_name + '@taoche.com',
            credentials=creds,
            autodiscover=True,
            access_type=DELEGATE
        )
        m = Message(
            account=account,
            subject=subject,
            body=HTMLBody(body),
            to_recipients=[Mailbox(email_address=i) for i in to]

        )
        m.send()
Exemple #15
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
Exemple #16
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()
Exemple #17
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
Exemple #18
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()
    def notifyOfChange(self):
        # format message body into something useful
        messageGreeting = ''
        today = str(date.today())
        # check to see if the application was a pass or a fail
        if self.passFail == True:
            messageGreeting = "Below are the stations that have received new check-ins: \n"
            formattedMessage = ''
            for ind in self.updateMessage:
                formattedMessage += str(ind + '\n')
        else:
            messageGreeting = "Station: The following station was unable to scrape.  Please check the URL " \
                              "for any discrepencies: \n"
            formattedMessage = "Station {0},\n URL https://www.plugshare.com/location/{1}".format(
                self.stationNames, self.urlID)

        # set exchange credentials
        credentials = Credentials('<UserName>', '<Password>')

        account = Account("<Outlook Email Address>",
                          credentials=credentials,
                          autodiscover=True,
                          access_type=DELEGATE)

        recipients = ['<Email Addresses>']

        #create message
        testMessage = Message(
            account=account,
            folder=account.sent,
            subject='{0} Plugshare Report (auto-generated)'.format(today),
            body="{0}{1}".format(messageGreeting, formattedMessage),
            to_recipients=recipients)

        testMessage.send_and_save()
Exemple #20
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
def miniprogram_booking_roomCode_get(roomCode, monthToLoad):  # noqa: E501
    # 按房间信息和月份(query中)获取所有的预约信息
    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"])
    responseList = []
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    try:
        room_account = Account(
            primary_smtp_address=('*****@*****.**' % roomCode),
            credentials=credentials,
            config=config
        )
    except Exception as e:
        db_session.remove()
        return {'code': -2002, 'message': '代理用的Office Account初始化失败', "log": str(e)}, 200
    monthToLoad_year = int(monthToLoad.split("-")[0])
    monthToLoad_month = int(monthToLoad.split("-")[1])
    if monthToLoad_month == 1:
        start = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year - 1, 12, 1))
    else:
        start = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year, monthToLoad_month - 1, 1))
    if monthToLoad_month == 11:
        end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year + 1, 1, 1))
    elif monthToLoad_month == 12:
        end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year + 1, 2, 1))
    else:
        end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year, monthToLoad_month + 2, 1))
    try:
        for item in room_account.calendar.view(start=start, end=end).all().order_by('start'):
            notes = db_session.query(orm.BookingNotes_db).filter(orm.BookingNotes_db.changekey == item.changekey).one_or_none()
            localizedStart = item.start.astimezone(get_localzone())
            localizedEnd = item.end.astimezone(get_localzone())
            bookedByID = getattr(notes, "bookedByID", 0)
            bookedByName = getattr(notes, "bookedByName", "")
            responseList.append({
                'startDate': ("%d-%0*d-%0*d" % (localizedStart.year, 2, localizedStart.month, 2, localizedStart.day)),
                'endDate': ("%d-%0*d-%0*d" % (localizedEnd.year, 2, localizedEnd.month, 2, localizedEnd.day)),
                'startTime': ("%0*d:%0*d" % (2, localizedStart.hour, 2, localizedStart.minute)),
                'endTime': ("%0*d:%0*d" % (2, localizedEnd.hour, 2, localizedEnd.minute)),
                'subject': item.subject,
                'changekey': item.changekey,
                'bookedByID': bookedByID,
                'bookedByName': bookedByName,
                'description': '' if not getattr(item, 'text_body') else getattr(item, 'text_body'),
                'type': 'appointment'
            })
    except Exception as e:
        db_session.remove()
        return {'code': -2003, 'message': '获取房间事件列表失败', 'log': str(e)}, 200
    db_session.remove()
    return {'code': 0, 'data': responseList, 'message': '成功'}, 200
Exemple #22
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')
Exemple #23
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 __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
Exemple #25
0
def send_mail_exchange(config, recipients, subject, body, attachments):
    """Sends the supplied message through an Exchange connection to the list of recipients"""
    # Gathering email account details
    user = config["Email"]
    password = encryption.get_password()

    # Connecting to Exchange account
    account = None
    try:
        credentials = Credentials(user, password)
        account = Account(user, credentials=credentials, autodiscover=True)
        logger.debug("Exchange connection successful")
    except Exception as e:
        logger.error("Could not connect to Exchange Email: " + str(e))
        return

    # Constructing message
    message = Message(account=account,
                      subject=subject,
                      body=body,
                      to_recipients=recipients.replace(", ", ",").split(","))

    # Attaching files
    for image_path in attachments:
        with open(image_path, 'rb') as f:
            repImage = FileAttachment(name=os.path.basename(image_path),
                                      content=f.read())
        message.attach(repImage)

    # Sending
    message.send_and_save()
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
Exemple #27
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
Exemple #28
0
 def login(self):
     """
     This function logs the user into the MS Exchange mailbox
     :return: The mailbox account object
     """
     credentials = Credentials(self.username, self.password)
     return Account(self.account, credentials=credentials, autodiscover=True)
    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
def Email_Attachment(username,password,Folder_name, File_path):
    #连接邮箱所需信息
    creds = Credentials(
        username=username,
        password=password
    )
    account = Account(
        primary_smtp_address=username,
        credentials=creds,
        autodiscover=True,
        access_type=DELEGATE
    )

    #迭代收件箱下的文件夹中的附件,并保存到本地
    for item in account.inbox.children:
        if item.name==Folder_name:#只保存Folder_name参数文件夹下的附件
            index=0
            totalcount=0
            page=0
            while True:          
                for model in item.all()[page:page+50]:
                    index=index+1
                    for attachment in model.attachments:
                        if isinstance(attachment,type(attachment)):
                            with open(File_path + attachment.name, 'wb') as f:
                                f.write(attachment.content)
                if totalcount==index:
                    break
                page=page+50
                totalcount=index