Example #1
0
def main():
    fromaddr = ""
    toaddr = ""
    mailserver = ""
    toaddrs = ""
    count = 0
    cmpValue = 0
    #pdb.set_trace()
    try:
        config_file = open("mailConfig.cfg", 'r')
    except IOError:
        print 'Can\'t open config file for reading, So mail will not be sent.'
        sys.exit(0)
    fileList = config_file.readlines()
    for linestr in fileList:
        lineStr = linestr[:-1]
        if lineStr.startswith('fromaddr'):
            fromaddr = getValue('fromaddr', lineStr)
        if lineStr.startswith('toaddr'):
            toaddr = getValue('toaddr', lineStr)
            toaddrs = toaddr.split(',')
        if lineStr.startswith('mailserver'):
            mailserver = getValue('mailserver', lineStr)
        count = count + 1

    mailobj = mailer.Mailer(toaddrs, fromaddr, mailserver)
    #print "the value is =>%s" %sys.argv[1]
    #print "the value is => %s" %sys.argv[2]
    #sub = "problem with the MSW installation script"
    #msg = "\n\rNot able to install\n\r Regards\n\r SIT Team\n\r"
    #mailobj.sendMail(sub,msg)
    mailobj.sendMail(sys.argv[1], sys.argv[2])
    print "\nDone"
Example #2
0
def monthly_revenue_report() -> dict:

    # Getting Subscribed Deals
    pipeline_id = functions.get_pipeline_id()
    stage_id = functions.get_stage_id(pipeline_id)
    pipeline_deals = functions.get_pipeline_deals(pipeline_id)
    subscribed_deals = functions.filter_subscribed_deals(
        pipeline_deals, stage_id)

    csv_file_path = functions.generate_subscribed_deals_data_for_monthly_revenue_report(
        subscribed_deals)

    # Creating Mailer
    sender_email = os.getenv("SENDER_EMAIL")
    sender_password = os.getenv("SENDER_PASSWORD")
    host = os.getenv("HOST")
    port = os.getenv("PORT")
    mail_handler = mailer.Mailer(sender_email, sender_password, host, port)

    # Sending email
    subejct = 'MTP Montly Revenue Report Data'
    mail_parts = mail_handler.build_mtp_data_csv_mail_parts(csv_file_path)
    recipients = [
        '*****@*****.**', '*****@*****.**'
    ]
    mail_handler_response = mail_handler.send_emails(mail_parts, subejct,
                                                     recipients)
    return mail_handler_response
Example #3
0
    def process(self, infos):
        """
        En prenant les informations dans la configuration fournie, 
        un mail est envoyé en se basant sur les informations contenues dans le paramètre

            subject = infos['title']
            content = mise en forme avec make_xhtml

        :param infos: données à envoyer par mail
        :return: -
        """
        self.logger.debug("Send Mail notification, infos = {}".format(infos))
        if self.conf:
            for dest in self.conf['to']:
                message = mailer.Message(From=self.conf['from'],
                                         To=dest,
                                         charset="utf-8")
                message.Subject = infos['title']

                message.Html = content.xml2text(
                    content.make_xhtml(root=None, entry=infos), 'utf-8')
                sender = mailer.Mailer(host=self.conf['server'],
                                       port=self.conf['port'],
                                       usr=self.conf['user'],
                                       pwd=self.conf['passwd'],
                                       use_ssl=self.conf['usessl'])
                sender.send(message)
                self.logger.debug("Mail sent to {}".format(dest))
Example #4
0
def render_email(report_file, server, users):
    """
    Render the report
    """

    output = StringIO.StringIO()
    report_data = {}

    with open(report_file) as infile:
        report_data = json.load(infile)
        _render('email.html', report_data, output)

    summary = []
    keys = report_data['summary'].keys()
    keys.sort()
    for key in keys:
        if report_data['summary'][key] > 0:
            summary.append('%s %d' %
                           (key.title(), report_data['summary'][key]))
    summary_str = ', '.join(summary)

    message = mailer.Message()
    message.From = 'nobody <*****@*****.**>'
    message.To = users
    message.Subject = report_data['info']['name'] + ' - ' + summary_str
    message.Html = output.getvalue()

    sender = mailer.Mailer(server)
    sender.send(message)
Example #5
0
 def _notify(self):
     if len(self.mailusers) == 0:
         return
     subj = "Your mailbox has reached a quota threshold"
     body = (
         "I am sorry to inform you that your email account for:\n\n"
         "%s\n\n"
         "has reached a usage of over %s%%. Please take actions before your inbox gets full.\n\n"
         "Sincerely, your email server.")
     emailhostname = config['emailhostname']
     msg = mailer.Message()
     msg.Subject = subj
     msg.charset = "utf-8"
     if config['emailbcc']:
         msg.BCC = config['emailbcc']
     mail = mailer.Mailer()
     mail.host = smtp['host']
     mail.use_tls = smtp['tls']
     mail.port = smtp['port']
     if smtp['user'] and smtp['pass']:
         mail.login(smtp['user'], smtp['pass'])
     print("Notifying above listed users...")
     for email in self.mailusers:
         if emailhostname == "auto" or emailhostname is None:
             emailhostname = email['email'].split("@")[1]
         msg.Body = body % (email['email'], config['threshold'])
         msg.From = "quota-notification@%s" % emailhostname
         if config['demo']:
             msg.To = config['demoemail']
         else:
             msg.To = email['email']
         mail.send(msg)
Example #6
0
	def runTest(self):
		'''
		Tests basic functionality.
		'''
		t = threading.Thread(target=self.helper)
		t.setDaemon(True)
		t.start()
		self.assertEqual(self.queue.get(.1), 'ready')
		time.sleep(.1)

		try:
			From = "*****@*****.**"
			To = ["*****@*****.**", "*****@*****.**"]

			mailer_inst = mailer.Mailer('127.0.0.1', 1025)
			msg = mailer.Message(From=From, To=To, charset="utf-8")
			mailer_inst.send(msg)

			peer, mailfrom, rcpttos, data = self.queue.get(.1)

			self.assertEqual(mailfrom, From)
			self.assertEqual(rcpttos, To)
			print data

		finally:
			try:
				raise asyncore.ExitNow()
			except asyncore.ExitNow:
				pass
Example #7
0
def send_mail(address, username, link, template):
    if EMAIL_ENABLED:
        message = mailer.Message(From="*****@*****.**", To=address)
        message.Subject, message.Html = get_email_text(username, link,
                                                       template)

        sender = mailer.Mailer(SMTP_ADDRESS, SMTP_PORT)
        sender.send(message)
Example #8
0
    def create_smtp_server():
        smtp = mailer.Mailer(host=EmailService.__smtp_server,
                             port=EmailService.__smtp_port,
                             usr=EmailService.__smtp_username,
                             pwd=EmailService.__smtp_password,
                             use_tls=True)

        return smtp
Example #9
0
def main():
    global emailer, maildomain, report_sender, error_sender, config, mailserver, backup_states
    emailer = mailer.Mailer(debug, error_recipient, mailserver, error_sender,
                            report_sender, maildomain, admin_report_recipient)
    emailer.config = config
    if is_networker_available():
        buildFrequencyMapping()
        buildLocationMapping()
        buildFrequencyToTimeMapping()
        for directorie, subdirs, filenames in os.walk(os.getcwd()):
            print(directorie)
            try:
                if isInIgnoreList(directorie) == False:
                    for filename in filenames:
                        if ".yaml" in filename:
                            try:
                                yamlD = yaml.load(
                                    open(directorie + "/" + filename, 'r'))
                                if yamlD != None and "Client" in yamlD:
                                    for x in range(0, len(yamlD['Client'])):
                                        try:
                                            createRelations(yamlD['Client'][x])
                                            if yamlD['Client'][x][
                                                    'backupType'] == 'Filesystem':
                                                getFilesystem_backup_state(
                                                    yamlD['Client'][x])
                                            elif yamlD['Client'][x][
                                                    'backupType'] == 'VM':
                                                getVM_backup_state(
                                                    yamlD['Client'][x])
                                            else:
                                                getFilesystem_backup_state(
                                                    yamlD['Client'][x])
                                        except:
                                            print("something went wrong")
                                            print(
                                                "sending error message to developer maurice fernitz"
                                            )
                                            emailer.send_error_mail(
                                                str(traceback.format_exc()) +
                                                " NODE: " +
                                                yamlD['Client'][x]['hostname'])
                            except:
                                emailer.send_error_mail(
                                    str(traceback.format_exc()))
            except:
                emailer.send_error_mail(str(traceback.format_exc()))
        send_metrics_to_graphite()
        print("Trying to send the report mails")
        emailer.report_send_email(contacts_relation_to_owner, backup_states,
                                  contacts_relation_to_backups)
        if send_admin_report.lower() == 'true':
            getServerProtectionReport()
            emailer.send_admin_report_mail(backup_states)
    else:
        print(
            "ERROR: Networker not reachable/available please make sure networker gui/restApi is reachable/available"
        )
Example #10
0
    def test(self):
        message = mailer.Message()
        message.From = "*****@*****.**"
        message.To = "*****@*****.**"
        message.Subject = "My Test Python Email"
        message.Body = "Hello Jose"  # open("letter.txt", "rb").read()

        my_mailer = mailer.Mailer("outgoing.verizon.net")
        my_mailer.send(message)
Example #11
0
def send_mail(mail_data, user_data, server_data):
    m = mailer.Mailer()

    m.set_login(user_data.get("sender"))
    m.set_srv(server_data.get("serv"), server_data.get("port"))
    m.set_body(mail_data.get("to"), mail_data.get("subject"),
               mail_data.get("attach"), mail_data.get("body"))

    m.conn()
Example #12
0
def main():
    locale.setlocale(locale.LC_ALL, '')
    logfmt = "%(asctime)s %(levelname)s: %(message)s"
    logging.basicConfig(format=logfmt, level=logging.WARNING)

    parser = argparse.ArgumentParser(description="Bot de déclaration pour l'URSSAF")
    parser.add_argument("cfgfile", metavar="configfile", help="Fichier de configuration")
    parser.add_argument("--payment", "-p", metavar="file", help="Fichier des factures payées")
    parser.add_argument("--ca-pdf-dir", "-c", metavar="dir", default=".", help="Répertoire où enregistrer le PDF de déclaration du chiffre d'affaire")
    parser.add_argument("--already-paid-noop", action="store_true", help="Ne fait rien si c'est déjà payé")
    parser.add_argument("--no-error-mail", action="store_true", help="N'envoie pas de mail pour les erreurs")
    parser.add_argument("--verbose", "-v", action="count", help="Augmente le niveau de verbosité")

    args = parser.parse_args()

    configpath = args.cfgfile
    verbose = args.verbose
    payfile = args.payment
    capdfdir = args.ca_pdf_dir
    paidnoop = args.already_paid_noop
    errormail = not args.no_error_mail

    if verbose is not None:
        loglevels = ["WARNING", "INFO", "DEBUG", "NOTSET"]
        verbose = min(len(loglevels), verbose) - 1
        logging.getLogger().setLevel(loglevels[verbose])

    logging.info("Reading config file %s", configpath)
    config = configparser.ConfigParser()
    config.read(configpath)

    smtphost = config["SMTP"]["smtphost"]
    smtpport = config["SMTP"].get("smtpport")
    smtpuser = config["SMTP"].get("smtpuser")
    smtppassword = config["SMTP"].get("smtppwd")
    mailsender = mailer.Mailer(smtphost, smtpport, smtpuser, smtppassword)

    try:
        try:
            dostuff(config, mailsender, payfile, capdfdir)
        except urssaf.AlreadyPaidError:
            if paidnoop:
                logging.info("Already declared and paid. Ignoring.")
            else:
                raise

    except KeyboardInterrupt:
        pass
    except:
        logging.exception("Top-level exception:")
        if not errormail:
            raise

        msg = "Exception caught while trying to run the declaration.\n\n"
        msg += traceback.format_exc()
        mailsender.error(smtpuser, msg)
Example #13
0
def process_message(msg):
    msg = json.loads(msg)

    message = mailer.Message()
    message.From = msg['From']
    message.To = msg['To']
    message.Subject = msg['Subject']
    message.Body = msg['Body']

    sender = mailer.Mailer('localhost')
    sender.send(message)
    print("Sent message at {}: {}\n".format(timestamp(), msg))
Example #14
0
def send_email_with_error(data: dict, error_traceback: str) -> str:
    """
    Send an email to the user who committed the changes that an error has happened while processing
    their .jobs_done file.

    Returns the recipient of the email in case of success, otherwise will raise an exception (not sure
    which exceptions are raised by the underlying library).
    """
    import mailer

    recipient = data['actor']['emailAddress']

    project_key = data['repository']['project']['key']
    slug = data['repository']['slug']
    changes = [(change['ref']['id'], change['toHash'])
               for change in data['changes']]
    changes_msg = ', '.join(
        f'{branch.replace("refs/heads/", "")} @ {commit[:7]}'
        for (branch, commit) in changes)
    subject = f'JobsDone failure during push to {project_key}/{slug} ({changes_msg})'

    message = mailer.Message(
        From=os.environ['JD_EMAIL_FROM'],
        To=[recipient],
        # RTo=None,
        # Cc=self.cc,
        Subject=subject,
        charset='UTF-8',
    )

    pretty_json = pprint.pformat(data)
    message.Body = EMAIL_PLAINTEXT.format(error_traceback=error_traceback,
                                          pretty_json=pretty_json)
    style = 'colorful'
    html = EMAIL_HTML.format(
        error_traceback_html=highlight(error_traceback, PythonTracebackLexer(),
                                       HtmlFormatter(style=style)),
        pretty_json_html=highlight(pretty_json, JsonLexer(),
                                   HtmlFormatter(style=style)),
    )

    message.Html = html

    sender = mailer.Mailer(
        host=os.environ['JD_EMAIL_SERVER'],
        port=int(os.environ['JD_EMAIL_PORT']),
        use_tls=True,
        usr=os.environ['JD_EMAIL_USER'],
        pwd=os.environ['JD_EMAIL_PASSWORD'],
    )
    sender.send(message)
    return recipient
Example #15
0
def send_email(errorcode, site, conf):
    """ Send email ONLY on error """
    mailhost = conf.get(site, 'mailhost')
    msg = mailer.Message()

    msg.From = 'Backup <emailaddress>'
    msg.To = ['MySQL Backup Failures <emailaddress>']
    msg.Subject = 'MySQL Backup Failures %s - %s' % (TIMESTAMP, site)
    msg.Body = 'Failure on %s - %s due to %s' % (site, conf.get(
        site, 'host'), errorcode)

    sender = mailer.Mailer(mailhost)  # MAILHOST configured at top

    sender.send(msg)
Example #16
0
def enviarCorreo(destinatarios='Pablo <*****@*****.**>', asunto='Correo Test', mensaje='Test', adjuntos=''):
    message = mailer.Message()
    nombreCorreo = '*****@*****.**'
    message.From = 'Diagnostico github <%s>'%nombreCorreo
    message.To = destinatarios
    message.Subject = asunto
    message.Html = mensaje

    if len(adjuntos) != 0:
        message.attach(adjuntos)

    mail = mailer.Mailer('vvv.ovh.net')
    mail.login(nombreCorreo, creaPalabra())
    mail.send(message)
Example #17
0
def main():
 global emailer,error_recipient,agentF,config,locations,error_sender,maildomain,baseurl,mailserver
 buildFrequencyMapping()
 buildLocationMapping()
 emailer = mailer.Mailer("false",error_recipient,mailserver,error_sender,"",maildomain)
 agentF = delete_agent.Agent(baseurl,headers,config['networker_urls'])
 vmF = delete_vm.VM(headers,baseurl,config['networker_urls'])
 vmuuidF = delete_vm_via_uuid.VMuuid(headers,baseurl,config['networker_urls'])
 print ("-----------------------Delete script has started------------------------")
 try:
   for filename in os.listdir(os.getcwd() + "/delete"):
    if ".yaml" in filename :
     try:
      yamlD = yaml.load(open(os.getcwd()+"/delete/"+filename,'r'))
      if yamlD != None and 'Client' in yamlD:
       for x in range(0,len(yamlD['Client'])) :
        try:
         if yamlD['Client'][x]['backupType'] == "Filesystem" :
            knownClient = agentF.getClient(yamlD['Client'][x]['hostname'])
            if knownClient != None and len(knownClient) > 0 :
                agentF.deleteClient(knownClient[0]['resourceId']['id'])
            else:
               print (yamlD['Client'][x]['hostname'] + " could not be found in networker, maybe it is already deleted?")
         elif yamlD['Client'][x]['backupType'] == "VM":
                result = vmF.searchForVM(yamlD['Client'][x]['hostname'])
                if result != None :
                        location = ""
                        if "location" in yamlD['Client'][x] :
                                location = locations[yamlD['Client'][x]['location'].lower()] + "_"
                        group=yamlD['Client'][x]['retentionclass']+"_VM_"+location+frequency[yamlD['Client'][x]['frequency'].lower()]+yamlD['Client'][x]['starttime']
                        vmF.deleteVM(result['uuid'],group,result['vCenter'])
        except:
          if len(yamlD['Client']) > 0 :
                emailer.send_error_mail(str(traceback.format_exc()) + " NODE: " + yamlD['Client'][x]['hostname'])
          else: 
                emailer.send_error_mail(str(traceback.format_exc()) + " NODE: " + yamlD['Client'])
      elif yamlD != None and 'ToDelete' in yamlD:
       	for x in range(0,len(yamlD['ToDelete'])) :
                try:
                        if yamlD['ToDelete'][x]['backupType'] == "VM" :
                                group=yamlD['ToDelete'][x]['group']
                                vmuuidF.deleteVM(yamlD['ToDelete'][x]['uuid'],group)
                except:
                        emailer.send_error_mail(str(traceback.format_exc()) + " NODE: " + yamlD['ToDelete'][x]['uuid'])
     except:
       emailer.send_error_mail(str(traceback.format_exc()))
 except:
  print ("something went wrong")
  print ("sending error message")
  emailer.send_error_mail(str(traceback.format_exc()))
Example #18
0
def check(weeks: int = None, days: int = None) -> dict:

    # Retrieving almost finished subscriptions
    pipeline_id = functions.get_pipeline_id()
    stage_id = functions.get_stage_id(pipeline_id)
    pipeline_deals = functions.get_pipeline_deals(pipeline_id)
    subscribed_deals = functions.filter_subscribed_deals(
        pipeline_deals, stage_id)
    almost_finished_subscriptions = functions.filter_almost_finished_subscriptions(
        subscribed_deals, weeks=weeks, days=days)

    # Sending emails (if any)
    if len(almost_finished_subscriptions) > 0:

        # Creating Mailer
        sender_email = os.getenv("SENDER_EMAIL")
        sender_password = os.getenv("SENDER_PASSWORD")
        host = os.getenv("HOST")
        port = os.getenv("PORT")
        mail_handler = mailer.Mailer(sender_email, sender_password, host, port)

        # Time Remaining String
        if weeks:
            time_remaining_string = f"{weeks} {'weeks' if weeks > 1 else 'week'}"

        if days:
            time_remaining_string = f"{days} {'days' if days > 1 else 'day'}"

        # Sending email
        subejct = f'Subscriptions finishing in {time_remaining_string}'
        mail_parts = mail_handler.build_almost_finished_subscriptions_notification_mail_parts(
            almost_finished_subscriptions,
            weeks_to_finish=weeks,
            days_to_finish=days)
        recipients = [
            '*****@*****.**', '*****@*****.**',
            '*****@*****.**'
        ]
        mail_handler_response = mail_handler.send_emails(
            mail_parts, subejct, recipients)

    else:
        mail_handler_response = {"message": "No messages to send."}

    if datetime.datetime.now().day == 1:
        mail_handler_response["subscribed_deals"] = subscribed_deals

    return mail_handler_response
Example #19
0
def main():
    locale.setlocale(locale.LC_ALL, '')
    logfmt = "%(asctime)s %(levelname)s: %(message)s"
    logging.basicConfig(format=logfmt, level=logging.WARNING)

    parser = argparse.ArgumentParser(description="Programme de rapprochement bancaire")
    parser.add_argument("cfgfile", metavar="configfile", help="Fichier de configuration")
    parser.add_argument("--invoice-dir", "-i", metavar="dir", help="Répertoire contenant les fichiers .inv")
    parser.add_argument("--payment", "-p", metavar="file", help="Fichier des factures payées")
    parser.add_argument("--no-error-mail", action="store_true", help="N'envoie pas de mail pour les erreurs")
    parser.add_argument("--verbose", "-v", action="count", help="Augmente le niveau de verbosité")

    args = parser.parse_args()

    configpath = args.cfgfile
    verbose = args.verbose
    invdir = args.invoice_dir
    payfile = args.payment
    errormail = not args.no_error_mail

    if verbose is not None:
        loglevels = ["WARNING", "INFO", "DEBUG", "NOTSET"]
        verbose = min(len(loglevels), verbose) - 1
        logging.getLogger().setLevel(loglevels[verbose])

    logging.info("Reading config file %s", configpath)
    config = configparser.ConfigParser()
    config.read(configpath)

    smtphost = config["SMTP"]["smtphost"]
    smtpport = config["SMTP"].get("smtpport")
    smtpuser = config["SMTP"].get("smtpuser")
    smtppassword = config["SMTP"].get("smtppwd")
    mailsender = mailer.Mailer(smtphost, smtpport, smtpuser, smtppassword)

    try:
        dostuff(config, mailsender, invdir, payfile)
    except KeyboardInterrupt:
        pass
    except:
        logging.exception("Top-level exception:")
        if not errormail:
            raise

        msg = "Exception caught while trying to run the declaration.\n\n"
        msg += traceback.format_exc()
        mailsender.error(smtpuser, msg)
Example #20
0
def run(conf):
    to = conf['to']
    method = conf['method']
    latent_factors = list(range(1, conf['latent_factors'] + 1))
    path = conf['path']
    plot_filename = str(datetime.utcnow())

    logger.info('Reading ratings.csv ...')
    movies = gl.SFrame.read_csv(os.path.join(path, 'ratings.csv'),
                                column_type_hints=[int, int, float, int])
    logger.info('Reading complete')

    data = []
    logger.info('Training model ...')
    for i in latent_factors:
        m = gl.recommender.factorization_recommender.create(movies,
                                                            user_id='userId',
                                                            item_id='movieId',
                                                            target='rating',
                                                            num_factors=i,
                                                            solver=method,
                                                            verbose=False)
        logger.info('Processing... {0}'.format(i))
        rmse = m.get('training_rmse')
        data.append(rmse)

    plt.plot(latent_factors, data)
    plt.xlabel('Number of latent factors')
    plt.ylabel('RMSE')
    plt.title('Number of latent factors in comparsion with RMSE')

    logger.info('Saving plot to disc ...')
    plt.savefig('{0}.svg'.format(plot_filename))
    logger.info('Save complete')

    buf = io.BytesIO()
    plt.savefig(buf, format='svg')
    buf.seek(0)

    mail = mailer.Mailer(os.path.join('./Credentials', 'credentials.json'))
    mail.send(toaddrs=to,
              fromaddrs='*****@*****.**',
              subject='Recommender engine',
              body='Method used = {0}\nLatent_factors = {1}'.format(
                  method, len(latent_factors)),
              payload=('{0}.svg'.format(plot_filename), buf))
Example #21
0
def send_email(errorcode):
    """ Send email ONLY in case of error condition """
    # Email Settings
    host = 'hostname/ip'
    fromemail = 'SendName <*****@*****.**>'
    toemail = ['ToName <*****@*****.**>']
    filestamp = time.strftime('%Y-%m-%d')
    subject = 'Rsync Backup Failures ' + filestamp

    msg = mailer.Message()
    msg.From = fromemail
    msg.To = toemail
    msg.Body = errorcode
    msg.Subject = subject
    
    sender = mailer.Mailer(host)
    sender.send(msg)
Example #22
0
    def send(self):
        """send email"""
        if not self._check():
            return False

        self._build_message()
        _sender = mailer.Mailer(host=self._host,
                                usr=self._usr,
                                port=self._port,
                                use_ssl=self._use_ssl,
                                pwd=self._pwd)
        try:
            _sender.send(self._message)
        except:
            print "[Error] Something wrong when sending email"
            return False
        return True
Example #23
0
    def sendNotif(self):
        """ send out mail """

        if not self._fw_updated or not send_email:
            return
        print("Sending notification email...")
        message = mailer.Message(
            From=email_from,
            To=re.split("\s{1,}|\n", email_to),
            Subject="BreachBlocker Notification"
        )
        message.Body = ""
        for ip in self._new_ips:
            message.Body += "Host " + ip + " added to firewall droplist (" + ", ".join(self._ip_violations[ip]) + ")\n"
        sender = mailer.Mailer(mailhost)
        try:
            sender.send(message)
        except Exception:
            self.printError("Could not send email. Server problems?")
Example #24
0
def job_email(user, reciever_emails):
    import mailer
    import datetime
    today = datetime.datetime.today().date()

    message = mailer.Message()

    message.From = '{user}@agl.com.au'.format(user=user)
    message.To = [reciever_emails]
    message.Subject = 'DR BYOT churned customer report {0}'.format(today)

    message.Body = '''Hi Team,

  On {dt_today}, you got this email. 
  '''.format(dt_today=today)
    #message.attach("P:/New Energy/Churn Moveout Report/Input_file/Full VPPSA Site List V3.xlsx")

    sender = mailer.Mailer('aglsmtp05.agl.com.au')

    sender.send(message)
    return ()
Example #25
0
 def __init__(self, _from):
     self.message = mailer.Message()
     self.message.From = _from
     self.sender = mailer.Mailer('sms.cellinkgy.com')
Example #26
0
            aprx.updateConnectionProperties(editingGDB, hubGDB)

            try:

                aprx.save()
            except:
                logging.basicConfig(filename=logFile, level=logging.ERROR)
                logging.error(' Error with ArcGIS Pro project {}.'.format(m))
            del aprx

            logging.basicConfig(filename=logFile, level=logging.INFO)
            logging.info(' Data sources for {} were updated.'.format(m))

with open(csvFile, 'w') as g:
    writer = csv.writer(g)
    writer.writerow(['APRX File Path'])

message.Subject = "ArcGIS Pro Data Source Update - SUCCESS"
message.Html = "All ArcGIS Pro projects that had data pointing to the Editing geodatabase have been repointed to the Hub.<br><br>" \
               "Check the log (<a href='{}'>{}</a>) if you like.<br><br>" \
               "Or you can simply go on with your day.".format(logFile, logFile)
mailer = mailer.Mailer("mailhost.co.jeffco.us")
mailer.send(message)

finish = time.time()
duration = str(finish - start)

logging.basicConfig(filename=logFile, level=logging.INFO)
logging.info(' Sync was successful in {} seconds'.format(duration))
def check_email(user, sender_email, path_input, path_output, reciever_emails):

    t_preliminary_0 = time.time()
    # Set user.
    # Create engine.
    engine = create_engine('hana://{user}@hananode1:30015'.format(user=user))

    df1 = pd.read_excel(path_input)

    df1.to_sql('vpp_churn_tom_from_python',
               engine,
               schema=user,
               if_exists='replace',
               dtype=types.NVARCHAR(length=255))

    t_preliminary_1 = time.time()

    # Wait for 5 seconds
    #time.sleep(300)

    t_sql_code_0 = time.time()
    sql = """
    SELECT A."Inverter", A."POD (NMI)" NMI, A."*approved BP*" BP_VPP, C.BUSINESSPARTNER BP_Active,C.COMPANY,
    min(CASE WHEN C.BUSINESSPARTNER IS NULL THEN '3_LeftVPP_New_NonAGL_Customer' 
    WHEN C.BUSINESSPARTNER IS NOT NULL AND right(A."*approved BP*",9) <> right(C.BUSINESSPARTNER,9) and C.COMPANY != 'AGL' THEN '3_LeftVPP_New_NonAGL_Customer'
    WHEN C.BUSINESSPARTNER IS NOT NULL AND right(A."*approved BP*",9) <> right(C.BUSINESSPARTNER,9) THEN '4_LeftVPP_New_AGL_Customer'
    when C.BUSINESSPARTNER IS NOT NULL AND right(A."*approved BP*",9) = right(C.BUSINESSPARTNER,9) and C.COMPANY = 'PD' THEN '2_PowerDirect'
    ELSE '1_CURRENT' END) AS STATUS
    , CASE WHEN A."*approved BP*" IS NOT NULL THEN (SELECT max(MOVEINDATE) from "SP_CUSTOMER"."CIA_TheTruthAboutCustomer"D where right(D.BUSINESSPARTNER,9) = right(A."*approved BP*",9) and left(D.NMI,10)=left(A."POD (NMI)",10)) END VPP_MOVEIN
    , CASE WHEN A."*approved BP*" IS NOT NULL THEN (SELECT max(MOVEOUTDATE) from "SP_CUSTOMER"."CIA_TheTruthAboutCustomer"D where right(D.BUSINESSPARTNER,9) = right(A."*approved BP*",9) and left(D.NMI,10)=left(A."POD (NMI)",10)) END VPP_MOVEOUT
    ,CASE WHEN C.BUSINESSPARTNER IS NOT NULL THEN (SELECT max(MOVEINDATE) from "SP_CUSTOMER"."CIA_TheTruthAboutCustomer"D where right(D.BUSINESSPARTNER,9) = right(C.BUSINESSPARTNER,9)and left(D.NMI,10)=left(C.NMI,10)) END CURRENT_CUSTOMER_MOVEIN
    
    from
    	(SELECT * from "{user}"."VPP_CHURN_TOM_FROM_PYTHON") A
    
    left join
    
    	(SELECT * FROM "SP_CUSTOMER"."CIA_TheTruthAboutCustomer" B
    	WHERE FUEL = 'ELEC' AND STATUS = 'ACTIVE'
    	) C on left(A."POD (NMI)",10) = left(C.NMI,10)
    
    GROUP BY A."Inverter", A."POD (NMI)", A."*approved BP*", C.NMI, C.BUSINESSPARTNER, C.TYPE, C.STATE, C.STATUS, C.COMPANY
    order by STATUS
        """.format(user=user)

    df2 = pd.read_sql(sql, engine)
    t_sql_code_1 = time.time()

    t_exportfile_code_0 = time.time()
    today = datetime.today().date()

    path_output_file = path_output + "/Full VPPSA Site List V3 outputfile {datetime}.xlsx".format(
        datetime=today)

    df2.to_excel(path_output_file)
    t_exportfile_code_1 = time.time()

    category_all = df2['nmi'].nunique()
    category_1 = df2.groupby('status')['nmi'].nunique()['1_CURRENT']
    category_2 = df2.groupby('status')['nmi'].nunique()['2_PowerDirect']
    category_3 = df2.groupby(
        'status')['nmi'].nunique()['3_LeftVPP_New_NonAGL_Customer']
    category_4 = df2.groupby(
        'status')['nmi'].nunique()['4_LeftVPP_New_AGL_Customer']

    ##log
    f = open("P:/New Energy/Churn Moveout Report/LOG_RUN.txt", "a+")
    f.write("%s, %s, %s, %s, %s\n" %
            (time.strftime("%x, %X"), len(df2),
             t_preliminary_1 - t_preliminary_0, t_sql_code_1 - t_sql_code_0,
             t_exportfile_code_1 - t_exportfile_code_0))
    f.close()

    if category_2 + category_3 + category_4 > 0:

        message = mailer.Message()

        message.From = sender_email
        message.To = [reciever_emails]
        message.Subject = 'VPPSA move and Churn Report on {datetime}'.format(
            datetime=today)
        message.Body = '''Hi all,
            
            On {today_date}, from {category_all_num} unique NMIs in the VPP list, {category_2_num} NMIs are identified as 2_PowerDirect, {category_3_num} NMIs are identified as 3_VPPChurn_New_NonAGL_Customer , {category_4_num} NMIs are identified as 4_VPPChurn_New_AGL_Customer, and %s NMIs are identified as 1_Current. 
            The report is attached to this email and can be find at {path_output_file_loc}.
            
            Definition of Flags:
            1_CURRENT: The Business partner ID in the VPPSA list is the same as the current active Business partner ID at that NMI.
            2_PowerDirect: The Business partner ID in the VPPSA list is the same as the current active Business partner ID at that NMI, but their COMPANY is power direct. 
            3_LeftVPP_New_NonAGL_Customer: The Business partner ID in the VPPSA list  has left that NMI and the new occupant at that NMI is not an AGL customer.
            4_LeftVPP_New_AGL_Customer: The Business partner ID in the VPPSA list  has left that NMI, but the new occupant at that NMI is still an AGL customer.
        
       
            If you have any questions please let me know.
            
            Kind regards,
            
            Javad'''.format(today_date=today,
                            category_all_num=category_all,
                            category_2_num=category_2,
                            category_3_num=category_3,
                            category_4_num=category_4,
                            category_1=category_1,
                            path_output_file_loc=path_output_file)

        message.attach(path_output_file)

        sender = mailer.Mailer('aglsmtp05.agl.com.au')

        sender.send(message)

    return ()
Example #28
0
def main():
    locale.setlocale(locale.LC_ALL, '')
    logfmt = "%(asctime)s %(levelname)s: %(message)s"
    logging.basicConfig(format=logfmt, level=logging.WARNING)

    parser = argparse.ArgumentParser(
        description="Bot d'actualisation pour Paul Emploi")
    parser.add_argument("cfgfile",
                        metavar="configfile",
                        help="Fichier de configuration")
    parser.add_argument("--user",
                        "-u",
                        metavar="PEusername",
                        help="Compte Pôle Emploi configuré à utiliser")
    parser.add_argument("--work",
                        "-w",
                        metavar="worklog",
                        help="Fichier des heures travaillées")
    parser.add_argument("--no-error-mail",
                        action="store_true",
                        help="N'envoie pas de mail pour les erreurs")
    parser.add_argument("--verbose",
                        "-v",
                        action="count",
                        help="Augmente le niveau de verbosité")

    args = parser.parse_args()

    configpath = args.cfgfile
    peuser = args.user
    verbose = args.verbose
    workfile = args.work
    errormail = not args.no_error_mail

    if verbose is not None:
        loglevels = ["WARNING", "INFO", "DEBUG", "NOTSET"]
        verbose = min(len(loglevels), verbose) - 1
        logging.getLogger().setLevel(loglevels[verbose])

    logging.info("Reading config file %s", configpath)
    config = configparser.ConfigParser()
    config.read(configpath)

    smtphost = config["SMTP"]["smtphost"]
    smtpport = config["SMTP"].get("smtpport")
    smtpuser = config["SMTP"].get("smtpuser")
    smtppassword = config["SMTP"].get("smtppwd")
    mailsender = mailer.Mailer(smtphost, smtpport, smtpuser, smtppassword)

    if peuser is None:
        section = next(s for s in config.sections()
                       if s.startswith("Account."))
    else:
        section = "Account." + peuser

    logging.info("Using account section %s", section)
    peuser = config[section]["username"]
    pepwd = config[section]["password"]
    emailaddr = config[section]["email"]

    try:
        dostuff(mailsender, emailaddr, peuser, pepwd, workfile)
    except KeyboardInterrupt:
        raise
    except:
        logging.exception("Top-level exception:")
        if not errormail:
            raise

        msg = "Exception caught while trying to run the \"actualisation\".\n\n"
        msg += traceback.format_exc()
        mailsender.error(smtpuser, msg)
Example #29
0
def main():
    global clientF, vmF, mailerF, protectiongroups, config, group_node_relation, debug, send_group_relation_report, protectedVMS, error_sender, report_sender, maildomain, mailserver, baseurl, send_syntax_errors
    if is_networker_available():
        mailerF = mailer.Mailer(debug, error_recipient, mailserver,
                                error_sender, report_sender, maildomain, "",
                                send_syntax_errors)
        mailerF.config = config
        try:
            buildFrequencyMapping()
            buildLocationMapping()
            clientF = client.Client(
                locations, frequency, config['networker_urls'], headers,
                baseurl, mailerF
            )  # Creates an object of the class Client for using all managing functions
            getProtectionGroups()
            vmF = virtual_machine.VirtualMachine(
                config['networker_urls'], baseurl, headers, mailerF,
                protectiongroups
            )  # Creates an object of the class Client for using all managing functions
            clientF.getClients()
            for directorie, subdirs, filenames in os.walk(os.getcwd()):
                if isInIgnoreList(directorie) == False:
                    if "archive" not in directorie:
                        for filename in filenames:
                            if ".yaml" in filename:
                                try:
                                    yamlD = yaml.load(
                                        open(directorie + "/" + filename, 'r'))
                                    if yamlD != None and 'Client' in yamlD:
                                        for x in range(0,
                                                       len(yamlD['Client'])):
                                            try:
                                                location = ""
                                                if "location" in yamlD[
                                                        'Client'][x]:
                                                    location = locations[
                                                        yamlD['Client']
                                                        [x]['location'].lower(
                                                        )] + "_"
                                                group = yamlD['Client'][x][
                                                    'retentionclass'] + "_VM_" + location + frequency[
                                                        yamlD['Client']
                                                        [x]['frequency'].lower(
                                                        )] + yamlD['Client'][
                                                            x]['starttime']
                                                if yamlD['Client'][x][
                                                        'backupType'] == "VM":
                                                    protectedVMS += 1
                                                    result = vmF.searchForVM(
                                                        yamlD['Client'][x]
                                                        ['hostname'],
                                                        yamlD['Client'][x],
                                                        False)
                                                    if result != None:
                                                        if vmF.isVmAlreadyKnown(
                                                                group,
                                                                result['uuid']
                                                        ) == False:
                                                            vmF.addVM(
                                                                result['uuid'],
                                                                group, result[
                                                                    'vCenter'],
                                                                yamlD['Client']
                                                                [x])
                                                            createGroupNode_Assoziation(
                                                                yamlD['Client']
                                                                [x], group)
                                                else:
                                                    if clientF.clientExists(
                                                            yamlD['Client']
                                                        [x]):
                                                        createGroupNode_Assoziation(
                                                            yamlD['Client'][x],
                                                            group)
                                                    else:
                                                        print(
                                                            "Node " +
                                                            yamlD['Client'][x]
                                                            ['hostname'] +
                                                            " not known, trying to create backup entry"
                                                        )
                                                        clientF.createClient(
                                                            yamlD['Client'][x])
                                                        createGroupNode_Assoziation(
                                                            yamlD['Client'][x],
                                                            group)
                                            except:
                                                mailerF.send_error_mail(
                                                    str(traceback.format_exc())
                                                    + " NODE: " +
                                                    yamlD['Client'][x]
                                                    ['hostname'])
                                except:
                                    mailerF.send_error_mail(
                                        str(traceback.format_exc()))
                    else:
                        doArchive(directorie)
            if send_group_relation_report.lower() == 'true':
                mailerF.send_group_node_relation_mail(group_node_relation)
            print("Number of processed vms: " + str(protectedVMS))
        except:
            print("something went wrong")
            print("sending error message to developer maurice fernitz")
            mailerF.send_error_mail(str(traceback.format_exc()))
    else:
        print("ERROR: please check if the ntworker is available")
    if row == None:
        result = "no account with that e-mail"
    else:
        uname = row[0]
        lastReset = row[1]

        newPass = randomString()
        crypt_pass = hashlib.sha1(dbInfo.DB_KEY3 + newPass).hexdigest()

        if (lastReset == None
                or ghShared.timeAgo(lastReset).find("minute") == -1):
            message = mailer.Message()
            message.From = "*****@*****.**"
            message.To = email
            message.Subject = "Galaxy Harvester password reset"
            message.Body = "Hello " + uname + ",\n\nYour password for galaxyharvester.net has been reset to:\n\n" + newPass + "\n\n go to http://galaxyharvester.net to login.\n"
            mailer = mailer.Mailer(mailInfo.MAIL_HOST)
            mailer.login(mailInfo.MAIL_USER, mailInfo.MAIL_PASS)
            mailer.send(message)
            cursor.execute('UPDATE tUsers SET userPassword="******", lastReset=NOW() WHERE userID="' + uname + '";')
            result = 'email sent'
        else:
            result = 'You can only reset your password 1 time per hour.'

    cursor.close()
    conn.close()

print "Content-Type: text/html\n"
print result