Exemplo n.º 1
0
def send_report(report, subject, to, cc=None):
    """E-mail a generated report to the designated recipients."""

    message_width = 76
    wrapper = textwrap.TextWrapper(width=message_width,
                                   subsequent_indent="  ",)
    pretty_message = "\n".join(wrapper.fill(x)
                               for x in report.split("\n"))
    sendmail(to,
             "*****@*****.**", # From:
             subject,
             pretty_message,
             cc=cc)
Exemplo n.º 2
0
def send_report(report, subject, to, cc=None):
    """E-mail a generated report to the designated recipients."""

    message_width = 76
    wrapper = textwrap.TextWrapper(
        width=message_width,
        subsequent_indent="  ",
    )
    pretty_message = "\n".join(wrapper.fill(x) for x in report.split("\n"))
    sendmail(
        to,
        "*****@*****.**",  # From:
        subject,
        pretty_message,
        cc=cc)
Exemplo n.º 3
0
    def send_email(self, subject, message):
        """ Send an email to the email address associated with the account

        """
        to_addr = self.get_address()
        if not self.trait_allows():
            self.logger.warn("Account flooded, will not mail %s" % to_addr)
        elif not self.dryrun:
            try:
                sendmail(to_addr, self.sender, subject, message)
                self.logger.debug("Sent message to %s" % to_addr)
            except smtplib.SMTPRecipientsRefused, e:
                error = e.recipients.get(to_addr)
                self.logger.warn("Failed to send message to %s (SMTP %d: %s)", to_addr, error[0], error[1])
            except smtplib.SMTPException:
                self.logger.exception("Failed to send message to %s", to_addr)
Exemplo n.º 4
0
def send_notify_email(new_cere_ous, to_email_addrs):
    """Sends information about OUs to a set of mail_addresses.

    @type  new_cere_ous:   dict
    @param new_cere_ous:   ou_id -> sko (basestring) mapping, containing the OUs
                           that has been added to the database.

    @type  to_email_addrs: list
    @param to_email_addrs: List of email addresses that should be notified about
                           the new OUs.
    """

    if len(new_cere_ous) < 1:
        logger.warn('No new OUs to send notification about')
        return

    ous = OU_class(db)

    # Set up email
    sender = '*****@*****.**'
    subject = 'New OUs added to Cerebrum'
    body = '%(num)d OUs added to Cerebrum on %(time)s\n\n' % \
           {'num': len(new_cere_ous), \
            'time': DateTime.now().strftime()}

    for ou_id in new_cere_ous.keys():
        names = ous.search_name_with_language(entity_id=ou_id, 
                                              name_language=co.language_nb,
                                              name_variant=co.ou_name)

        body += '  Entity Id: %d\n' % ou_id
        body += '  Stedkode:  %s\n' % new_cere_ous[ou_id]
        if len(names):
            body += '  Name     : %s\n\n' % names[0]['name']
    
    for to_email in to_email_addrs:
        try:
            sendmail(to_email, sender, subject, body)

        except SMTPRecipientsRefused, ref:
            for email, cond in ref.recipients.iteritems():
                logger.info('Failed to notify \'%s\': %s', email, cond)
            continue

        except SMTPException, e:
            logger.warn('Failed to notify \'%s\': %s', to_email, e)
            continue
Exemplo n.º 5
0
    def send_email(self, subject, message):
        """ Send an email to the email address associated with the account

        """
        to_addr = self.get_address()
        if not self.trait_allows():
            self.logger.warn("Account flooded, will not mail %s" % to_addr)
        elif not self.dryrun:
            try:
                sendmail(to_addr, self.sender, subject, message)
                self.logger.debug("Sent message to %s" % to_addr)
            except smtplib.SMTPRecipientsRefused, e:
                error = e.recipients.get(to_addr)
                self.logger.warn("Failed to send message to %s (SMTP %d: %s)",
                                 to_addr, error[0], error[1])
            except smtplib.SMTPException:
                self.logger.exception("Failed to send message to %s", to_addr)
Exemplo n.º 6
0
def send_email(requests, dryrun, database):
    """Send 'confirm you are still alive' e-mails.
    """

    logger.debug("%d e-mails to dispatch.", len(requests))
    for account_id in requests:
        attrs = requests[account_id]
        email = attrs.email
        uname = attrs.uname
        account_id = attrs.account_id
        magic_key = attrs.magic_key
        expire_date = attrs.expire_date.strftime("%Y-%m-%d")
        confirm_url = get_config("EXPIRE_CONFIRM_URL") + magic_key

        message = get_config("EXPIRE_MESSAGE_TEMPLATE") % {
            "uname": uname,
            "expire_date": expire_date,
            "url": confirm_url,}

        logger.debug("Generated a message for %s/%s (request key: %s). ",
                     uname, email, magic_key)
        if not dryrun:
            try:
                sendmail(email,
                         get_config("EXPIRE_MESSAGE_SENDER"),
                         get_config("EXPIRE_MESSAGE_SUBJECT"),
                         message)
                logger.debug("Message for %s/%s (request key: %s) sent",
                             uname, email, magic_key)
            except smtplib.SMTPRecipientsRefused, e:
                error = e.recipients.get(email)
                logger.warn("Failed to send message to %s/%s (SMTP %d: %s)",
                            uname, email, error[0], error[1])
                if error[0] == 550:
                    continue
                else:
                    cancel_request(attrs, database)
            except smtplib.SMTPException:
                logger.exception("Failed to send message to %s/%s", uname,
                        email)
                cancel_request(attrs, database)
Exemplo n.º 7
0
 def mail_warning(self, person, account, reason):
     """Warn a person by sending an e-mail to all its accounts."""
     msg  = "Someone has tried to recover the password for your account: %s.\n" % account.account_name
     msg += "This has failed, due to the following reason:\n\n  %s\n\n" % reason
     msg += "If this was not you, please contact your local IT-department as soon as possible."
     msg += "\n\n-- \n%s\n" % self.email_signature
     account2 = Factory.get('Account')(self.db)
     for row in person.get_accounts():
         account2.clear()
         account2.find(row['account_id'])
         try:
             primary = account2.get_primary_mailaddress()
         except Errors.NotFoundError, e:
             log.error("Couldn't warn user %s, no primary mail: %s" %
                       (account.account_name, e))
             continue
         log.debug("Emailing user %s (%d)" % (account2.account_name, account2.entity_id))
         try:
             sendmail(primary, self.email_from, self.email_subject, msg)
         except Exception, e:
             log.error("Error for %s from Utils.sendmail: %s" % (primary, e))
Exemplo n.º 8
0
def send_email(requests, dryrun, database):
    """Send 'confirm you are still alive' e-mails.
    """

    logger.debug("%d e-mails to dispatch.", len(requests))
    for account_id in requests:
        attrs = requests[account_id]
        email = attrs.email
        uname = attrs.uname
        account_id = attrs.account_id
        magic_key = attrs.magic_key
        expire_date = attrs.expire_date.strftime("%Y-%m-%d")
        confirm_url = get_config("EXPIRE_CONFIRM_URL") + magic_key

        message = get_config("EXPIRE_MESSAGE_TEMPLATE") % {
            "uname": uname,
            "expire_date": expire_date,
            "url": confirm_url,
        }

        logger.debug("Generated a message for %s/%s (request key: %s). ",
                     uname, email, magic_key)
        if not dryrun:
            try:
                sendmail(email, get_config("EXPIRE_MESSAGE_SENDER"),
                         get_config("EXPIRE_MESSAGE_SUBJECT"), message)
                logger.debug("Message for %s/%s (request key: %s) sent", uname,
                             email, magic_key)
            except smtplib.SMTPRecipientsRefused, e:
                error = e.recipients.get(email)
                logger.warn("Failed to send message to %s/%s (SMTP %d: %s)",
                            uname, email, error[0], error[1])
                if error[0] == 550:
                    continue
                else:
                    cancel_request(attrs, database)
            except smtplib.SMTPException:
                logger.exception("Failed to send message to %s/%s", uname,
                                 email)
                cancel_request(attrs, database)
Exemplo n.º 9
0
 def mail_warning(self, person, account, reason):
     """Warn a person by sending an e-mail to all its accounts."""
     msg = "Someone has tried to recover the password for your account: %s.\n" % account.account_name
     msg += "This has failed, due to the following reason:\n\n  %s\n\n" % reason
     msg += "If this was not you, please contact your local IT-department as soon as possible."
     msg += "\n\n-- \n%s\n" % self.email_signature
     account2 = Factory.get('Account')(self.db)
     for row in person.get_accounts():
         account2.clear()
         account2.find(row['account_id'])
         try:
             primary = account2.get_primary_mailaddress()
         except Errors.NotFoundError, e:
             log.error("Couldn't warn user %s, no primary mail: %s" %
                       (account.account_name, e))
             continue
         log.debug("Emailing user %s (%d)" %
                   (account2.account_name, account2.entity_id))
         try:
             sendmail(primary, self.email_from, self.email_subject, msg)
         except Exception, e:
             log.error("Error for %s from Utils.sendmail: %s" %
                       (primary, e))
Exemplo n.º 10
0
            mail_to = val
        elif opt in ("--mail_from", ):
            mail_from = val
        elif opt in ("--mail_cc", ):
            mail_cc = val
        else:
            usage()
    report = []
    logger.info("### Searching invalid VOIP objects...")
    report_invalid_voip_addresses(logger, report)
    logger.info("### Search  finished, found %d" % len(report))
    if len(report):
        message = create_report_message(report)
        if mail_to and mail_from:
            subject = 'Report of invalid voipAddresses.'
            sendmail(mail_to, mail_from, subject, message, cc=mail_cc)
            logger.info("Sent report by mail to %s." % mail_to)
        else:
            outstream.write(message)
            logger.info("Wrote report to file %s" % outfile)
    if not outstream is sys.stdout:
        outstream.close()


def usage(err=0):
    import os
    if err:
        print >> sys.stderr, err
    prog = os.path.basename(sys.argv[0])
    print >> sys.stderr, """\nUsage: %(prog)s [options]
Report voip addresses owned by persons without accounts.
Exemplo n.º 11
0
 
 if errors:
     mail_to = options["error_recipients"]
     subject = "Errors from subnet-import %s" % today
     mail_body = doc_info        
         
     mail_body += "The following errors were encountered during the import:\n\n"
     mail_body += "\n\n".join(errors)
     
     if options["force"]:
         mail_body +=  "\n\nImport forced - non-erronous changes made anyway."
         mail_body +=  "\nThe following changes were made:\n%s\n" % "\n".join(changes)
         
         logger.info("Force-committing non-erronous changes to database.")
         logger.info("Sending mail to '%s' (CC: '%s')" % (mail_to, options["mail-cc"]))
         sendmail(mail_to, options["mail-from"], subject, mail_body, cc=options["mail-cc"])
         db.commit()            
         return 0
     
     else:
         mail_body +=  "\n\nImport not completed - no changes made."
         mail_body +=  "Fix the above problems, then rerun the import.\n"
         logger.error("Errors encountered. No changes made by import.")
         db.rollback()
         logger.info("Sending mail to '%s' (CC: '%s')" % (mail_to, options["mail-cc"]))
         sendmail(mail_to, options["mail-from"], subject, mail_body, cc=options["mail-cc"])
         return 3
 else:
     mail_to = options["status_recipients"]
     subject = "Status from subnet-import %s" % today
     mail_body = doc_info
Exemplo n.º 12
0
            mail_to = val
        elif opt in ("--mail_from",):
            mail_from = val
        elif opt in ("--mail_cc",):
            mail_cc = val
        else:
            usage()
    report = []
    logger.info("### Searching invalid VOIP objects...")
    report_invalid_voip_addresses(logger, report)
    logger.info("### Search  finished, found %d" % len(report))
    if len(report):
        message = create_report_message(report)
        if mail_to and mail_from:
            subject = "Report of invalid voipAddresses."
            sendmail(mail_to, mail_from, subject, message, cc=mail_cc)
            logger.info("Sent report by mail to %s." % mail_to)
        else:
            outstream.write(message)
            logger.info("Wrote report to file %s" % outfile)
    if not outstream is sys.stdout:
        outstream.close()


def usage(err=0):
    import os

    if err:
        print >>sys.stderr, err
    prog = os.path.basename(sys.argv[0])
    print >>sys.stderr, """\nUsage: %(prog)s [options]
Exemplo n.º 13
0
        mail_body = doc_info

        mail_body += "The following errors were encountered during the import:\n\n"
        mail_body += "\n\n".join(errors)

        if options["force"]:
            mail_body += "\n\nImport forced - non-erronous changes made anyway."
            mail_body += "\nThe following changes were made:\n%s\n" % "\n".join(
                changes)

            logger.info("Force-committing non-erronous changes to database.")
            logger.info("Sending mail to '%s' (CC: '%s')" %
                        (mail_to, options["mail-cc"]))
            sendmail(mail_to,
                     options["mail-from"],
                     subject,
                     mail_body,
                     cc=options["mail-cc"])
            db.commit()
            return 0

        else:
            mail_body += "\n\nImport not completed - no changes made."
            mail_body += "Fix the above problems, then rerun the import.\n"
            logger.error("Errors encountered. No changes made by import.")
            db.rollback()
            logger.info("Sending mail to '%s' (CC: '%s')" %
                        (mail_to, options["mail-cc"]))
            sendmail(mail_to,
                     options["mail-from"],
                     subject,