Esempio n. 1
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')
Esempio n. 2
0
    def test_q(self):
        tz = EWSTimeZone.timezone('Europe/Copenhagen')
        start = tz.localize(EWSDateTime(1950, 9, 26, 8, 0, 0))
        end = tz.localize(EWSDateTime(2050, 9, 26, 11, 0, 0))
        result = '''\
<m:Restriction xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
    <t:And xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <t:Or>
            <t:Contains ContainmentMode="Substring" ContainmentComparison="Exact">
                <t:FieldURI FieldURI="item:Categories"/>
                <t:Constant Value="FOO"/>
            </t:Contains>
            <t:Contains ContainmentMode="Substring" ContainmentComparison="Exact">
                <t:FieldURI FieldURI="item:Categories"/>
                <t:Constant Value="BAR"/>
            </t:Contains>
        </t:Or>
        <t:IsGreaterThan>
            <t:FieldURI FieldURI="calendar:End"/>
            <t:FieldURIOrConstant>
                <t:Constant Value="1950-09-26T08:00:00+01:00"/>
            </t:FieldURIOrConstant>
        </t:IsGreaterThan>
        <t:IsLessThan>
            <t:FieldURI FieldURI="calendar:Start"/>
            <t:FieldURIOrConstant>
                <t:Constant Value="2050-09-26T11:00:00+01:00"/>
            </t:FieldURIOrConstant>
        </t:IsLessThan>
    </t:And>
</m:Restriction>'''
        q = Q(Q(categories__contains='FOO') | Q(categories__contains='BAR'),
              start__lt=end,
              end__gt=start)
        r = Restriction(q, folders=[Calendar()], applies_to=Restriction.ITEMS)
        self.assertEqual(str(r),
                         ''.join(l.lstrip() for l in result.split('\n')))
        # Test empty Q
        q = Q()
        self.assertEqual(
            q.to_xml(folders=[Calendar()],
                     version=None,
                     applies_to=Restriction.ITEMS), None)
        with self.assertRaises(ValueError):
            Restriction(q, folders=[Calendar()], applies_to=Restriction.ITEMS)
        # Test validation
        with self.assertRaises(ValueError):
            Q(datetime_created__range=(1, ))  # Must have exactly 2 args
        with self.assertRaises(ValueError):
            Q(datetime_created__range=(1, 2, 3))  # Must have exactly 2 args
        with self.assertRaises(TypeError):
            Q(datetime_created=Build(15, 1)).clean()  # Must be serializable
        with self.assertRaises(ValueError):
            Q(datetime_created=EWSDateTime(2017, 1,
                                           1)).clean()  # Must be tz-aware date
        with self.assertRaises(ValueError):
            Q(categories__contains=[[1, 2], [3, 4]
                                    ]).clean()  # Must be single value
Esempio n. 3
0
 def test_hardcode_all(self, m):
     # Test that we can hardcode everything without having a working server. This is useful if neither tasting or
     # guessing missing values works.
     Configuration(
         server='example.com',
         credentials=Credentials('foo', 'bar'),
         auth_type=NTLM,
         version=Version(build=Build(15, 1, 2, 3), api_version='foo'),
     )
Esempio n. 4
0
 def test_magic(self):
     config = Configuration(
         server='example.com',
         credentials=Credentials('foo', 'bar'),
         auth_type=NTLM,
         version=Version(build=Build(15, 1, 2, 3), api_version='foo'),
     )
     # Just test that these work
     str(config)
     repr(config)
Esempio n. 5
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}
Esempio n. 6
0
    def __init__(self, email: Email, config: EWSConfig):
        self._email = email
        self._config = config
        self._gcs_client = storage.Client()
        credentials = Credentials(config.email_account, config.password)
        version = Version(build=Build(config.exchange_version["major"],
                                      config.exchange_version["minor"]))
        ews_config = Configuration(
            service_endpoint=config.exchange_url,
            credentials=credentials,
            auth_type="basic",
            version=version,
            retry_policy=FaultTolerance(max_wait=300),
        )
        self._account = Account(
            primary_smtp_address=config.email_account,
            config=ews_config,
            autodiscover=False,
            access_type="delegate",
        )

        # Setup reply-mail client.

        recipient = ""
        if self._config.hardcoded_recipients:
            recipient = self._config.mail_to_mapping.get(self._email.recipient)
        else:
            recipient = self._config.mail_to_mapping.get("STANDARD")
        acc_credentials = Credentials(
            username=recipient["sender_account"],
            password=util.get_secret(os.environ["PROJECT_ID"],
                                     recipient["sender_account_secret"]),
        )
        acc_config = Configuration(
            service_endpoint=config.exchange_url,
            credentials=acc_credentials,
            auth_type="basic",
            version=version,
            retry_policy=FaultTolerance(max_wait=300),
        )
        self._reply_email_account = Account(
            primary_smtp_address=recipient["sender_account"],
            config=acc_config,
            autodiscover=False,
            access_type="delegate",
        )
# Loading secrets
with open(secrets_filename, "r") as secrets_file:
    secrets = json.load(secrets_file)

# Loading passwords
with open(passwords_filename, "r") as passwords_file:
    passwords = json.load(passwords_file)

# Loading email template
with open(email_filename, "r") as email_file:
    email_template = jinja2.Template(email_file.read())

logging.info("Loaded Secrets, Password and Email template file.")

# Setting up Exchange Creds
version = Version(build=Build(15, 0, 1395, 4000))
credentials = Credentials(username=secrets['proxy']['username'],
                          password=secrets["proxy"]["password"])
config = Configuration(server="webmail.capetown.gov.za",
                       credentials=credentials,
                       version=version,
                       auth_type=NTLM)
account = Account(primary_smtp_address="*****@*****.**",
                  config=config,
                  autodiscover=False,
                  access_type=DELEGATE)
logging.info("Authenticated with Exchange")

with open(logo_filename, 'rb') as fp:
    city_logo_attachment = FileAttachment(name='city_logo.png',
                                          content=fp.read())
        ["*****@*****.**", "*****@*****.**"],
        "cc_email":
        HR_CREW + ["*****@*****.**"]
    },
    "CITY MANAGER": {
        "receiver_name": ["Phindile", "Ashwin"],
        "receiver_email": [
            "*****@*****.**",
            "*****@*****.**"
        ],
        "cc_email":
        HR_CREW + ["*****@*****.**"]
    },
}

EXCHANGE_VERSION = Version(build=Build(15, 0, 1395, 4000))


def get_data_df(filename, minio_access, minio_secret):
    with tempfile.NamedTemporaryFile() as temp_data_file:
        logging.debug("Pulling data from Minio bucket...")
        result = minio_utils.minio_to_file(temp_data_file.name,
                                           BUCKET,
                                           minio_access,
                                           minio_secret,
                                           CLASSIFICATION,
                                           minio_filename_override=filename)
        assert result

        logging.debug(f"Reading in raw data from '{temp_data_file.name}'...")
        data_df = pandas.read_csv(temp_data_file)
Esempio n. 9
0
from exchangelib import DELEGATE, Account, Credentials, Configuration, NTLM, Build, Version, Attendee

credentials = Credentials(username='******',
                          password='******')

version = Version(build=Build(14, 3, 123, 4))
config = Configuration(server='mail.snellemantom.com.au',
                       credentials=credentials,
                       version=version,
                       auth_type=NTLM)

my_account = Account(primary_smtp_address='*****@*****.**',
                     credentials=credentials,
                     config=config,
                     access_type=DELEGATE)

for item in my_account.calendar.all().order_by('-datetime_received')[:100]:
    try:
        if '@snellemantom.com.au' not in item.required_attendees \
                or 'boardroom' in item.required_attendees \
                or 'meetingroom' in item.required_attendees:
            attendees = []
            Subject = str(item.subject)
            Start = str(item.start)
            End = str(item.end)
            Location = str(item.location)
            for x in item.required_attendees:
                attendees.append(
                    str(x.mailbox.name).replace(" | Snelleman Tom",
                                                "").replace("'", ""))
            print(Subject + " - " + Location + " - " + Start + " to " + End +