Esempio n. 1
0
    def composeEmailToSender(self, sender, body, subject, users):
        msgTemplate = body

        sendToEmails = []
        for user in users:
            if user in sHandler.sysData.userData.keys():
                sendToEmails.append(
                    exchangelib.Mailbox(email_address=sHandler.sysData.
                                        userData[user]['email']))

        m = exchangelib.Message(account=self.account,
                                subject=subject,
                                body=exchangelib.HTMLBody(msgTemplate),
                                to_recipients=sendToEmails)

        logoName = "SAS_Logo.jpg"
        with open(logoName, 'rb') as f:
            logoimg = exchangelib.FileAttachment(name=logoName,
                                                 content=f.read())
            m.attach(logoimg)

        m.send()
        sHandler.sysLog.logger.info("Sent ticket confirmation to: " +
                                    sender.name + " (" + sender.email_address +
                                    ") " + str(users))
        print("\t[LOG] Sent ticket confirmation to: " + sender.name + " (" +
              sender.email_address + ") " + str(users) + "\n\n>",
              end='')
Esempio n. 2
0
def send_email(to,
               subject,
               body,
               cc_recipients=[],
               attachments=[],
               reply_to=[]):
    """
    Sends an email to a list of recipients
    to: list of email address of recipients
    email_from: email address to send from
    subject: subject line of email
    body: body text in html
    attachments: list of filepaths to attachments to include
    reply_to: email address to reply to
    """
    # create the message
    m = exchangelib.Message(account=a,
                            folder=a.sent,
                            subject=subject,
                            body=exchangelib.HTMLBody(body),
                            to_recipients=to,
                            cc_recipients=cc_recipients,
                            reply_to=reply_to)
    for f in attachments:
        # add in attachment
        with open(f, "rb") as fil:
            f_contents = fil.read()
        attach_file = exchangelib.FileAttachment(name=basename(f),
                                                 content=f_contents)
        m.attach(attach_file)
    # send the message via the server set up earlier.
    m.send_and_save()
Esempio n. 3
0
def submit_workbook(
    subject_line: str,
    recipient: Email,
    username_backup: Optional[str] = None,
    cc_me: bool = False
    ):
    """
    Emails the current notebook to 'recipient' with 'subject_line'.
    If 'cc_me' is True, then the email will also "CC" the current user.

    Uses the RJC Exchange mail server. Passwords are handled securely with
    the getpass library in the Python standard library.

    The current user is known through a query of the user's Jupyter username.
    Since the username is created from the user's RJC email prefix, once the
    username is known, the user's email address is known. This makes things
    convenient.

    'subject_line': a str representing the subject line to be used in the email
    'recipient': the primary recipient of the email, typically the Python course
        administrator.
    'cc_me': a bool indicating whether the current user should be "CC'd" on the
        email.
    'username_backup': If provided, this is used as an override for the current
        user's username. To be used when testing functionality from an account
        that is not linked to an RJC email (e.g. a JupyterHub admin account).
        Not useful in typical operation.
    """
    user_name = get_hub_user()
    if username_backup or not user_name:
        user_name = username_backup
    # if not user_name:
    #     raise EnvironmentError("submit_workbook() must be run from within a Jupyter Hub environment.")
    notebook_path = get_notebook_path()
    user_email = user_name.lower() + "@rjc.ca"
    
    account = connect_to_rjc_exchange(user_email, user_name)
    cc_user = []
    if cc_me:
        cc_user = [user_email]
    message = exchangelib.Message(
        account=account,
        folder=account.sent,
        subject=subject_line,
        body=f'{notebook_path.name} submission',
        to_recipients=[recipient],
        cc_recipients=cc_user,
    )
    with open(notebook_path) as nb_file:
        nb_data = nb_file.read().encode("utf-8")
    attachment = exchangelib.FileAttachment(name=notebook_path.name, content=nb_data)
    message.attach(attachment)
    message.send_and_save()
    print(f"{notebook_path.name} successfully submitted to {recipient}")
Esempio n. 4
0
    def send(self, to, subject, msg):
        '''send function

        Sends an email <to> <subject> <msg>'''
        account = self.login(self.smtp_host)
        email = exchangelib.Message(account=account,
                                    subject=subject,
                                    body=msg,
                                    to_recipients=[to])
        email.send()
        print('Email sent to:', to)
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()
Esempio n. 6
0
    def composeEndProgramEmail(self):
        endTime = datetime.datetime.now().strftime("%m/%d/%Y at %I:%M:%S %p")
        emailRecipients = [
            exchangelib.Mailbox(email_address="*****@*****.**"),
            exchangelib.Mailbox(email_address="*****@*****.**")
        ]
        emailBody = """POS.TicketingAutoForward Alert
	The script to send tickets to Trello has ended on {}.
	If this has ended prior to 11PM, please look into the logs or most recent emails to determine the cause of the application to end at this time.""".format(
            endTime)
        m = exchangelib.Message(account=self.account,
                                subject="POS.TAF ended {}".format(endTime),
                                body=emailBody,
                                to_recipients=emailRecipients)
        m.send()
Esempio n. 7
0
 def compose_message(self, sender, recipients,
                     subject, body, text_body=None):
     if body is None:
         body = ''
     body = body[:MAX_BODY_LEN]
     if text_body is None:
         text_body = ''
     message = exchangelib.Message(
         account=self.service,
         subject=subject,
         text_body=text_body[:MAX_BODY_LEN],
         body=exchangelib.HTMLBody(
             body[:MAX_BODY_LEN]
         ),
         to_recipients=recipients
     )
     return message
Esempio n. 8
0
    def __init__(self):
        # Get a logger
        log = logging.getLogger(__name__)

        # timestamps the message with current date and time
        time = self.convert_to_EWStime(datetime.now())

        # Create a namedtuple to simulate exchangelib Mailbox object
        FakeSender = namedtuple("FakeSender", ["email_address"])
        my_sender = FakeSender("*****@*****.**")

        self.m = exc.Message(subject="[AM] Test",
                             item_id="DEF568",
                             sender=my_sender,
                             body="Test message",
                             datetime_sent=time)
        log.info('Test message created')
        import os
        cwd = os.path.dirname(os.path.realpath(__file__))
        # filenames = os.listdir(cwd+u"/calcs")
        dummy = os.path.join(cwd, 'calcs', 'Dummy.txt')
        actual = os.path.join(cwd, 'calcs', 'test.xlsx')
        myfiles = [actual]
        for myfile in myfiles:
            try:
                # os.chdir("./calcs")
                log.info("Accessing: %s" % myfile)
                f = open(myfile, mode='rb')
                file_contents = f.read()
                # suffix = random.randint(0,99999)
                att = FileAttachment(name=myfile,
                                     content=file_contents,
                                     attachment_id=AttachmentId())
                self.m.attach(att)
                f.close()
                os.chdir("..")
            except IOError:
                log.error("Error opening file %s. Exiting." % myfile)
                import sys
                sys.exit(0)
Esempio n. 9
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()
Esempio n. 10
0
    def composeEmailToTicketing(self,
                                sender,
                                to_recipients,
                                cc_recipients,
                                body,
                                subject,
                                labels,
                                users,
                                attachments=[]):
        fromUser = sender.name + " [" + sender.email_address + "]"

        toUsers = "N/A"
        if to_recipients != None:
            toUsers = to_recipients[0].name + " [" + to_recipients[
                0].email_address + "]"
            if len(to_recipients) > 1:
                for x in range(1, len(to_recipients)):
                    toUsers += ", " + to_recipients[
                        x].name + " [" + to_recipients[x].email_address + "]"

        ccUsers = "N/A"
        if cc_recipients != None:
            ccUsers = cc_recipients[0].name + " [" + cc_recipients[
                0].email_address + "]"
            if len(cc_recipients) > 1:
                for x in range(1, len(cc_recipients)):
                    ccUsers += ", " + cc_recipients[
                        x].name + " [" + cc_recipients[x].email_address + "]"

        bodyAdd = "###From: {}\n\n###To: {}\n\n###Cc: {}\n\n###Subject: {}\n**════════════════════════════════**\n\n".format(
            fromUser, toUsers, ccUsers, subject)

        subjectAddSender = sender.name
        subjectAddLabel = ''
        subjectAddUser = ''
        sendToEmails = [exchangelib.Mailbox(email_address=self.ticketingEmail)]

        attList = []
        for file in attachments:
            if isinstance(file, exchangelib.FileAttachment):
                localPath = os.path.join(os.getcwd() + r"\temp", file.name)
                with open(localPath, 'wb') as f:
                    f.write(file.content)
                attList.append((file.name, file.content))

        for label in labels:
            subjectAddLabel += '#' + label + ' '
        for user in users:
            subjectAddUser += sHandler.sysData.userData[user]['username'] + ' '

        body = bodyAdd + body
        subject = subjectAddSender + " - " + subject + ' ' + subjectAddLabel + subjectAddUser
        m = exchangelib.Message(account=self.account,
                                subject=subject,
                                body=body,
                                to_recipients=sendToEmails)

        for file in attList:
            localPath = os.path.join(os.getcwd() + r"\temp", file[0])
            m.attach(exchangelib.FileAttachment(name=file[0], content=file[1]))
            os.remove(localPath)

        m.send()
        sHandler.sysLog.logger.info("Sent ticket to Trello: " + subject)
        print("\t[LOG] Sent ticket to Trello: " + subject + "\n\n>", end='')
# 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()
Esempio n. 12
0
    data = json.loads(msg, strict=False)
    print(data)
    print('Incoming Email Loaded')
except Exception as e:
    print('Error while loading state....Exit-1')
    print(str(e))
    sys.exit(1)

#Get the email
item_id = data['item_id']
email = account.inbox.get(item_id=item_id)

# Copy Email
kwargs = {f.name: getattr(email, f.name) for f in email.supported_fields()}
del (kwargs['attachments'])
reply = exchangelib.Message(**kwargs)
reply.account = account
reply.subject = 'RE: ' + email.subject
reply.consersation_id = email.conversation_id
if email.sender not in reply.to_recipients:
    reply.to_recipients.append(reply.sender)

if data['type'] == 'link_generated':
    link = '<a href ="' + data['url'] + '">here</a>'
    body = '<html>'
    body += '<body>'
    body += 'Hi! Manager/Service Desk <br/>'
    body += 'Please validate the request '
    body += link
    body += '<br/>'