Beispiel #1
0
    def login(self, server):
        '''Login to server, return account instance'''

        credentials = exchangelib.ServiceAccount(username=self.username,
                                                 password=self._password)
        if self.ews_url and self.ews_auth_type and self.smtp_host:
            config = exchangelib.Configuration(service_endpoint=self.ews_url,
                                               credentials=credentials,
                                               auth_type=self.ews_auth_type)

            account = exchangelib.Account(primary_smtp_address=server,
                                          config=config,
                                          autodiscover=False,
                                          access_type=exchangelib.DELEGATE)
        else:
            account = exchangelib.Account(primary_smtp_address=server,
                                          credentials=credentials,
                                          autodiscover=True,
                                          access_type=exchangelib.DELEGATE)

        self.ews_url = account.protocol.service_endpoint
        self.ews_auth_type = account.protocol.auth_type
        self.smtp_host = account.primary_smtp_address

        return account
Beispiel #2
0
 def ensure_connection(self):
     try:
         if not self.account:
             credentials = exchangelib.ServiceAccount(
                 username=self.username, password=self.password)
             if self.host:
                 config = exchangelib.Configuration(server=self.host,
                                                    credentials=credentials)
                 self.account = exchangelib.Account(
                     primary_smtp_address=self.email_address,
                     config=config,
                     autodiscover=False,
                     access_type=exchangelib.DELEGATE)
             else:
                 self.account = exchangelib.Account(
                     primary_smtp_address=self.email_address,
                     credentials=credentials,
                     autodiscover=True,
                     access_type=exchangelib.DELEGATE)
         yield
     except Exception as e:
         # NOTE(sileht): retry just once if the connection have been
         # broken to ensure this is not a sporadic connection lost.
         # Like wifi reconnect, sleep wake up
         # Wait a bit when disconnection occurs to not hog the cpu
         self.logger.warn(e)
         time.sleep(1)
         self.connection = None
	def open(self, address, password, host = None):
		""" Opens a connection to an email for reading
		Use: https://resources.hacware.com/connecting-to-the-ews-with-python-using-exchangelib-2/
		"""

		credentials = exchangelib.Credentials(address, password)

		if (host):
			config = exchangelib.Configuration(server = host, credentials = credentials)
			yield exchangelib.Account(address, config = config, autodiscover = False, access_type = exchangelib.DELEGATE)
		else:
			yield exchangelib.Account(address, credentials = credentials, autodiscover = True)
Beispiel #4
0
def getEvents(VALUES):
    """get events from exchange and write them to file"""
    url = VALUES['owa']
    username = VALUES['username']
    password = VALUES['password']
    BEFORE = int(VALUES['before'])
    FUTURE = int(VALUES['future'])

    try:
        credentials = exchangelib.Credentials(username=username,
                                              password=password)
        config = exchangelib.Configuration(server=url, credentials=credentials)
        account = exchangelib.Account(primary_smtp_address=username,
                                      credentials=credentials,
                                      config=config)
        total_number = str(account.calendar.total_count)
        tz = exchangelib.EWSTimeZone.localzone()
        right_now = tz.localize(exchangelib.EWSDateTime.now())

        start = right_now - datetime.timedelta(days=BEFORE)
        end = right_now + datetime.timedelta(days=FUTURE)

        allEvents = account.calendar.view(start=start, end=end)

        return allEvents
    except Exception as inst:
        print(inst)
        quit()
Beispiel #5
0
 def initData(self, email, username, password, trelloEmail):
     self.credentials = exchangelib.Credentials(username=username,
                                                password=password)
     self.account = exchangelib.Account(email,
                                        credentials=self.credentials,
                                        autodiscover=True)
     self.ticketingEmail = trelloEmail
     self.recentEmail = self.account.inbox.all().order_by(
         '-datetime_received')[0].id
Beispiel #6
0
def connect_to_exchange(server: str, domain: str, email: str, username: str) -> exchangelib.Account:
    """
    Get Exchange account connection with server
    """
    credentials = exchangelib.Credentials(username= f'{domain}\\{username}', 
                                          password=getpass.getpass("Exchange pass:"))
    config = exchangelib.Configuration(server=server, credentials=credentials)
    return exchangelib.Account(primary_smtp_address=email, autodiscover=False, 
                   config = config, access_type='delegate')
Beispiel #7
0
def main():
    boot_time = time.time()
    config = load_config()

    metrics.init(config, 'iris-owa-sync', default_metrics)

    owaconfig = config.get('owa')

    if not owaconfig:
        logger.critical('Missing OWA configs')
        sys.exit(1)

    api_host = owaconfig.get('api_host', 'http://localhost:16649')
    iris_client = IrisClient(api_host, 0, owaconfig['iris_app'],
                             owaconfig['iris_app_key'])

    proxies = owaconfig.get('proxies')

    # only way to configure a proxy is to monkey-patch (http adapter) a monkey-patch (baseprotocol) :/
    if proxies:
        UseProxyHttpAdapter._my_proxies = proxies
        exchangelib.protocol.BaseProtocol.HTTP_ADAPTER_CLS = UseProxyHttpAdapter

    creds = exchangelib.Credentials(**owaconfig['credentials'])

    try:
        nap_time = int(owaconfig.get('sleep_interval', 60))
    except ValueError:
        nap_time = 60

    while True:
        start_time = time.time()
        message_count = 0

        try:
            config = exchangelib.Configuration(credentials=creds,
                                               **owaconfig['config'])
            account = exchangelib.Account(config=config,
                                          access_type=exchangelib.DELEGATE,
                                          **owaconfig['account'])
        except (exchangelib.errors.EWSError,
                requests.exceptions.RequestException):
            logger.exception('Failed authenticating to OWA365')
            metrics.incr('owa_api_failure_count')
        else:
            logger.info('Receiving mail on behalf of %s',
                        owaconfig['account'].get('primary_smtp_address'))
            message_count = poll(account, iris_client)

        now = time.time()
        run_time = now - start_time
        logger.info(
            'Last run took %2.f seconds and processed %s messages. Waiting %s seconds until next poll..',
            run_time, message_count, nap_time)
        metrics.set('uptime', now - boot_time)
        metrics.emit()
        sleep(nap_time)
Beispiel #8
0
def exchange_test_connect(address, password):
    """Tests Exchange connection with supplied credentials"""
    logger.debug("Attempting Exchange login with user: %s" % (address))
    try:
        credentials = exchangelib.Credentials(address, password)
        account = exchangelib.Account(address,
                                      credentials=credentials,
                                      autodiscover=True)
        logger.debug("Connection successful")
        return True, "Connection successful"
    except Exception as e:
        logger.debug("Connection unsuccessful: %s" % str(e))
        return False, str(e)
def send_alert_email(public_ip, service_id, location, email_isp):
    email_body = "Buna ziua, \n Nu ne mai raspunde routerul cu IP-ul: " + public_ip + "\n ServiceID: " + service_id + "\n Locatie: " + location + "\n Ne puteti ajuta va rugam cu o verificare ? \n P.S.: Va rugam sa raspundeti cu toti colegii din CC.\n O zi buna, \n NOC Team \n"
    creds = E.Credentials(username=exchange_username, password=exchange_password)
    config = E.Configuration(server=exchange_server, credentials=creds)
    a = E.Account(primary_smtp_address=exchange_smtp_address, config=config, autodiscover=False, access_type=E.DELEGATE)
    m = E.Message(
        account=a,
        subject='Router Down',
        body=email_body,
        to_recipients=email_isp,
        cc_recipients=exchange_cc_recipients,  # Simple strings work, too
    )
    m.send_and_save()
Beispiel #10
0
 def __init__(self, username, password):
     if isinstance(username, bytes):
         username = username.decode()
     if isinstance(password, bytes):
         password = password.decode()
     self.credentials = ex.Credentials(username, password)
     self.config = ex.Configuration(server='outlook.office365.com',
                                    credentials=self.credentials)
     self.account = ex.Account(primary_smtp_address=username,
                               config=self.config,
                               autodiscover=False,
                               access_type=ex.DELEGATE)
     self._inbox_all = []
def check_email():
    creds = E.Credentials(username=exchange_username, password=exchange_password)
    config = E.Configuration(server=exchange_server, credentials=creds)
    account = E.Account(primary_smtp_address=exchange_smtp_address, config=config, autodiscover=False, access_type=E.DELEGATE)  # logging onto Exchange
    email_filtered = account.inbox.filter(subject__icontains="Devices up/down")
    re_ip = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")				
    if email_filtered.exists():  # if there are any e-mails for this filter
        for i in email_filtered:			# for each e-mail
            #print(i.body)
            ip = re.findall(re_ip,i.body)
            for j in ip:
                if not None:
                    email_filtered.delete()
                    return j
Beispiel #12
0
def send_zipped_file_exchange(zipped_file, recipients, sender, connect_params):
    for param in ['host', 'sender', 'user', 'pass']:
        assert param in connect_params, 'must specify mandatory parameter %s' % param

    credentials = exchangelib.ServiceAccount(
        username=connect_params['user'],
        password=connect_params['pass']
    )

    print("creds are:\n%s" % credentials)

    config = exchangelib.Configuration(
        server=connect_params['host'],
        credentials=credentials,
        # version=version,
        # auth_type=NTLM
    )

    print("config is:\n%s" % config)

    account = exchangelib.Account(
        primary_smtp_address=connect_params['sender'],
        credentials=credentials,
        autodiscover=False,
        config=config,
        access_type=exchangelib.DELEGATE
    )

    message = exchangelib.Message(
        account=account,
        subject='TEST: File %s' % zipped_file,
        body='',
        to_recipients=recipients
    )

    with open(zipped_file, 'w+') as zf:
        attachment = exchangelib.FileAttachment(name=zipped_file, content=zf.read())
        message.attach(attachment)

    message.send_and_save()
Beispiel #13
0
def connect_ews(config):
    domain = config.get('domain', None)
    username = config.get('username', None)
    email = config.get('email', None)
    if username is not None and domain is not None:
        username = f'{domain}\\{username}'
    else:
        username = f'{email}'
    password = config.get('password', None)
    if password is None:
        password = keyring.get_password('ewsorgsync', username)
    if password is None:
        logging.error(
            'Can\'t find password (neither in config nor in keychain)')
        sys.exit(-1)
    if domain is not None:
        username = f'{domain}\\{username}'
    else:
        username = f'{email}'
    cred = exlib.Credentials(username, password)
    endpoint = config.get('endpoint', None)
    server = config.get('server', None)
    if endpoint is not None and server is not None:
        logging.error(
            'The server and endpoint options are mutually exclusive!')
        sys.exit(-1)
    elif endpoint is None and server is None:
        logging.error('You must give either the server or endpoint option!')
        sys.exit(-1)
    conf = {'server': server, 'service_endpoint': endpoint}
    ewsconf = exlib.Configuration(credentials=cred, **conf)
    logging.debug('Connecting to endpoint')
    acc = exlib.Account(primary_smtp_address=config['email'],
                        config=ewsconf,
                        default_timezone=exlib.EWSTimeZone.localzone(),
                        access_type=exlib.DELEGATE)
    logging.debug('Refreshing folders')
    acc.root.refresh()
    return acc
Beispiel #14
0
def getEvents(VALUES):
    """get months events from exchange and write them to file"""
    url = VALUES['owa']
    #    print(url)
    username = VALUES['username']
    password = VALUES['password']
    BEFORE = VALUES['before']
    FUTURE = VALUES['future']

    try:
        credentials = exchangelib.Credentials(username=username,
                                              password=password)
        config = exchangelib.Configuration(server=url, credentials=credentials)
        account = exchangelib.Account(primary_smtp_address=username,
                                      credentials=credentials,
                                      config=config)

        tz = exchangelib.EWSTimeZone.localzone()
        right_now = tz.localize(exchangelib.EWSDateTime.now())

        start = right_now - datetime.timedelta(days=7)
        #        print(start)
        end = right_now + datetime.timedelta(days=7)
        #        print(end)

        allEvents = account.calendar.view(start=start, end=end)
        #        for item in allEvents:
        #            local_start = item.start.astimezone(tz=tz)
        #            local_end = item.end.astimezone(tz=tz)
        #            print("{} start={} end={}".format(item.subject, local_start, local_end))

        return allEvents
    except:
        print("username or password incorrect")
        print("remember username should be in form of ")
        print("-u <domain>\\\<username> or")
        print("in config file user=<domain>\\<username>")
        quit()
Beispiel #15
0
#!/usr/bin/env python3
import exchangelib
from string import Template
from os.path import basename
from modules import get_profile
import sys

email_config = get_profile.getProfile(items=['nhs'])

# set up connection to EWS
try:
    c = exchangelib.Credentials(email_config['user'], email_config['password'])
    a = exchangelib.Account('*****@*****.**',
                            credentials=c,
                            autodiscover=True)
except Exception as e:
    print(e)
    sys.exit(1)


def read_template(filename):
    """
    Returns a Template object comprising the contents of the 
    file specified by filename.
    """
    with open(filename, 'r', encoding='utf-8') as template_file:
        template_file_content = template_file.read()
    return Template(template_file_content)


def send_email(to,
# Created on 2018/2/

# from exchangelib import DELEGATE, Account, Credentials, Configuration, NTLM, Message, Mailbox, HTMLBody
# from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
import exchangelib
# 此句用来消除ssl证书错误,exchange使用自签证书需加上
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

# 输入你的域账号如example\leo
cred = exchangelib.Credentials(r'hywingroup\gjxx', 'hywin666')

config = exchangelib.Configuration(server='https://mail.hywingroup.com',
                                   credentials=cred,
                                   auth_type=exchangelib.NTLM)
a = exchangelib.Account(primary_smtp_address='*****@*****.**',
                        config=config,
                        autodiscover=False,
                        access_type=exchangelib.DELEGATE)

# 此处为用来发送html格式邮件的文件路径
# with open(r'D:\1.html') as f:
#     msg = f.read().decode('utf-8')

m = exchangelib.Message(
    account=a,
    folder=a.sent,
    subject=u'测试邮件',
    body='ceshiyoujian',
    to_recipients=[Mailbox(email_address='*****@*****.**')])
m.send_and_save()
            logging.error("parameter " + parameter + " is not defined.")
            sys.exit(1)

    if not config["ssl_verify"]:
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        exchangelib.BaseProtocol.HTTP_ADAPTER_CLS = exchangelib.NoVerifyHTTPAdapter

    exchange_credentials = exchangelib.Credentials(username=config["username"],
                                                   password=config["password"])

    exchange_config = exchangelib.Configuration(
        server=config["server"], credentials=exchange_credentials)

    exchange_account = exchangelib.Account(
        primary_smtp_address=config["primary_smtp_address"],
        config=exchange_config,
        autodiscover=False,
        access_type=exchangelib.DELEGATE)

    exchange_account.public_folders_root.refresh()
    public_folders_root = exchange_account.public_folders_root
    target_folder = get_folder(config["target_path"], public_folders_root)

    item = exchangelib.PostItem(account=exchange_account,
                                folder=target_folder,
                                subject=config["subject"])
    item.author = config["author"]
    item.save()

    logging.info("Success")
    sys.exit(0)
Beispiel #18
0
    def authenticate(self, request, username, password):
        """
        Check for the format of the username (``dom\\user`` vs ``user@dom``),
        then authenticate, and if successful, get or create the user object and
        return it.
        """
        username = username.lower()
        allowed_formats = get_setting('AUTH_EXCHANGE_ALLOWED_FORMATS')
        if '\\' in username:
            # assume dom\user
            if 'netbios' not in allowed_formats: return None
            netbios, user = username.rsplit('\\', 1)
            try:
                dom = get_setting(
                    'AUTH_EXCHANGE_NETBIOS_TO_DOMAIN_MAP')[netbios]
            except KeyError:
                dom = netbios
            smtp = '{0}@{1}'.format(user, dom)
            c_username = username
        elif '@' in username:
            # assume user@dom
            if 'email' not in allowed_formats: return None
            user, dom = username.rsplit('@', 1)
            smtp = username
            c_username = username
        else:
            # assume username only
            if 'username' not in allowed_formats: return None
            dom = get_setting('AUTH_EXCHANGE_DEFAULT_DOMAIN')
            user = username
            smtp = "{0}@{1}".format(user, dom)
            if not '.' in dom:
                c_username = "******".format(dom, user)
            else:
                c_username = "******".format(user, dom)

        # check if domain is allowed
        domains = get_setting('AUTH_EXCHANGE_DOMAIN_SERVERS')
        if dom not in domains: return None

        # authenticate against Exchange server
        domain_server = domains.get(dom, 'autodiscover') or 'autodiscover'
        cred = el.Credentials(username=c_username, password=password)
        if domain_server == 'autodiscover':
            acc_opts = {
                'primary_smtp_address': smtp,
                'credentials': cred,
                'autodiscover': True,
                'access_type': el.DELEGATE
            }
            try:
                acc = el.Account(**acc_opts)
            except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed):
                return None
        else:
            cfg_opts = {
                'credentials': cred,
                'server': domain_server,
            }
            try:
                cfg = el.Configuration(**cfg_opts)
            except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed):
                return None
            acc_opts = {
                'config': cfg,
                'primary_smtp_address': smtp,
                'credentials': cred,
                'autodiscover': False,
                'access_type': el.DELEGATE
            }
            try:
                acc = el.Account(**acc_opts)
            except (el.errors.UnauthorizedError, el.errors.AutoDiscoverFailed):
                return None
        if not acc: return None

        # auth successful, get or create local user
        try:
            u = user_model.objects.get(**{username_field: c_username})
        except user_model.DoesNotExist:
            if self.create_unknown_user:
                u = user_model.objects.create(**{username_field: c_username})
                if DomainOrganization:
                    DomainOrganization.associate_new_user(u, dom)
            else:
                return None

        # enforce domain user properties, if they exist, and save
        user_properties = get_setting(
            'AUTH_EXCHANGE_DOMAIN_USER_PROPERTIES').get(dom, {})
        if user_properties:
            for k, v in user_properties.items():
                setattr(u, k, v)
        if '.' in dom: setattr(u, u.get_email_field_name(), c_username)
        u.save()

        return u