示例#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='')
示例#2
0
 def attach_file(self, message, path):
     filename = os.path.basename(path)
     with open(path) as attachment_file:
         attachment = exchangelib.FileAttachment(
             name=filename, content=attachment_file.read())
         message.attach(attachment)
     return message
示例#3
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()
示例#4
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}")
示例#5
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()
示例#6
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='')