Esempio n. 1
0
def sendmail_win_hb(email, days):
    # target_filename = filename + '*.csv'
    # newest = max(glob.iglob(target_filename), key=os.path.getctime)
    # print('newest file: ' + newest)
    # today_date = datetime.datetime.now().strftime('%y%m%d')
    # try:
    # 	newest_date = re.search( filename + '(\d+)', newest).group(1)
    # except AttributeError:
    # 	newest_date = ''
    # print('newest date: ' + newest_date)
    # if newest_date != today_date:
    # 	print('Error: newest date != today date.. mannual intervention needed..')
    # 	return

    try:
        sendmail_secret = None
        # with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'secrets.json')) as data_file:
        # with open(os.path.join(os.path.dirname('C:\\Users\\809452\\gta_swarm'), 'secrets.json')) as data_file:
        with open(os.path.join('C:\\Users\\809452\\gta_swarm',
                               'secrets.json')) as data_file:
            sendmail_secret = (json.load(data_file))['sendmail_win']
    except FileNotFoundError:
        print('Secret file not found..')
        return

    print('Setting account..')
    # Username in WINDOMAIN\username format. Office365 wants usernames in PrimarySMTPAddress
    # ('*****@*****.**') format. UPN format is also supported.
    credentials = Credentials(username='******',
                              password=sendmail_secret['password'])

    print('Discovering..')

    # If the server doesn't support autodiscover, use a Configuration object to set the server
    # location:
    config = Configuration(server='emailuk.kuoni.com', credentials=credentials)

    try:
        account = Account(primary_smtp_address=email,
                          config=config,
                          autodiscover=False,
                          access_type=DELEGATE)
    except ConnectionError as e:
        print('Fatal: Connection Error.. aborted..')
        return

    print('Logged in as: ' + str(email))

    to_date = datetime.datetime.now() + datetime.timedelta(days=1)
    # from_date = to_date + datetime.timedelta(days=days)
    from_date = datetime.datetime.now() + datetime.timedelta(days=days)

    # tz = EWSTimeZone.timezone('Europe/Copenhagen')
    # tz = EWSTimeZone.timezone('Europe/London')
    tz = EWSTimeZone.timezone('Asia/Shanghai')
    # tz = EWSTimeZone.localzone()

    print('Filtering from ' + str(from_date))
    print('Filtering to ' + str(to_date))

    items_for_days = account.inbox.filter(datetime_received__range=(
        # tz.localize(EWSDateTime(2017, 1, 1)),
        tz.localize(EWSDateTime(from_date.year, from_date.month,
                                from_date.day)),
        # tz.localize(EWSDateTime(2018, 1, 1))
        tz.localize(EWSDateTime(to_date.year, to_date.month, to_date.day))
        # )).filter(sender='*****@*****.**')  # Filter by a date range
        # )).filter(author='*****@*****.**')  # Filter by a date range
    ))  # Filter by a date range
    # )).filter(sender='*****@*****.**')

    if not items_for_days:
        print('items_for_days is none..')

    print('Items count: ' + str(items_for_days.count()))

    for item in items_for_days:
        # print('? Email subject: ' + item.subject)
        # print('?? Email sender: ' + str(item.sender))
        # print('??? Email date time: ' + str(item.datetime_received))
        for attachment in item.attachments:
            if isinstance(attachment, FileAttachment):
                print('- Email subject: ' + item.subject)
                print('-- Email sender: ' + str(item.sender))
                print('--- Email date time: ' + str(item.datetime_received))
                # local_path = os.path.join('/tmp', attachment.name)
                # local_path = os.path.join('', attachment.name)
                # CTRIP---API-Errors---API-valuation-step-issues--h-_v205111_s2608_2018-07-01-00-00
                if 'CTRIP---API-Errors---API-valuation-step-issues' not in attachment.name:
                    print('Warning: attachment not API report.. ')
                    continue
                local_path = os.path.join(
                    os.path.dirname(os.path.abspath(__file__)),
                    attachment.name)
                with open(local_path, 'wb') as f:
                    try:
                        f.write(attachment.content)
                    except ErrorItemNotFound:
                        print('Error: item not found.. ')
                        continue
                print('----> Saved attachment to', local_path)
                # Test break..
                return
Esempio n. 2
0
def get_attachments(email_address=None, password=None, email_folder=None, output_folder=None, file_types=''):

    if not isinstance(email_folder, list):
        email_folder = [email_folder]

    creds = Credentials(
        username='******' + email_address,
        password=password
    )

    config = Configuration(server='imap-mail.outlook.com', credentials=creds)

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

    tz = EWSTimeZone.timezone('America/New_York')

    today = datetime.today()
    tomorrow = today + timedelta(days=1)

    starttime = tz.localize(EWSDateTime(today.year, today.month, today.day, 0, 0, 0))

    endtime = tz.localize(EWSDateTime(tomorrow.year, tomorrow.month, tomorrow.day, 0, 0, 0))

    check_folder(output_folder)

    folder = account.root / 'Top of Information Store'

    for l in email_folder:
        folder = folder / l

    # Save attachments to specified folder
    for email in folder.all().order_by('-datetime_received').filter(datetime_received__range=(starttime, endtime)):

        print('  {0}'.format(email.datetime_received.astimezone(tz)))
        print('  {0}'.format(email.subject))

        if len(email.attachments) < 1:
            continue

        company_name = get_company_name(email.sender.email_address)

        for attachment in email.attachments:
            if isinstance(attachment, FileAttachment):

                print('    {0}'.format(attachment.name), end='')

                flag = True
                for f in file_types:
                    if attachment.name.endswith(f):
                        flag = False
                        break

                if flag:
                    print('  |  ignoring file')
                    continue

                print('  |  saving file')
                local_path = os.path.join(output_folder, '_'.join([company_name, attachment.name]))

                with open(local_path, 'wb') as f:
                    f.write(attachment.content)

            elif isinstance(attachment, ItemAttachment):
                if isinstance(attachment.item, Message):
                    print(attachment.item.subject, attachment.item.body)
Esempio n. 3
0
 def test_type(self):
     self.assertEqual(Credentials('a', 'b').type, Credentials.UPN)
     self.assertEqual(
         Credentials('*****@*****.**', 'b').type, Credentials.EMAIL)
     self.assertEqual(Credentials('a\\n', 'b').type, Credentials.DOMAIN)
Esempio n. 4
0
import six
import os
import requests
import json
import pytz
from tzlocal import get_localzone
from flask import Flask, send_from_directory
from exchangelib import Credentials, Account, Configuration, DELEGATE, RoomList, CalendarItem, EWSDateTime
from exchangelib.services import GetRooms
from exchangelib.items import MeetingRequest, MeetingCancellation, SEND_TO_ALL_AND_SAVE_COPY

from swagger_server.models.inline_response200 import InlineResponse200  # noqa: E501
from swagger_server import util, orm, weapp

credentials = Credentials(
    os.environ["EWS_admin_email"],
    os.environ["EWS_admin_password"])

config = Configuration(server='outlook.office365.com', credentials=credentials)

account = Account(
    primary_smtp_address='*****@*****.**',
    credentials=credentials,
    autodiscover=False,
    config=config,
    access_type=DELEGATE
)
tzinfo = pytz.timezone('Asia/Shanghai')


def miniprogram_announcement_post(announcementPostBody):
Esempio n. 5
0
 def __init__(self):
     email = os.environ['OUTLOOK_EMAIL']
     password = os.environ['OUTLOOK_PASSWORD']
     credentials = Credentials(email, password)
     self.account = Account(email, credentials=credentials, autodiscover=True)
    Account,
    Credentials,
    EWSDateTime,
    EWSTimeZone,
    Configuration,
    CalendarItem
)
from exchangelib.items import SEND_TO_ALL_AND_SAVE_COPY
tz = EWSTimeZone.timezone('Europe/Stockholm')

EMAIL_HOST="smtp.office365.com"
EMAIL_HOST_USER="******"
EMAIL_HOST_PASSWORD="******"


credentials = Credentials(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
config = Configuration(server='outlook.office365.com', credentials=credentials)
account = Account(primary_smtp_address=EMAIL_HOST_USER, config=config, autodiscover=False, access_type=DELEGATE)

# create a meeting request and send it out
calendar_item = CalendarItem(
    account=account,
    folder=account.calendar,
    start=tz.localize(EWSDateTime(2018, 8, 22, 13, 30)),
    end=tz.localize(EWSDateTime(2018, 8, 22, 14, 30)),
    subject="Greetings from the rating platform",
    body="Please come to my meeting, it will be supergöy!",
    required_attendees=['*****@*****.**',
                        '*****@*****.**']
)
calendar_item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY)
Esempio n. 7
0
#######################################

from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \
    EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \
    Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \
    HTMLBody, Build, Version
import keyring
import json

credentials = json.load(open('calendarid.json'))

USERNAME = credentials["exchange"][0]["email"]
# "ExchangeCalShopDirect" is the name saved in keyring
PASSWORD = keyring.get_password("ExchangeCalShopDirect", USERNAME)

credentials = Credentials(username=USERNAME, password=PASSWORD)

my_account = Account(primary_smtp_address=USERNAME,
                     credentials=credentials,
                     autodiscover=True,
                     access_type=DELEGATE)

# Build a list of calendar items
tz = EWSTimeZone.timezone('Europe/London')

items_for_2018 = my_account.calendar.filter(start__range=(tz.localize(
    EWSDateTime(2018, 1,
                5)), tz.localize(EWSDateTime(2018, 1,
                                             10))))  # Filter by a date range

for item in items_for_2018:
Esempio n. 8
0
 def __init__(self):
     self.credentials = Credentials(_config.username, _config.password)
     self.account = None
     self.target_folder = 'AWSCodeCommitNotifications'
Esempio n. 9
0
from exchangelib import Credentials, Account, Message, Mailbox
from exchangelib import DELEGATE, Configuration
# from exchangelib.items import SEND_ONLY_TO_ALL, SEND_ONLY_TO_CHANGED
import os

# getting the sensitive information from enviornment variables
# stored in the .bash_profile
outlook_user = os.environ.get('OUTLOOK_USER')
outlook_password = os.environ.get('OUTLOOK_PASS')
outlook_server = os.environ.get('OUTLOOK_SERVER')
outlook_email = os.environ.get('OUTLOOK_EMAIL')

# Using the necessary credential and configuration to connect to
# the exchange server
credentials = Credentials(username=outlook_user, password=outlook_password)
config = Configuration(server=outlook_server, credentials=credentials)
account = Account(primary_smtp_address=outlook_email,
                  config=config,
                  autodiscover=False,
                  access_type=DELEGATE)

# for item in account.inbox.all().order_by('-datetime_received')[:10]:
#    print(item.subject, item.sender, item.datetime_received)

# Sending simple text mail to to, cc & bcc list
msg = Message(
    account=account,
    subject='another test mail',
    body='this is an another random body for testing mail services',
    to_recipients=[
        # Mailbox(email_address='*****@*****.**')
Esempio n. 10
0
from exchangelib import DELEGATE, Account, Credentials, Configuration, FileAttachment, ItemAttachment, Message, CalendarItem, HTMLBody, Mailbox, FaultTolerance
from pathlib import Path
from datetime import timedelta
from exchangelib import UTC_NOW
import time
import stdiomask

try:
    ad_password = stdiomask.getpass(prompt='Enter Active Directory Password: '******'*')
except Exception as error:
    print('ERROR', error)

#credentials are the domain name with username and password
creds = Credentials(username='******', password=ad_password)
#account configuration
config = Configuration(server='HSCLink.health.unm.edu',
                       credentials=creds,
                       retry_policy=FaultTolerance(max_wait=3600))
#create the instance of account class object
a = Account('*****@*****.**', credentials=creds, autodiscover=True)
#define and create the auto_rules folder
auto_folder = a.root / 'Top of Information Store' / 'auto_rules'

##list of file name text keywords in attachments to save
#attachment_to_save = ['#8940', 'random_rule_check']

#generate a time difference variable for the recency of hours that messages have arrived
#since = UTC_NOW() - timedelta(hours=4)
Esempio n. 11
0
import os, sys, re, logging, base64, requests, ldap
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import xml.etree.ElementTree as xml

# uncomment this line below to turn on debug logs
#logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.basicConfig(stream=sys.stderr, level=logging.CRITICAL)

ad_sys_user = '******'
ad_sys_password = base64.b64decode('your base 64 pass')

config = Configuration(
    server='X.X.X.X',  #to be changed with AD IP
    credentials=Credentials(username='******', password='******'),
    auth_type=NTLM,
    verify_ssl=False)


def disable_ad_account(domain_name, username, password, base_dn, lp_username):
    # Disable Active Directory User Account

    # Args:
    # 	domain_name (str)	: AD domain name :ex mydomain.com
    # 	username (str)		: admin account used for AD authentication
    # 	password (str)		: password for the admin account
    # 	base_dn (str)		: AD base DN (exp: DC=domain,DC=com)
    # 	lp_username (str)	: The AD username to be disabled (aka. compromised ID)

    # Returns:
Esempio n. 12
0
    def alert(self, matches):
        """
        Some of the code is a copy-and-paste from EmailAlerter.
        If anything changes in EmailAlerter ensure this method is updated accordingly.
        """
        body = self.create_alert_body(matches)

        # START copy-and-paste from EmailAlerter
        # Add JIRA ticket if it exists
        if self.pipeline is not None and 'jira_ticket' in self.pipeline:
            url = '%s/browse/%s' % (self.pipeline['jira_server'],
                                    self.pipeline['jira_ticket'])
            body += '\nJIRA ticket: %s' % (url)

        to_addr = self.rule['email']
        if 'email_from_field' in self.rule:
            recipient = lookup_es_key(matches[0],
                                      self.rule['email_from_field'])
            if isinstance(recipient, basestring):
                if '@' in recipient:
                    to_addr = [recipient]
                elif 'email_add_domain' in self.rule:
                    to_addr = [recipient + self.rule['email_add_domain']]

        # END copy-and-paste from EmailAlerter

        try:
            # setup exchangelib objects
            credentials = Credentials(username=self.user,
                                      password=self.password)

            if self.exchange_host or self.exchange_service_endpoint:
                config = Configuration(
                    server=self.exchange_host,
                    service_endpoint=self.exchange_service_endpoint,
                    auth_type=self.exchange_auth_type,
                    credentials=credentials)
                account = Account(primary_smtp_address=self.from_addr,
                                  config=config,
                                  autodiscover=False,
                                  access_type=DELEGATE)
            else:
                account = Account(primary_smtp_address=self.from_addr,
                                  credentials=credentials,
                                  autodiscover=True,
                                  access_type=DELEGATE)

            email_subject = self.create_title(matches)
            email_msg = body.encode('UTF-8')

            reply_to = self.rule.get('email_reply_to', self.from_addr)

            to_recipients = [Mailbox(email_address=i) for i in to_addr]
            cc_recipients = None
            bcc_recipients = None
            if self.rule.get('cc'):
                cc_recipients = [
                    Mailbox(email_address=i) for i in self.rule['cc']
                ]

            if self.rule.get('bcc'):
                bcc_recipients = [
                    Mailbox(email_address=i) for i in self.rule['bcc']
                ]

            msg = Message(
                account=account,
                folder=account.sent,
                subject=email_subject,
                body=email_msg,
                to_recipients=to_recipients,
                cc_recipients=cc_recipients,
                bcc_recipients=bcc_recipients,
            )

            # send the message
            msg.send_and_save()
        except Exception as e:
            raise EAException("Error connecting to Exchange host: %s" % (e))

        elastalert_logger.info("Sent email to %s" % (to_addr))
from azure.servicebus import ServiceBusService, Message, Queue
from bson.json_util import dumps
import hashlib 
import urllib


def getContact(mailbox):
    return {'name':mailbox.name, 'email':mailbox.email_address}

def getContacts(mailboxes):

    return [getContact(i) for i in mailboxes]


try:
    credentials = Credentials(username='******', password='')
    account = Account(primary_smtp_address='@.com', credentials=credentials,autodiscover=True, access_type=DELEGATE)
    print ('Connected to email server')
    client = pymongo.MongoClient('mongodb://*****:*****@serivice-desk-store.documents.azure.com:10255/?ssl=true&replicaSet=globaldb')
    db = client.hilton
    collection  = db.emails
    print ('Connected to cosmosdb/mongodb')
    nttBus = ServiceBusService(service_namespace='ntt-bus',shared_access_key_name='RootManageSharedAccessKey',shared_access_key_value='ak9L18tmI2FssJBIZLz3OCs8U55rcYZaSbwgAR6/B34=')
    print ('Conected to nttbus')
except Exception as e:
    print ('Error Connecting to external service' +str(e))
    sys.exit(1)

n=1
unread  = account.inbox.filter(is_read=False).only('sender','to_recipients','cc_recipients','subject','datetime_received','text_body','body','conversation_id','message_id','body').order_by('-datetime_received')[:n]
emails = [i for i in unread]
Esempio n. 14
0
excelName = 'weekly report-胡佳(2021).xlsx'
mailName = '51job.com\\fox.hu'
mailPassword = '******'
mailAddress = '*****@*****.**'
to = '*****@*****.**'
cc = '*****@*****.**'

# 看能不能把这两个参数去掉 起始行号 末尾行号
startRow = 3
endRow = 5

urllib3.disable_warnings()  # 取消SSL安全连接警告
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

cred = Credentials(mailName, mailPassword)  # 用户名不需要填写后缀
config = Configuration(
    server='mail.51job.com',  # 例如:mail.****.com
    credentials=cred,
    auth_type=NTLM)
account = Account(
    primary_smtp_address=mailAddress,  # 例如:[email protected]
    config=config,
    autodiscover=False,
    access_type=DELEGATE)


# 看能不能把参数去掉
def getExcelData():
    wb = openpyxl.load_workbook(excelName)
    sheet = wb[('Sheet1')]
    SMTP_SERVER = os.getenv('SMTP_SERVER')
    RECEIVER_EMAIL = os.getenv('RECEIVER_EMAIL')
    SENDER_EMAIL = os.getenv('SENDER_EMAIL')
    SENDER_PASSWORD = os.getenv('SENDER_PASSWORD')

    ODBC_SOURCE = os.getenv('ODBC_SOURCE')
    ODBC_UID = os.getenv('ODBC_UID')
    ODBC_PWD = os.getenv('ODBC_PWD')

    conn_str = 'DSN={};UID={};PWD={}'.format(ODBC_SOURCE, ODBC_UID, ODBC_PWD)

    conn = pyodbc.connect(conn_str)
    cursor = conn.cursor()

    creds = Credentials(username=ACCOUNT, password=PASSWORD)

    config = Configuration(server='outlook.office365.com', credentials=creds)

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

    root_folder = account.root
    dachser = root_folder.glob('**/0000 Voorraadlijst - Dachser')

    exit_code = 0
    exit_msg = ''
    try:
        init()
Esempio n. 16
0
try:
    with open(os.path.join(os.path.dirname(__file__), 'settings.yml')) as f:
        settings = load(f)
except FileNotFoundError:
    print(
        'Copy settings.yml.sample to settings.yml and enter values for your test server'
    )
    raise

categories = ['perftest']
tz = EWSTimeZone.timezone('US/Pacific')

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

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


# Calendar item generator
def calitems():
    i = 0
    start = tz.localize(EWSDateTime(2000, 3, 1, 8, 30, 0))
    end = tz.localize(EWSDateTime(2000, 3, 1, 9, 15, 0))
Esempio n. 17
0
#!/usr/bin/python
import os
import random
import shutil
from exchangelib import Credentials, Account

print('Connecting...')
credentials = Credentials('域\邮箱名','密码')
acount = Account('邮箱名@邮箱地址',credentials=credentials, autodiscover=True)
print('Login successfully.')

# 自定义黑名单,邮件主题包含下面的字符串
blackList = ['[JIRA]','[Service Desk Notification]']
for item in acount.inbox.all():
    subject = item.subject
    for blackName in blackList:
        if blackName in subject:
            print(subject)
            item.soft_delete()

print('Jobs done.')
    def sendMail(self,
                 recipients,
                 subject,
                 content,
                 isHtml,
                 attatchment,
                 successNum,
                 faileNum,
                 errorNum,
                 importance='Normal'):
        """
        发送邮件
        :param recipients:  收件人列表
        :param subject: 邮件标题
        :param attatchment: 附件
        :param importance: 重要级别,默认中等
        :return:
        """
        config = Configuration(server=self.mailserver,
                               credentials=Credentials(
                                   username=self.sendername,
                                   password=self.password),
                               auth_type=NTLM)

        account = Account(primary_smtp_address=self.sendermail,
                          config=config,
                          access_type=DELEGATE,
                          locale="CN")

        if isHtml:
            try:
                content = HTMLBody(content)
            except:
                content = "%s is not html content" % content
        mailto = []
        for recipient in recipients:
            mailto.append(Mailbox(email_address=recipient))

        choice = "Normal"
        if importance in ['High', 'high', 'HIGH', 'H', 'h']:
            choice = 'High'
        if importance in ['Low', 'low', 'LOW', 'L', 'l']:
            choice = 'Low'
        if importance in ['Normal', 'normal', 'NORMAl', 'N', 'n']:
            choice = 'Normal'

    #发送附件
        if os.path.isfile(attatchment):
            file_obj = open(attatchment, "r")
            try:
                attatchcontent = file_obj.read()
            finally:
                file_obj.close()
            binary_file_content = attatchcontent.encode('utf-8')
            attatchmentName = "接口运行详情报告.html"
            my_file = FileAttachment(name=attatchmentName,
                                     content=binary_file_content)
        else:
            binary_file_content = "<p>报告获取失败</p>"
            my_file = ""
        allcasenum = successNum + faileNum + errorNum
        if my_file == "":
            body_content = '<html><body style="text-align:center"></h4>' \
                           '<table border="1" style="width:700px;text-align:center">' \
                           '<caption>接口运行情况</caption><tr><th>总用例数</th><th>通过用例总数</th><th>失败用例总数</th><th>错误用例总数</th>' \
                           '</tr><tr><td>%d</td><td style="color:green">%d </td><td style="color:orange">%d </td><td style="color:red">%d </td>' \
                           '</tr></table></body></html>'%(allcasenum,successNum,faileNum,errorNum)
        else:
            body_content = '<html><body style="text-align:center"></h4>' \
                           '<table border="1" style="width:700px;text-align:center">' \
                           '<caption>接口运行情况</caption><tr><th>总用例数</th><th>通过用例总数</th><th>失败用例总数</th><th>错误用例总数</th>' \
                           '</tr><tr><td>%d</td><td style="color:green">%d </td><td style="color:orange">%d </td><td style="color:red">%d </td>' \
                           '</tr></table><p>接口详情信息请下载附件查看</p></body></html>' % (allcasenum, successNum, faileNum, errorNum)

        item = Message(account=account,
                       subject=subject,
                       body=HTMLBody(body_content),
                       to_recipients=mailto,
                       importance=choice)
        if my_file != "":
            item.attach(my_file)
        item.send()
Esempio n. 19
0
import requests
import re
import pandas as pd
import matplotlib.pyplot as plt

import os
import time

import cartopy.crs as ccrs
import cartopy.crs as ccrs  #    I know this is imported twice but it avoids errors for some reason when imported the second time

#   External install/import (pip install exchangelib)
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody, FileAttachment

#   Assign credentials for email account. Include '@uvic.ca' in username and smtp address
creds = Credentials(username='******',
                    password='******')
a = Account(primary_smtp_address='[YourFullUVIcEmail]',
            credentials=creds,
            autodiscover=True,
            access_type=DELEGATE)

onc = ONC("[YourONCToken]")
"""
EmailChecker

Function for performing the comparison between old/new emails.
    Arguments:
        folder - The folder location for either the "DMAS Alerts - Archive" or
                 the "DMAS Alerts - Monitor" folder where comparison will be
                 performed.
                 
Esempio n. 20
0
from exchangelib import Credentials, Account, Configuration, DELEGATE

mail_queue_list = []

credentials = Credentials(username='******',
                          password='******')
config = Configuration(server='outlook.office365.com', credentials=credentials)
account = Account(primary_smtp_address='*****@*****.**',
                  autodiscover=False,
                  config=config,
                  access_type=DELEGATE)

# filter to search subject/body or a word contained
# https://github.com/ecederstrand/exchangelib/issues/83
unread_list = account.inbox.filter(is_read=False and "subject in 'BNAUTO:'")

if unread_list.count() > 0:
    for mail in unread_list:
        mail_queue_list.append({mail.subject: mail.body})
        #To mark a email as read
        mail.is_read = True
        mail.save()

print(mail_queue_list)
#soup.select('td div table tbody tr td div')[1].text
#soup.select('p strong')[0].text
#m=soup.select('div div table tbody td div')[5]
#m.find('strong',text='Assigned To: ').next_sibling
Esempio n. 21
0
from exchangelib import Credentials, Account

credentials = Credentials('*****@*****.**', 'Li@m1026!')
account = Account('*****@*****.**', credentials=credentials, autodiscover=True)

for f in account.root.walk():
    if f.name == 'Where_is_Mike':
        my_folder = f
        break
else:
    raise Exception('Folder not found')

for item in my_folder.all().order_by('-datetime_received')[:5]: print(item.subject)
Esempio n. 22
0
from exchangelib import Account, credentials, FileAttachment, Credentials

#域名\\邮箱姓名
credentials = Credentials(username='******', password='******')

account = Account('*****@*****.**', credentials=credentials, autodiscover=True)
print('1.Connected to B exchangw~~')

print(account.inbox.children)
for item in account.inbox.children:
    print('Running the FOR now~')
    print('2.文件夹名称:'+item.name)
    if item.name=='XRAY':#只要XRAY文件夹下的附件
        index=0
        totalcount=0
        page=0
        while True:
            for model in item.all()[page:page+50]:
                index=index+1
                print(str(index)+'-开始:'+model.subject)
                for attachment in model.attachments:
                    if isinstance(attachment, FileAttachment):
                        with open('D:\\Cache\\cache\\' + attachment.name, 'wb') as f:
                            f.write(attachment.content)
            if totalcount==index:
                break
            page=page+50
            totalcount=index
Esempio n. 23
0
    def _execute(self, *args, **kwargs):

        if not self.password:
            logging.error(
                f"no password given for {self.section}. authentication will not be attempted."
            )
            return

        if not self.delete_emails:
            if not os.path.exists(self.tracking_db_path):
                with sqlite3.connect(self.tracking_db_path) as db:
                    c = db.cursor()
                    c.execute("""
CREATE TABLE IF NOT EXISTS ews_tracking (
    exchange_id TEXT NOT NULL,
    message_id TEXT NOT NULL,
    insert_date INT NOT NULL )""")
                    c.execute("""
CREATE INDEX IF NOT EXISTS idx_exchange_id ON ews_tracking(exchange_id)""")
                    c.execute("""
CREATE INDEX IF NOT EXISTS idx_insert_date ON ews_tracking(insert_date)""")
                    db.commit()

        # get the next emails from this account
        credentials = Credentials(self.username, self.password)
        config = Configuration(
            server=self.server, credentials=credentials,
            auth_type=NTLM)  # TODO auth_type should be configurable

        _account_class = kwargs.get(
            'account_class') or Account  # Account class connects to exchange.
        account = _account_class(
            self.target_mailbox,
            config=config,
            autodiscover=False,
            access_type=DELEGATE
        )  # TODO autodiscover, access_type should be configurable

        for folder in self.folders:
            path_parts = [_.strip() for _ in folder.split('/')]
            root = path_parts.pop(0)

            _account = kwargs.get('account_object') or account

            try:
                target_folder = getattr(_account, root)
            except AttributeError:
                public_folders_root = _account.public_folders_root
                target_folder = public_folders_root / root
            #print(target_folder.tree())

            for path_part in path_parts:
                target_folder = target_folder / path_part

            target_folder.refresh()

            logging.info(
                f"checking for emails in {self.target_mailbox} target {folder}"
            )
            total_count = 0
            already_processed_count = 0
            error_count = 0
            for message in target_folder.all().order_by('-datetime_received'):
                if isinstance(message, ResponseMessageError):
                    logging.warning(
                        f"error when iterating mailbox {self.target_mailbox} folder {folder}: {message} ({type(message)})"
                    )
                    continue

                # XXX not sure why this is happening?
                if message.id is None:
                    continue

                total_count += 1

                try:
                    # if we're not deleting emails then we need to make sure we keep track of which ones we've already processed
                    if not self.delete_emails:
                        with sqlite3.connect(self.tracking_db_path) as db:
                            c = db.cursor()
                            c.execute(
                                "SELECT message_id FROM ews_tracking WHERE exchange_id = ?",
                                (message.id, ))
                            result = c.fetchone()
                            if result is not None:
                                #logging.debug("already processed exchange message {} message id {} from {}@{}".format(
                                #message.id, message.message_id, self.target_mailbox, self.server))
                                already_processed_count += 1
                                continue

                    # otherwise process the email message (subclasses deal with the site logic)
                    self.email_received(message)

                except Exception as e:
                    logging.error(f"unable to process email: {e}")
                    report_exception()
                    error_count += 1

                if self.delete_emails:
                    try:
                        logging.debug(f"deleting message {message.id}")
                        message.delete()
                    except Exception as e:
                        logging.error(f"unable to delete message: {e}")
                else:
                    # if we're not deleting the emails then we track which ones we've already processed

                    with sqlite3.connect(self.tracking_db_path) as db:
                        c = db.cursor()
                        c.execute(
                            """
INSERT INTO ews_tracking (
    exchange_id,
    message_id,
    insert_date ) VALUES ( ?, ?, ? )""", (message.id, message.message_id,
                                          local_time().timestamp()))
                        # TODO delete anything older than X days
                        db.commit()

            logging.info(
                f"finished checking for emails in {self.target_mailbox} target {folder}"
                f" total {total_count} already_processed {already_processed_count} error {error_count}"
            )
Esempio n. 24
0
    MyButton.config(font=("serif", 30), bg="green")

    top.update()

    w = top.winfo_width()  # width for the Tk root
    h = top.winfo_height()  # height for the Tk root

    ws = top.winfo_screenwidth()  # width of the screen
    hs = top.winfo_screenheight()  # height of the screen
    x = (ws / 2) - (w / 2)
    y = (hs / 2) - (h / 2)

    top.geometry('%dx%d+%d+%d' % (w, h, x, y))
    top.update()
    credentials = Credentials(
        username='******',  # Or [email protected] for O365
        password='******')
    account = Account(primary_smtp_address='*****@*****.**',
                      credentials=credentials,
                      autodiscover=True,
                      access_type=DELEGATE)

    yardAccount = Account(primary_smtp_address='*****@*****.**',
                          credentials=credentials,
                          autodiscover=True,
                          access_type=DELEGATE)
    done = []
    tz = EWSTimeZone.localzone()
    Message.register('flag', Flag)

    top.after(0, doStuff, credentials, yardAccount, account, done)
Esempio n. 25
0
from datetime import datetime
import pyodbc
from exchangelib import Account, Credentials, Configuration, DELEGATE

# This is instantiated outside of the methods to prevent attempted double-connections (which, IIRC, never succeed)
connection = pyodbc.connect(
    'DRIVER={ODBC Driver 17 for SQL Server};SERVER=ServerGoesHere;DATABASE=DBNameGoesHere;TrustedConnection=yes;'
)


class SentItemsError(Exception):
    def __init__(self, message):
        super().__init__(message)


cred = Credentials('USerGoesHere', 'PasswordGoesHere')
config = Configuration(server='ServerGoesHere', credentials=cred)
a = Account(primary_smtp_address='User@ServerGoesHere',
            autodiscover=False,
            config=config,
            access_type=DELEGATE)


def forwarder(email_subject, unique_id):
    a.root.refresh()
    print(email_subject)
    message = a.sent.get(subject=email_subject)
    message.forward(
        subject='Fwd: 10-Minute Reminder',
        body=
        'Hey [name of recipient can go here],\n\nThis is a 10-minute reminder for [whatever the reminders were meant for].',
Esempio n. 26
0
from exchangelib import Credentials, Account
from exchangelib import Message, Mailbox, Attendee
try:
    # credentials = Credentials('*****@*****.**', 'XXXXXXX')
    # account = Account('*****@*****.**', credentials=credentials, autodiscover=True)
    credentials = Credentials('*****@*****.**', 'XXXX')
    account = Account('*****@*****.**',
                      credentials=credentials,
                      autodiscover=True)
except:
    pass


def send_email(email_id):
    try:
        print("Sending Email")
        m = Message(
            account=account,
            subject='Not complying Mask Protocol',
            body=
            'This is an auto generated mail. Please do not reply\n\nYou have not follwed the mask protocol, you were found not wearing the mask.\nPlease ensure you wear the mask when entering the premises.',
            to_recipients=[Mailbox(email_address=email_id)])
        m.send()
    except:
        pass
    return "Done"
Esempio n. 27
0
 def test_equality(self):
     self.assertEqual(Credentials('a', 'b'), Credentials('a', 'b'))
     self.assertNotEqual(Credentials('a', 'b'), Credentials('a', 'a'))
     self.assertNotEqual(Credentials('a', 'b'), Credentials('b', 'b'))
Esempio n. 28
0
from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials

credentials = Credentials('*****@*****.**', 'Ms540436')
my_account = Account(primary_smtp_address='*****@*****.**',
                     credentials=credentials,
                     autodiscover=True,
                     access_type=DELEGATE)

my_account.ad_response
Esempio n. 29
0
notify = sh.Command('/usr/bin/notify-send')
zenity = sh.Command('/usr/bin/zenity')

# Get the local timezone
tz = EWSTimeZone.localzone()

sleep = int(
    sys.argv[1]
)  # 1st arg to this script is the number of seconds to look back in the inbox
now = UTC_NOW()
emails_since = now - timedelta(seconds=sleep)
cal_items_before = now + timedelta(
    seconds=sleep *
    4)  # Longer notice of upcoming appointments than new emails
username, _, password = netrc().authenticators('office365')
c = Credentials(username, password)
a = Account(primary_smtp_address=c.username,
            credentials=c,
            access_type=DELEGATE,
            autodiscover=True,
            verify_ssl=False)

for msg in a.calendar.view(start=now, end=cal_items_before)\
        .only('start', 'end', 'subject', 'location')\
        .order_by('start', 'end'):
    if msg.start < now:
        continue
    minutes_to_appointment = int((msg.start - now).total_seconds() / 60)
    subj = 'You have a meeting in %s minutes' % minutes_to_appointment
    body = '%s-%s: %s\n%s' % (msg.start.astimezone(tz).strftime('%H:%M'),
                              msg.end.astimezone(tz).strftime('%H:%M'),
Esempio n. 30
0
    HTMLBody, Build, Version

from urlparse import urlparse
import uuid

import requests
import sys
import json
import time
from thehive4py.api import TheHiveApi
from thehive4py.models import Alert, AlertArtifact

api = TheHiveApi('[thehiveurl]', '[thehiveuser]', '[thehivepassword]', {'http': '', 'https': ''})

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

config = Configuration(server='mail.example.com', credentials=creds)

account = Account(
    primary_smtp_address='[smtpaddress]',
    credentials=creds,
    autodiscover=False,
    config=config,
    access_type=DELEGATE)

to_be_processed_mail_folder = account.root.get_folder_by_name('to_be_processed')
processed_mail_folder = account.root.get_folder_by_name('processed')

num_emails_to_process = to_be_processed_mail_folder.total_count