示例#1
0
    def mail(obj,confidence):
        import sendmail
        import tzctl
        import smtplib

        logging.debug('sending notification email')

        try:
            subject = sendmail.subjects['object_detected']
            message = sendmail.messages['object_detected']
            format_dict = {
                'camera': camera_config['@name'],
                'hostname': socket.gethostname(),
                'moment': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'object': obj,
                'confidence': confidence,
            }
            if settings.LOCAL_TIME_FILE:
                format_dict['timezone'] = tzctl.get_time_zone()

            else:
                format_dict['timezone'] = 'local time'

            message = message % format_dict
            subject = subject % format_dict

            old_timeout = settings.SMTP_TIMEOUT
            settings.SMTP_TIMEOUT = 10
            sendmail.send_mail(data['smtp_server'], int(data['smtp_port']), data['smtp_account'],
                               data['smtp_password'], data['smtp_tls'], data['from'], [data['addresses']],
                               subject=subject, message=message, files=[])

            settings.SMTP_TIMEOUT = old_timeout

            self.finish_json()

            logging.debug('notification email succeeded')

        except Exception as e:
            if isinstance(e, smtplib.SMTPResponseException):
                msg = e.smtp_error

            else:
                msg = str(e)

            msg_lower = msg.lower()
            if msg_lower.count('tls'):
                msg = 'TLS might be required'

            elif msg_lower.count('authentication'):
                msg = 'authentication error'

            elif msg_lower.count('name or service not known'):
                msg = 'check SMTP server name'

            elif msg_lower.count('connection refused'):
                msg = 'check SMTP port'

            logging.error('notification email failed: %s' % msg, exc_info=True)
            self.finish_json({'error': str(msg)})
示例#2
0
def enviar_email(remitente,
                 destinatarios,
                 asunto,
                 mensaje,
                 servidor,
                 login,
                 password,
                 ficheros=[],
                 html='',
                 cc=[],
                 bcc=[],
                 charset='iso-8859-1'):

    send_mail(remitente,
              destinatarios,
              asunto,
              mensaje,
              servidor,
              login,
              password,
              files=ficheros,
              html=html,
              cc=cc,
              bcc=bcc,
              charset=charset)
示例#3
0
文件: main.py 项目: niu2x/birthday
def main():
	now = time.localtime()
	now = datetime.datetime(now.tm_year, now.tm_mon, now.tm_mday)
	lunar_now = lunar.get_lunar_date(now)
	now = (now.year, now.month, now.day)
	
	log('now', now)
	log('lunar_now', lunar_now)

	personGroup = []

	sql1 = 'select name, sex, birthday, calendar, mail from person where birthday="%04d-%02d-%02d" and calendar="阳历"' % (now[0], now[1], now[2])
	sql2 = 'select name, sex, birthday, calendar, mail from person where birthday="%04d-%02d-%02d" and calendar="阴历"' % (lunar_now[0], lunar_now[1], lunar_now[2])
	for sql in (sql1, sql2):
		db.select(sql, lambda item:personGroup.append({'name':item[0],'sex':item[1],'birthday':item[2],'calendar':item[3],'mail':item[4]}))
	
	init_template_pathname_group()

	for person in personGroup:
		templatePathname = random.choice(templatePathnameGroup)
		template = Template(open(templatePathname, 'rt').read())
		text = template.render(person = create_person(
				person['name'],
				person['sex'],
				person['birthday'],
				person['calendar'],
				person['mail'],
				now,
				lunar_now
			) 
		)
		send_mail('*****@*****.**', person['mail'], 'Happy Birthday To You!', text)
示例#4
0
def mail(report, host):
    names, emails = sendmail.get_contacts(CONTACTS)
    message_template = sendmail.read_template(MAIL_TEMPL)
    message = 'Ha cambiado la configuración del router' + host + ':' + '\n' + ''
    sendmail.write_template(message, report, MAIL_TEMPL)
    sendmail.send_mail(names, emails, message_template, 'Notificación SNMP',
                       MAIL_TEMPL)
示例#5
0
def send(cfg):
    from_address = cfg.get('smtp', 'FROM')
    to_address = cfg.get('smtp', 'TO')
    subject = cfg.get('smtp', 'SUBJECT')
    text = cfg.get('smtp', 'TEXT')
    file = cfg.get('smtp', 'PATH') + cfg.get('excel', 'WB_NAME')
    password = cfg.get('smtp', 'PASS')

    send_mail(from_address, to_address, subject, text, password, [file])
示例#6
0
def analysis_data():
    # print content
    pattern = '>Resets: (\d{4}-\d{2}-\d{2})<.*>(\d*\.?\d*)/(\d*) GB'
    #print type(content)
    info = re.search(pattern, str(content))
    deadline, used = info.groups()[0], info.groups()[1]
    print '已用 %s GB' % used
    sendmail.send_mail(sender, pwd, recipient, 'BWG used %s GB' % used,
                       '%s到期,已用%sGB' % (deadline, used))
    print 'email send'
示例#7
0
def notific(message, lines):
    report = open('report', "w")
    report.write(message)
    report.close()
    names, emails = sendmail.get_contacts(CONTACTS)
    message_template = sendmail.read_template(MAIL_TEMPL)
    #message = 'Ha cambiado la configuración del router'+host+':'+'\n'+''
    sendmail.write_template(message, 'report', MAIL_TEMPL)
    sendmail.send_mail(names, emails, message_template, 'Notificación SNMP',
                       MAIL_TEMPL, message)
示例#8
0
def send_email(to, subject, template):
    '''
    msg = Message(
        subject,
        recipients=[to],
        html=template,
        sender=app.config['MAIL_DEFAULT_SENDER']
    )
    mail.send(msg)
    '''
    send_mail(subject=subject, mailto=to, content=template, attachments=None)
示例#9
0
def test():
    if request.method == 'POST':
        s = request.form.get('tos')
        tos = s.split(',')
        content = request.form.get('content')
        subject = request.form.get('subject')
        send_mail(tos, subject, content)
        return jsonify({'resp': status})
    elif request.method == 'GET':
        return jsonify({'resp': error})
    else:
        return 'no data'
示例#10
0
def main():
    # mail smtp
    sender = u'*****@*****.**'
    subject = u'鹏博士机房ceph集群每日运行状态报告'
    session = smtp_conn('smtp.163.com', 25,
                        '*****@*****.**',
                        'xxxxxxxxxxx')

    content = get_ceph()
    if content:
        body = format_output(format_info(content))
        send_mail(session, 'html', sender, ['*****@*****.**'], subject, body)
示例#11
0
文件: wsgi.py 项目: yaojunru/mail-sms
def test():
    if request.method == 'POST':
        s = request.form.get('tos')
        tos = s.split(',')
        content = request.form.get('content')
        subject = request.form.get('subject')
        send_mail(tos,subject,content)
        return jsonify({'resp':status})
    elif request.method == 'GET':
        return jsonify({'resp':error})
    else:
        return 'no data'
示例#12
0
def ssh_commnd(ip, port, username, passwd, redisbak_src, redisbak_dst,
               redis_port):
    save_time = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S-%f")
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, passwd)

    dump_dst = redisbak_dst + '/dump.rdb_' + ip + '_' + str(
        redis_port) + '_' + save_time
    appendonly_dst = redisbak_dst + '/appendonly.aof_' + ip + '_' + str(
        redis_port) + '_' + save_time

    dump_save = 'cp ' + redisbak_src + '/dump.rdb ' + dump_dst
    appendonly_save = 'cp ' + redisbak_src + '/appendonly.aof ' + appendonly_dst

    stdin, stdout, stderr = ssh.exec_command(dump_save)
    dump_status = 'succeed'

    for i in stderr.readlines():
        dump_status = i

    if dump_status == 'succeed':
        success_conment = ip + '_' + redis_port + ' Redis dump.db persistent file backup successfully'
        log_write(access_log, ip, success_conment)
    else:
        faild_conment = ip + '_' + redis_port + local_ip + ' Redis dump.db persistence failed to backup file'
        log_write(log, dump_status, faild_conment)
        send_mail(mail_host, mail_user, mail_pass, mail_postfix,
                  mail_addresser, to_list, 'reid_dump_bak_fiaid',
                  faild_conment)

    stdin, stdout, stderr = ssh.exec_command(appendonly_save)
    appendonly_status = 'succeed'
    for i in stderr.readlines():
        appendonly_status = i

    if appendonly_status == 'succeed':
        success_conment = ip + '_' + redis_port + ' Redis appendonly.aof persistent file backup successfully'
        log_write(access_log, ip, success_conment)
    else:
        faild_conment = ip + '_' + redis_port + local_ip + ' Redis appendonly.aof persistence failed to backup file'
        log_write(log, appendonly_status, conment)
        send_mail(mail_host, mail_user, mail_pass, mail_postfix,
                  mail_addresser, to_list, 'Redis_appendonly_bak_fiaid',
                  faild_conment)

    ssh.close()

    result_list = []
    result_list.append(dump_status)
    result_list.append(appendonly_status)

    return result_list
示例#13
0
def send_tele_msg():
    username, emailid, message = request.json.get(
        'userName'), request.json.get('emailId'), request.json.get('message')
    chat_id = 158775078

    text = f"""*Name*: {username}\n*MailID*: {emailid}\n*Message*:\n{message}"""

    res = tele_bot.send_message(chat_id=chat_id,
                                text=text,
                                parse_mode=telegram.ParseMode.MARKDOWN)

    sendmail.send_mail(username, emailid, text)
    return {'status': True}
示例#14
0
	def POST(self):
		web.header('Content-type','text/html')

		yield """<!DOCTYPE html>
<html><head><title>Reimbursement Mailer</title></head>
<body onload="window.scrollTo(0, document.body.scrollHeight)">Loading..."""

		expenses = list(db.select('expense', where="type='reimbursement' AND completed=0"))

		# finance office emails
		table = """<table border="1" style="border-collapse: collapse">
<tr><th>Date</th><th>Student</th><th>Email</th><th>Group(s)</th><th>Amount</th><th>Petty Cash</th></thead>"""
		keyfunc = lambda x : x.student
		for student_id, student_expenses in itertools.groupby(sorted(expenses, key=keyfunc), keyfunc):
			student = db.select('student', {"id": student_id}, where="id=$id")[0]
			clubs = []
			total = 0
			for expense in student_expenses:
				club = get_club_by_expense(expense)
				clubs.append(club.name)
				total += expense.amount

			table += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (
				time.strftime("%Y/%m/%d", time.localtime(expense.date)),
				student.name,
				student_email(student.id),
				"/".join(set(clubs)),
				currency(total, parens = False),
				"Yes" if abs(total) <= 2500 else "No")
		table += "</table>"
		msg="""
<p>The following student reimbursements are being submitted:</p>

%s

<p>Reply to this email if you have any followup questions.</p>

<p>Thanks!<br>
SAO Finance</p>
""" % (table,)
		try:
			# send financial services mails
			sendmail.send_mail(sender="SAO Mailer <*****@*****.**>",
				to=[finance_email],
				cc=["*****@*****.**", "SAO Mailer <*****@*****.**>"],
				subject="Reimbursements Report " + time.strftime("%m/%d/%Y"),
				body=msg,
				html = True)
		except Exception, e:
			yield "<h1>ERROR IN SENDING MAIL: " + str(e) + "</h1>"
			raise e
示例#15
0
文件: test.py 项目: ma6174/webmail
 def GET(self,name):
     logger.info(name)
     info = urllib.unquote(name).split('/')
     info = [i for i in info if i != '']
     if len(info) < 3:
         return webmail.__doc__
     try:
         print ''
         send_mail(info[:-2],info[-2],info[-1])
     except:
         return 'Failed Send Mail'
     print info
     render = web.template.render('./')
     return render.pages(info[:-2],info[-2],info[-1])
示例#16
0
def Notice(config, msg):

    content = ''
    content += '[Project]: ' + config['Project_name'] + '\n'
    content += '[server address]:%s\n' % config['server_address']
    content += msg + '\n'
    content += '''

=================================================
这是一封自动转发的邮件,用来通知大家服务器是否有更新,
如果有任何问题,请联系智刚。
=================================================
    '''
    send_mail(config['mailto_list'], config[
              'Project_name'] + u"代码有更新", content)
示例#17
0
def main():

    try:
        for dirpath, dirnames, files in os.walk(FILE_PATH):
            for i in files:
                file = dirpath + i
                try:
                    LOGGER.info("Transferring file: " + i)
                    insert_csv(file, i)
                except Exception, e:
                    LOGGER.error(e)
                    send_mail(SENDER, RECEIVERS, e)
                finally:
                    os.remove(file)
                LOGGER.info("File successfully removed from " + FILE_PATH + "\n" + "-" * 80)
示例#18
0
def main():
    global mail_content,port
    try:
        mail_content+="begin time: "+time.strftime("%Y-%m-%d %H:%M:%S")+"\n" 
        if len(port) == 1:
            backup(port[0])
        else:       
            for p in port:
                backup(p) 
        mail_content+="end time: "+time.strftime("%Y-%m-%d %H:%M:%S")+"\n"
        file_clear()    
        disk_info() 
        sendmail.send_mail(mailto_list, "mysqlbackup report for "+server, mail_content)    
    except Exception,ex:
        print ex
示例#19
0
def insert_csv(file, filename):
    try:
        cnx = mysql.connector.connect(user=USER, password=PASSWORD, host=HOST, database=DB, port=DB_PORT)
        cursor = cnx.cursor()
        with open(file, "rb") as f:
            thedata = f.read()
        curr_datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql = "INSERT INTO wyko_file(wyko_file,file_name,date_inserted) VALUES (%s,%s,%s)"
        cursor.execute(sql, (thedata, filename, curr_datetime))
        if cursor.rowcount != 0:
            LOGGER.info("Transfer to database succesful!")
            cnx.commit()
    except (MySQLdb.OperationalError, MySQLdb.ProgrammingError), e:
        LOGGER.error(e)
        send_mail(SENDER, RECEIVERS, e)
示例#20
0
def test():
    html = ent_place.get(1.0, END)
    title = ent_title.get(1.0, END)
    number = ent_number.get(1.0, END)
    email = ent_email.get(1.0, END)
    password = ent_password.get(1.0, END)
    print(email, password)
    try:
        s.send_mail(html, root.filename, title, number, email, password)
        start_label = Label(root, text="Рассылка успешно доставлена")
        start_label.pack()
    except:
        start_label = Label(
            root, text="Что-то не вписала или не добавила Excel файл!!!")
        start_label.pack()
示例#21
0
    async def handle_DATA(self, server: SMTP, session: Session,
                          envelope: Envelope) -> str:
        signal_numbers = []
        mail_addresses = []
        for addr in envelope.rcpt_tos:
            # a real email address cannot start with a special char
            if addr.startswith("+"):
                signal_numbers.append(addr)
            else:
                mail_addresses.append(addr)

        # send signal message if required
        if len(signal_numbers) > 0:
            print("Forwarding message to signal")
            success = await self.send_signal(envelope, signal_numbers)

            if not success:
                return "554 Sending signal message has failed"

        # send email if required
        if len(mail_addresses) == 0:
            return "250 Message accepted for delivery"
        else:
            envelope.rcpt_tos = mail_addresses

            print(
                f"Sending email via MTA. From: {envelope.mail_from} To: {envelope.rcpt_tos}"
            )
            return send_mail(
                self.config["smtp_host"],
                int(self.config["smtp_port"]),
                self.config["smtp_user"],
                self.config["smtp_passwd"],
                envelope,
            )
示例#22
0
	def post(self):
		global xmyUri 
		email=self.get_argument("user_email")
		"""check if user exists"""
		if (not self.dbManager.check_user_exist(email)) or (self.dbManager.check_user_activated(email) and xmyUri != "/auth/login/forgetpasswd"):
			"""Show no users"""
			xmyUri = ''
			self.redirect("/")
			return
		link=self.genLink(email)
		message="Please click "+self.webaddress+link+" to activate your account"
		#db.insert(link,email,date)
		self.dbManager.set_activate_events(email,link)
		sendmail.send_mail(email,"Activate your account",message)
		xmyUri = ''
		self.redirect("/")
示例#23
0
def doFunc(logfile):
    mailto_list=['******@qq.com','********@qq.com']#收邮件人列表
    #record_log(logfile,'有','邮件投递成功')
    time.sleep(doFirst())
    xtfw=urlread.getxtfw()
    jwzx=urlread.getjwzx()
    dy2018=urlread.getdy2018()
    ismessage=(int(xtfw!='')|int(jwzx!='')|int(dy2018!=''))
    content=''#清空变量
    if int(jwzx!=''):
        content=('<p>以下是今天的教务在线更新信息:</p>%s<p>&nbsp;</p>' %jwzx) #<p></p>
    if int(xtfw!=''):
        content=('%s<p>以下是今天的“校园综合协调服务管理平台”最新信息:</p>%s<p>&nbsp;</p>' %(content,xtfw))
        content=('%s<p><a href="http://202.118.201.228/homepage/index.do">教务在线首页</a></p>'%content)
    if int(dy2018!=''):
        content=('%s<p>电影天堂电影更新:</p>%s<p>&nbsp;</p>' %(content,dy2018))

    if ismessage:
        content=('%s<p><a href="mailto:*******@qq.com">如需取消,请点这里</a></p>'%content)
        content=('%s<p>***********</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;By wxj</p>'%content)
        
        #print(content)

        if sendmail.send_mail(mailto_list,"教务在线有新消息了!",content,'html'):
            #print ("邮件投递成功")
            record_log(logfile,ismessage,'邮件投递成功')
        else:  
            #print ("邮件投递失败")
            record_log(logfile,ismessage,'邮件投递失败')
        #print ("do well!")
    else:
        record_log(logfile,ismessage,'无邮件投递')
示例#24
0
文件: app.py 项目: Didilya/mireviews
def submit():  # user submiting form
   if request.method == 'POST':
      customer = request.form['customer']
      dealer = request.form['dealer']
      rating = request.form['rating']
      comments = request.form['comments']
      # print(customer, dealer, rating, comments)
      if customer == '' or dealer =='':
         return render_template('index.html', message='PLEASE enter info')
      if db.session.query(Feedback).filter(Feedback.customer == customer).count() == 0:
         data = Feedback(customer, dealer, rating, comments)
         db.session.add(data)
         db.session.commit()
         send_mail(customer, dealer, rating, comments)
         return render_template('success.html')
      return render_template('index.html', message='you already submitted feedback')
示例#25
0
文件: report.py 项目: oyytoy/stock
def select_2():

    alias = ["经纪人/渠道", "姓名", "股票代码", "委托时间", "委托方向", "委托币种", "委托价格", "已成交数量"]
    sql = """
          SELECT IFNULL(c.name,d.channel_name) 经纪人,b.name 姓名,stock_code 股票代码
           ,entrust_datetime 委托时间,CASE WHEN entrust_bs=0 THEN '买' WHEN entrust_bs=1 THEN '卖' WHEN entrust_bs=2 THEN 'short' END 委托方向
           ,CASE WHEN currency=0 THEN '港币' WHEN currency=1 THEN '美金' WHEN currency=2 THEN '人民币' END 委托币种
           ,CASE WHEN entrust_order_type=1 THEN latest_filled_price WHEN entrust_order_type!=1 THEN entrust_price END 委托价格
           ,filled_amount 已成交数量  FROM trade_entrust_order a LEFT JOIN customer_info b ON a.customer_no=b.customer_no 
           LEFT JOIN broker_info c ON  b.broker_id = c.id
           LEFT JOIN channel_info d ON b.channel_id=d.channel_id WHERE    a.local_order_type = 0 AND a.is_preview_order = 1 AND a.filled_amount!=0
    """

    db.query(sql, alias, '全量.csv')

    sendmail.send_mail(to_mail_list, u'全量.csv')
示例#26
0
def main():
    global mail_content
    try:
        if time.strftime("%H") == "00":
            back_type = 1
        else:
            back_type = 0
        mail_content += "begin time: " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
        backup(back_type)
        mail_content += "end time: " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n"
        file_clear()
        # print mail_content
        # disk_info()
        sendmail.send_mail(mailto_list, "mysqlbackup report for " + server, mail_content)
    except Exception, ex:
        print ex
示例#27
0
def send_stat():

    hh = humannum.humannum

    content = '<body>'
    content += ('<h2> Summary: </h2>'
                '<p> <b>uploaded bytes</b>: {bytes_uploaded} </p>'
                '<p> <b>uploaded files</b>: {uploaded_files} </p>'
                '<p> <b>uploaded speed</b>: {uploaded_speed} / s </p>'
                '<p> <b>start at</b>      : {start_time} </p>'
                '<p> <b>end at</b>        : {end_time} </p>'
                '<p> <b>spend</b>        : {spend} seconds </p>'
                '<p>  </p>').format(
                    bytes_uploaded=hh(stat['bytes_uploaded']),
                    uploaded_files=stat['uploaded_files'],
                    uploaded_speed=hh(stat['uploaded_speed']),
                    start_time=time.strftime(
                        '%Y-%m-%d %H-%M-%S',
                        time.localtime(stat['start_time'])),
                    end_time=time.strftime('%Y-%m-%d %H-%M-%S',
                                           time.localtime(stat['end_time'])),
                    spend=int(stat['end_time'] - stat['start_time']),
                )

    failed_num = len(stat['failed_files'])

    if failed_num > 0:
        content += ('<h2> Failed Files: '
                    '<b style="color:red;">{n}</b></h2>').format(n=failed_num)

        for file_name, error in stat['failed_files'].items():
            content += ('<h4> {file_name} : </h4>'
                        '<p> {error} </p>').format(
                            file_name=file_name,
                            error=error,
                        )
    content += '</body>'

    subject = '[{tag}] Baishan Storage Daily Report {daily}'.format(
        tag='INFO' if failed_num <= 0 else 'WARN',
        daily=time.strftime('%Y-%m-%d', time.localtime()),
    )

    try:
        sendmail.send_mail(['*****@*****.**'], subject, content)
    except Exception as e:
        logger.exception(repr(e))
示例#28
0
def downECMWFdata(productname, **kwargs):
    '''
    Only available in UNIX-platform, tested on CentOS.
    :param productname:
    :param kwargs:
    :return:
    '''
    from ecmwfapi import ECMWFDataServer
    server = ECMWFDataServer()
    # try to get the required key-values, or throw exception
    startdate = datetime.datetime.today()
    enddate = datetime.datetime.today()
    try:
        startdate = kwargs["startdate"]
        enddate = kwargs["enddate"]
        outpath = kwargs["workspace"]
    except KeyError:
        print ("downECMWFdata function must have the statdate, enddate, and workspace args.")
    savepath = outpath + os.sep + "ei-interim-sfc-oper-fc-%s.nc"
    tmpdate = startdate.replace(day = 1)
    enddate = enddate.replace(day = 1)
    while tmpdate <= enddate:
        deltadays = GetDayNumber(tmpdate.year, tmpdate.month) - 1
        tmpenddate = tmpdate + datetime.timedelta(days = deltadays)
        datestring = tmpdate.strftime("%Y%m%d") + '/to/' + tmpenddate.strftime("%Y%m%d")
        print (datestring)
        tmpsavepath = savepath % (datestring.replace('/to/', '-'))
        if os.path.exists(tmpsavepath):
            tmpdate = tmpenddate + datetime.timedelta(days = 1)
            continue
        server.retrieve({
            "class"  : "ei",
            "dataset": "interim",
            "date"   : datestring,
            "expver" : "1",
            "grid"   : "0.75/0.75",
            "levtype": "sfc",
            "param"  : "50.128/142.128/143.128/167.128/228.128/239.128",
            "step"   : "3/6/9/12",
            "stream" : "oper",
            "time"   : "00:00:00/12:00:00",
            "type"   : "fc",
            "format" : "netcdf",
            "target" : tmpsavepath,
        })
        send_mail('zlj', 'zlj', "ECMWF Download report", "%s have been done!" % datestring)
        tmpdate = tmpenddate + datetime.timedelta(days = 1)
示例#29
0
def analyze_mysql_processlist(cur_dbmon):
    mail_text = ''
    table_head = '''
<table border="1" width="100%">
<tr><th colspan="8">Mysql Active Processlist</th></tr>
'''
    table_body = ''
    processlist_active_warning = 0
    longquery_second = 0

    try:
        sql = "select host,port,create_time,count(*) cnt from mysql_processlist group by host,port,create_time"
        cur_dbmon.execute(sql)
        g_result = cur_dbmon.fetchall()

        for g_line in g_result:
            sql = "select tags,p_user,p_host,p_db,command,time,status,info from mysql_processlist a where a.host='%s' and a.port='%s' and a.create_time='%s' " % (
                g_line[0], g_line[1], g_line[2])
            cur_dbmon.execute(sql)
            result = cur_dbmon.fetchall()

            if int(g_line[3]) >= processlist_active_warning:
                table_body += "<tr><td colspan='8'>DBInstanceId:%s | DBPORT:%s | CreateTime:%s | Active process number is %d.</td></tr>\n" % tuple(
                    g_line)
                table_body += "<tr><td>TAGS</td><td>USER</td><td>CLIENT</td><td>DB</td><td>COMMAND</td><td>TIME</td><td>STATE</td><td>INFO</td></tr>\n"
                for line in result:
                    table_body += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % tuple(
                        line)
            else:
                table_head_tmp = ''
                table_body_tmp = ''
                table_head_tmp += "<tr><td colspan='8'>DBInstanceId:%s | DBPORT:%s | CreateTime:%s | Long query</td></tr>\n" % tuple(
                    g_line[0:3])
                table_head_tmp += "<tr><td>TAGS</td><td>USER</td><td>CLIENT</td><td>DB</td><td>COMMAND</td><td>TIME</td><td>STATE</td><td>INFO</td></tr>\n"

                for line in result:

                    if line[6] > longquery_second:
                        table_body_tmp += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % tuple(
                            line)

                if table_body_tmp:
                    table_body += table_head_tmp + table_body_tmp

            sql = "insert into mysql_processlist_history (server_id,host,port,tags,pid,p_user,p_host,p_db,command,time,status,info,create_time) select server_id,host,port,tags,pid,p_user,p_host,p_db,command,time,status,info,create_time from mysql_processlist where host='%s' and port='%s' and create_time='%s'" % (
                g_line[0], g_line[1], g_line[2])
            cur_dbmon.execute(sql)

            sql = "delete from mysql_processlist where host='%s' and port='%s' and create_time='%s'" % (
                g_line[0], g_line[1], g_line[2])
            cur_dbmon.execute(sql)

        if table_body:
            mail_text += table_head + table_body + "</table>"
        #print mail_text
        result = sendmail.send_mail("*****@*****.**", "mail_subject", mail_text)
    except Exception, e:
        print e
        print "analyze mysql processlist got error"
示例#30
0
 def GET(self):
     pars = web.input()
     username = pars['username']
     rt = db.query('select * from user where username=$aa', vars={'aa':username})
     for r in rt:
         email = r['email']
         from sendmail import send_mail
         return send_mail(email, 'checkmail', 'please checkmail http://localhost:8080/checkingmail')
def main():
    if check_mail():
        output = subprocess.check_output(
            "kubectl get pods|awk 'NR>1{print $3}'", shell=True)
        lines = output.split('\n')
        for item in lines[0:-1]:
            print(item)
            if item != "Running":
                sendmail.send_mail('*****@*****.**', 'wsy123456',
                                   '*****@*****.**',
                                   "Message from 112.35.6.145",
                                   "Error pod status in 112.35.6.145")
                break
            else:
                pass
    else:
        print("sendmail module is not exists,please check it...")
示例#32
0
def analyze_mongodb_currentop(cur_dbmon):
    mail_text = ''
    table_head = '''
<table border="1" width="100%">
<tr><th colspan="11">Mongodb Active Processlist</th></tr>
'''
    table_body = ''

    try:
        #sql = "select a.ServerId,b.Host,b.Description,a.CreateTime,count(a.id) cnt from mongodb_current_op a,mongodb_list b  where a.ServerId=b.Id group by a.ServerId,a.CreateTime"
        sql = "select a.host,a.port,a.CreateTime,count(*) cnt,a.uuid from mongodb_current_op a group by a.host,a.port,a.uuid"
        processlist_active_warning = 0
        longquery_second = 0
        cur_dbmon.execute(sql)
        g_result = cur_dbmon.fetchall()

        for g_line in g_result:
            sql = "select a.Op_desc ,a.Secs_running ,a.Op ,a.Ns ,a.Op_query ,a.Op_insert ,a.Client ,a.Msg ,a.Locks ,a.WaitingForLock ,a.LockStats from mongodb_current_op a where a.host = '%s' and a.port='%s'  and a.uuid = '%s'" % (
                g_line[0], g_line[1], g_line[4])
            cur_dbmon.execute(sql)
            result = cur_dbmon.fetchall()

            if int(g_line[3]) >= processlist_active_warning:
                table_body += "<tr><td colspan='11'>Server:%s | DB_PORT:%s | ServerTime:%s | Active process number is %d.</td></tr>\n" % tuple(
                    g_line[0:4])
                table_body += "<td>Op_desc</td><td>Secs_running</td><td>Op</td><td>Ns</td><td>Op_query</td><td>Op_insert</td><td>Client</td><td>Msg</td><td>Locks</td><td>WaitingForLock</td><td>LockStats</td></tr>\n"
                for line in result:
                    table_body += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % tuple(
                        line)
            else:
                table_head_tmp = ''
                table_body_tmp = ''
                table_head_tmp += "<tr><td colspan='11'>Server:%s | DB_PORT:%s | ServerTime:%s | Long query</td></tr>\n" % tuple(
                    g_line[0:3])
                table_head_tmp += "<td>Op_desc</td><td>Secs_running</td><td>Op</td><td>Ns</td><td>Op_query</td><td>Op_insert</td><td>Client</td><td>Msg</td><td>Locks</td><td>WaitingForLock</td><td>LockStats</td></tr>\n"

                for line in result:

                    if line[1] > longquery_second:
                        table_body_tmp += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % tuple(
                            line)

                if table_body_tmp:
                    table_body += table_head_tmp + table_body_tmp

            sql = "insert into mongodb_current_op_his(host,port,Op_desc ,Secs_running ,Op ,Ns ,Op_query ,Op_insert ,Client ,Msg ,Locks ,WaitingForLock ,LockStats ,CreateTime,uuid) select host,port,Op_desc ,Secs_running ,Op ,Ns ,Op_query ,Op_insert ,Client ,Msg ,Locks ,WaitingForLock ,LockStats ,CreateTime,uuid from mongodb_current_op where host='%s' and port='%s' and uuid='%s'" % (
                g_line[0], g_line[1], g_line[4])
            cur_dbmon.execute(sql)

            sql = "delete from mongodb_current_op where host='%s' and port='%s' and uuid='%s'" % (
                g_line[0], g_line[1], g_line[4])
            cur_dbmon.execute(sql)

        if table_body:
            mail_text += table_head + table_body + "</table>"
        result = sendmail.send_mail("*****@*****.**", "mail_subject", mail_text)
    except Exception, e:
        print "analyze_mongodb_currentop got error:%s" % e
示例#33
0
def send_email_notification(camera_config, files):
    import socket
    import sendmail
    import tzctl
    import smtplib

    logging.debug('sending animation email')

    try:
        subject = sendmail.subjects['motion_end']
        message = sendmail.messages['motion_start']
        format_dict = {
            'camera': camera_config['@name'],
            'hostname': socket.gethostname(),
            'moment': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        }
        if settings.LOCAL_TIME_FILE:
            format_dict['timezone'] = tzctl.get_time_zone()

        else:
            format_dict['timezone'] = 'local time'

        message = message % format_dict
        subject = subject % format_dict

        sendmail.send_mail(
            camera_config['@animation_email_notifications_smtp_server'],
            int(camera_config['@animation_email_notifications_smtp_port']),
            camera_config['@animation_email_notifications_smtp_account'],
            camera_config['@animation_email_notifications_smtp_password'],
            camera_config['@animation_email_notifications_smtp_tls'],
            camera_config['@animation_email_notifications_from'],
            [camera_config['@animation_email_notifications_addresses']],
            subject=subject,
            message=message,
            files=files)

        logging.debug('animation email succeeded')

    except Exception as e:
        if isinstance(e, smtplib.SMTPResponseException):
            msg = e.smtp_error
        else:
            msg = str(e)
        logging.error('animation email failed: %s' % msg, exc_info=True)
def send_password(user, passwd):
    from sendmail import send_mail

    from django.template import loader, Context

    recipient = '<%(name)s> %(email)s' % {'name': user.get_full_name(),
                                          'email': user.email}
    recipient = user.email
    sender = '<%(name)s> %(email)s' % {'name': settings.DEFAULT_FROM_NAME,
                                       'email': settings.DEFAULT_FROM_EMAIL}
    sender = settings.DEFAULT_FROM_EMAIL
    subject = _(u'Password recovery')
    message = loader.get_template(
        'profile/' + settings.EMAIL_RECOVER_PASSWORD).render(
            Context(
                {'passwd': passwd}))
    send_mail(recipient_list=[recipient], from_email=sender,
              subject=subject, message=message)
示例#35
0
def main():
    global mail_content, port
    try:
        mail_content += "begin time: " + time.strftime(
            "%Y-%m-%d %H:%M:%S") + "\n"
        if len(port) == 1:
            backup(port[0])
        else:
            for p in port:
                backup(p)
        mail_content += "end time: " + time.strftime(
            "%Y-%m-%d %H:%M:%S") + "\n"
        file_clear()
        disk_info()
        sendmail.send_mail(mailto_list, "mysqlbackup report for " + server,
                           mail_content)
    except Exception, ex:
        print ex
示例#36
0
def main():
    setup()
    initalizeInterrupts()
    masterQueue = initMasterQueue()
    GPIO.output(ledPin, GPIO.LOW)  #set it to low on start up

    while True:

        if queue.getQueue() == masterQueue.getQueue(
        ):  # if the last 4 inputs inputted by the buttons are equal to the master key
            GPIO.output(ledPin, GPIO.HIGH)
            send_mail()
            queue.dequeue()
            queue.dequeue()
            queue.dequeue()
            queue.dequeue()
        else:
            GPIO.output(ledPin, GPIO.LOW)
示例#37
0
 def GET(self):
     pars = web.input()
     username = pars['username']
     rt = db.query('select * from user where username=$aa', vars={'aa':username})
     for r in rt:
         password = r['password']
         email = r['email']
         content ='your password is '+password
         from sendmail import send_mail
         return send_mail(email, 'findpassword', content)
示例#38
0
def main():
    global mail_content
    try:
        if time.strftime('%H') == "00":
            back_type = 1
        else:
            back_type = 0
        mail_content += "begin time: " + time.strftime(
            "%Y-%m-%d %H:%M:%S") + "\n"
        backup(back_type)
        mail_content += "end time: " + time.strftime(
            "%Y-%m-%d %H:%M:%S") + "\n"
        file_clear()
        #print mail_content
        #disk_info()
        sendmail.send_mail(mailto_list, "mysqlbackup report for " + server,
                           mail_content)
    except Exception, ex:
        print ex
示例#39
0
def MailButtonAction():
    global maildatalist, mailflag, AddrLabel1, AddrLabel2, AddrLabel3

    senderAddr = Spammodule.getGmailId()
    password = Spammodule.getGmailPass()

    recAddr = ''

    if mailflag == 0:
        recAddr = AddrLabel1.get()
    elif mailflag == 4:
        recAddr = AddrLabel3.get()
    else:
        recAddr = AddrLabel2.get()

    print(maildatalist)

    if len(maildatalist) > 0:
        sendmail.send_mail(senderAddr, password, recAddr, maildatalist,
                           mailflag)
示例#40
0
def set_attach_to_forum(cookie, site="http://m.dimonvideo.ru/"):
    page = send_mail("{}settings.php?op=5&id=3".format(site), cookie, [])

    if page:
        lst = page.split("<tr>")[1:-1]
        L = []

        for i in lst:
            mo = re.search(r"name *= *'([^']+)'", i)
            if not mo:
                continue
            name = mo.group(1)
            mo = re.search(r"checked *= *'([^']+)'", i)

            if mo:
                # Опция уже включена на сайте.
                if name == "forumupl" and mo.group(1) == "checked":
                    return True
                L.append((name, "1"))

        L.extend(
            [
                ("forumupl", "1"),
                ("op", "1"),
                ("id", "3"),
                ("submit", "Сохранить")
            ]
        )
        page = send_mail("{0}settings.php?op=5&id=3".format(site), L)

    if page is None:
        return None  # ошибка соединения
    elif page == 0:
        return None  # ошибка авторизации
    else:
        page = page.split("<h4")
        if len(page) < 2:
            raise
        else:
            return page[1].split(">")[1].split("</h")[0].decode(
                "cp1251").encode("utf-8")
示例#41
0
def checkWebFenjianli(url, exceptinfo):             #检测纷简历网站是否正常访问
    max_num = 10
    for i in range(max_num):
        try:
            req = urllib2.Request(url, headers = headers)
            resp = urllib2.urlopen(req)
            htmlcontent = resp.read().decode('utf-8', 'ignore')
            if '关于纷简历' in htmlcontent:
                return 'Y'
            else:
                logging.error("纷简历网站内容错误!")
                sendmail.send_mail(exceptinfo)
                return 'N'
        except urllib2.URLError, e:
            if i < max_num - 1:
                continue
            else:
                logging.error(e.reason)
                logging.error(sys.exc_info())
                sendmail.send_mail(exceptinfo)
                return 'N'
示例#42
0
def checkWebInfo(url, webcontent, exceptinfo):
    max_num = 10
    for i in range(max_num):
        try:
            req = urllib2.Request(url, headers = headers)
            resp = urllib2.urlopen(req)
            response = resp.read().decode('utf-8', 'ignore')
            if (response != webcontent):
                sendmail.send_mail(exceptinfo)
                logging.error("接口返回内容不等于" + webcontent)
                return 'N'
            else:
                return 'Y'
        except urllib2.URLError, e:
            if i < max_num - 1:
                continue
            else:
                logging.error(e.reason)
                logging.error(sys.exc_info())
                sendmail.send_mail(exceptinfo)
                return 'N'
def main():
    if GPIO.input(Laser) == False:
        print("Laser Detected")
        time.sleep(3)
        measure1 = usonic.measure(Trig, Echo)
        measure2 = usonic.measure(Trig2, Echo2)
        print(measure1, measure2)

        date = datetime.datetime.now()
        cur_date = str(date.strftime("%Y-%m-%d"))
        cur_time = str(date.strftime("%H:%M:%S"))
        img_name = "{0} {1}.jpg".format(cur_date, cur_time)
        m1 = ( measure1 / 32)*100
        m2 = ( measure2 / 26)*100
        avg = int((m1+m2)/2)

        json_data = {
        "latest":{
            "file":str(cur_date+"/"+img_name),
            "date":cur_date, 
            "time":cur_time
            },
        "measure1":m1,
        "measure2":m2,
        "avg":avg
        }

        with open("data.json",'w') as json_out:
            json.dump(json_data, json_out)
        json_out.close()

        print(img_name)
        relay.relay(Relay, 0)
        cam.camera_take(image_save_dir+img_name)
        time.sleep(1)
        relay.relay(Relay, 1)
        upload_blob(bucket_name, "data.json", "data.json")
        upload_blob(bucket_name, image_save_dir+img_name, str(image_save_dir+cur_date+"/"+img_name))
        body = "Your mailbox was triggered on {0} {1}\nYou can view more info on https://rich-ripple-262608.appspot.com".format(cur_date, cur_time)
        sendmail.send_mail("IOT Mailbox got Mail", body)
示例#44
0
def checkSolrInfo(url, exceptinfo):
    max_num = 10
    for i in range(max_num):
        try:
            req = urllib2.Request(url, headers = headers)
            resp = urllib2.urlopen(req)
            response = resp.read().decode('utf-8', 'ignore')
            json_data = json.loads(response)
            if json_data['response']['numFound'] != 0:
                return 'Y'
            else:
                logging.error(exceptinfo)
                sendmail.send_mail(exceptinfo)
                return 'N'
        except urllib2.URLError, e:
            if i < max_num - 1:
                continue
            else:
                logging.error(e.reason)
                logging.error(sys.exc_info())
                sendmail.send_mail(exceptinfo)
                return 'N'
示例#45
0
def sendmail_2():
    sub='美国江森自控安防系统产品资料' 
    html_content = '''<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=GB2312"></HEAD><BODY>
    <div class="gmail_quote"><div style="line-height:1.7;color:#000000;font-size:14px;font-family:arial">
    <div>您好!<br>&nbsp;&nbsp;美国江森自控安防系统产品请看附件!<br><br>&nbsp;</div>
    <div><div style="color:rgb(0,0,0);line-height:1.7;font-family:arial;font-size:14px">
    <div style="color:rgb(0,0,0);line-height:1.7;font-family:arial;font-size:14px"><div><div>
    <div>顺颂商祺!</div>
    <div>于卓琼</div>
    <div>市场总监</div>
    <div>T: 021-64512509&nbsp; C:13501693190&nbsp; E: <a href="mailto:[email protected]" target="_blank">[email protected]</a></div>
    <div><a href="http://blog.sina.com.cn/secsung" target="_blank">http://blog.sina.com.cn/secsung</a></div>
    <div>
    <div><span style="line-height:21px;font-family:Simsun">A more confortable, safe and sustainable world</span></div>
    <div>-----------------------------------------------<br style="line-height:21px;font-family:Simsun">
    <span style="line-height:21px;font-family:Simsun">江森自控上海总代理</span></div>
    <div><span style="line-height:21px;font-family:Simsun">19:24:09 2011-12-12</span></div></div></div></div></div></div>
    <div style="background:rgb(222,232,242);padding:4px;clear:both;font-family:verdana,Arial,Helvetica,sans-serif;margin-top:10px;margin-bottom:15px">
    <div style="padding:4px 8px 8px;line-height:16px;font-size:14px"><b>从网易163邮箱发来的超大附件</b></div><div style="background:rgb(255,255,255);padding:4px">
    <div style="padding:6px 4px;min-height:36px;clear:both">
    <div style="width:36px;float:left">
    <a href="http://fs.163.com/fs/display/?p=X-NETEASE-HUGE-ATTACHMENT&amp;file=Xt9C6OiQlThxcHl1OlqSAGfB6-TbYqzD4opBeoPvVB3BFOqda4CzUN7XQirmy137pNzMQzZJ8Zofu3eiHEgiTA&amp;title=%E6%B1%9F%E6%A3%AE%E8%B5%84%E6%96%99" target="_blank">
    <img src="cid:ico-bfile-6.gif"  border="0"></a></div>
    <div><div style="padding:0px;line-height:14px;font-size:12px">
    <a style="color:rgb(0,0,0);text-decoration:none" href="http://fs.163.com/fs/display/?p=X-NETEASE-HUGE-ATTACHMENT&amp;file=Xt9C6OiQlThxcHl1OlqSAGfB6-TbYqzD4opBeoPvVB3BFOqda4CzUN7XQirmy137pNzMQzZJ8Zofu3eiHEgiTA&amp;title=%E6%B1%9F%E6%A3%AE%E8%B5%84%E6%96%99" target="_blank">江森产品.rar</a>                                    <span style="color:rgb(187,187,187)"> (60.57M, 2011年12月27日 19:39 到期)</span> </div>
     <div style="padding:4px 0px;line-height:14px;font-size:12px"> <a href="http://fs.163.com/fs/display/?p=X-NETEASE-HUGE-ATTACHMENT&amp;file=Xt9C6OiQlThxcHl1OlqSAGfB6-TbYqzD4opBeoPvVB3BFOqda4CzUN7XQirmy137pNzMQzZJ8Zofu3eiHEgiTA&amp;title=%E6%B1%9F%E6%A3%AE%E8%B5%84%E6%96%99" target="_blank">下载</a>                                </div>
    </div></div></div></div>
    <br><br><span title="neteasefooter"><span></span></span></div></div><br><br><span title="neteasefooter"><span></span></span></div><br>
    </BODY></HTML>    ''' 
    mailto_list=utils.getMailList('maillist.txt')  
    userList = utils.getUser('mailuser.properties')
    userSize = len(userList)
    for to in mailto_list:
        user=userList[random.randint(0,userSize-1)];
        c_logger.info ( "%s start send %s" % (user.username,to))
        sendmail.send_mail( user.host , user.username , user.password ,  to, sub ,'' ,html_content,['ico-bfile-6.gif'])
        time.sleep(random.randint(1,3))
    c_logger.info( "finish")   
示例#46
0
def sendmail_1():
    sub='美国江森自控安防系统上海总代理-上海希宸经贸有限公司诚邀垂询' 
    html_content = '''<html><body>
    <b>详情请点击访问 <a 
    href='http://blog.sina.com.cn/secsung'>http://blog.sina.com.cn/secsung</a>
    <br><br>
    <img alt="" src="cid:johnson.jpg" style="border: none;" />
    详情请点击访问 <a 
    href='http://blog.sina.com.cn/secsung'>http://blog.sina.com.cn/secsung</a>
    <br><br><br><br></b>
    ------------------------------------------------<br>
    江森自控上海总代
    </body></html>
    ''' 
    mailto_list=utils.getMailList('maillist.txt')
    userList = utils.getUser('mailuser.properties')
    userSize = len(userList)
    for to in mailto_list:
        user=userList[random.randint(0,userSize-1)];
        c_logger.info ( "%s start send %s" % (user.username,to))
        sendmail.send_mail( user.host , user.username , user.password ,  to, sub ,'' ,html_content,['johnson.jpg'])
        time.sleep(random.randint(1,3))
    c_logger.info( "finish")   
示例#47
0
def check_waiting_list(waitings):
    for url, info in waitings.iteritems():
        if info['hit'] < -10:
            info['hit'] += 1
            continue
        req = urllib2.Request(url, headers=headers)
        response = urllib2.urlopen(req)
        the_page = response.read()
        product_name = re_product_name.search(the_page).group(1)
        pm_id = re_pm_id.search(the_page).group(1)

        #print product_name, pm_id
        req = urllib2.Request(ajax_url % pm_id, headers=headers)
        response = urllib2.urlopen(req)
        json = response.read()

        details = re_details.search(json)
        curr_price = float(details.group(1))
        market_price = float(details.group(2))
        yhd_price = float(details.group(3))
        prom_price = float(details.group(4))
        stock_num = int(details.group(5))
        remain_time = int(details.group(6)) // 1000

        #print curr_price, ops
        subject = '%s 当前价格%0.2f元,库存%d件, 剩余时间%d时%d分' % \
            (product_name, curr_price, stock_num, remain_time/3600, (remain_time % 3600) // 60)
        content = '%s  %s' % (subject, url)
        print subject

        if info['price'] == 0:
            if info['hit'] >= 0:
                info['price'] = curr_price
                print 'update product price'
            else:
                info['hit'] += 1
        elif curr_price < info['price']:
            if info['hit'] >= 5:
                if send_mail(subject, content):
                    print '发送通知成功 %s' % subject
                    info['hit'] = -1000
                else:
                    print '发送通知失败 %s' % subject
            else:
                info['hit'] += 1
                info['update'] = time.time()
        elif time.time() - info['update'] > 120.0:
            info['hit'] = 0
        time.sleep(10)
示例#48
0
  def post(self):
    # Handle response to feedback data.  

    sender_name = self.request.get('name')
    description = self.request.get('description')
    sender_email = self.request.get('email')
    lang = self.request.get('language', 'burmese')
    encoding = self.request.get('encoding', 'DEFAULT ENCODING')
    font = self.request.get('font', 'notosans')
    comment = self.request.get('commment', 'DEFAULT COMMENT')
    sampleText = self.request.get('sampleText', 'SAMPLE TEXT')

    logging.info('Feedback input = %s %s %s' % (lang, font, sampleText))

    # Create the ErrorReport
    newReport = ErrorReport()
    newReport.submitterName = sender_name
    newReport.submitterMail = sender_email
    newReport.encoding = encoding
    newReport.language = lang
    newReport.comment = comment
    newReport.font = font
    newReport.sampleText = sampleText
    
    # Write to datastore.
    newReport.put()
    
    logging.info('Sender: %s (%s)\n' % (sender_name, sender_email))
    logging.info("Description received = '%s'\n" % description)

    email_body = ('sender: %s (%s)\n \nDescription: %s\n' %
                   (sender_name, sender_email, description))

    result = sendmail.send_mail('smtpauth.earthlink.net',
         None, '*****@*****.**','*****@*****.**',
         'Feedback', email_body, False)
      
    template_values = {
      'language': lang,
      'sampleText': sampleText,
      'font': font,
      'encoding': encoding,
      'result': result
    }
    logging.info("EMail result: %s\n" % (result))

    path = os.path.join(os.path.dirname(__file__), 'sendfeedback.html')
    self.response.out.write(template.render(path, template_values))
示例#49
0
    wb = Workbook()
    ws = wb.add_sheet('In-Out Summary')
    write_header(ws)
    today = datetime.today()
    days = 7
    start_day = today - one_hour * 24 * days
    row = 2
    for i in range(days):
        handle_one_day(start_day + i * 24 * one_hour, ws, row)
        row += 24

    conn.disconnect()
    dir_path = tempfile.gettempdir()
    file_name = 'WK{} IOSummary.xls'.format(today.strftime('%W'))
    file_path = os.path.join(dir_path, file_name)
    wb.save(file_path)

    from sendmail import send_mail
    subject = 'Engineering Asset IO Weekly Summary'
    fmt = '%Y-%m-%d 08:00'
    body = '<h1>Time Range:<br /> {} - {}</h1>'
    body = body.format(start_day.strftime(fmt),
                       today.strftime(fmt),
                       )
    kwargs = dict(attachments=[file_path],
                  to=['Lisa.Ramos', 'Elva.Shao'],
                  bcc=['Colin.Qi', 'Sucre.Su'],
                  )
    send_mail(subject, body, **kwargs)
    os.remove(file_path)
示例#50
0
文件: maiproce.py 项目: AlenMa/quote
import time

mail_list=['*****@*****.**','*****@*****.**','*****@*****.**']
if __name__ == '__main__':
    try:
        f=open('/home/alenma/workspace/quote/quotecode.txt','r')
        line=f.readline()
        quotes=[]
        while line:
            data=line.split('|')
            q=Quote(data[0],data[1],int(data[2]),float(data[3]))
            quotes.append(q)
            line=f.readline()
    finally:
        if f:
            f.close()
    
    up=0
    while up<=10:
        for i in quotes:
            price=sinaquote.getprice(i.code)+up
            rate=i.getrate(price)
            if rate>=0.2:
                subject="%s(%s)'s price is %s,rate is %f"  %(i.name,i.code,price,rate)
                content="%s(%s) 's price is %s,rate is %f"  %(i.name,i.code,price,rate)
                sendmail.send_mail(mail_list,subject,content)
                time.sleep(10)
        time.sleep(10)
        up+=1
        
            
示例#51
0
 def POST(self):
     #导入sendmail。py 的send_mail 方法
     from sendmail import send_mail
     return send_mail('*****@*****.**', 'test', 'test111')
示例#52
0
文件: massmail.py 项目: cinno/pymm
  def __init__(self, cfgfile):
    self.cfgfile = cfgfile

    config = configparser.ConfigParser()
    config.read(cfgfile)
    
    username     = config['DEFAULT']['username']
    senderadress = config['DEFAULT']['senderadress']
    mailhost     = config['DEFAULT']['mailhost']
    port         = config['DEFAULT']['port']
    subject      = config['DEFAULT']['subject']
    note         = config['DEFAULT']['note']

    # determine number of required fmtstr's in message
    message    = config['DEFAULT']['message']
    numfmtstrs = len(re.findall('{}',message))

    recipients = eval(config['RECIPIENTS']['recipients'])

    logger.debug('username: {}\n'
                 'senderadress: {}\n'
                 'mailhost: {}\n'
                 'port: {}\n'
                 'subject: {}\n'
                 'note: {}\n'
                 'message: {}\n'
                 'numfmtstrs: {}\n'
                 'recipients: {}'.format(username,senderadress,mailhost,port,
                                           subject,note,message,numfmtstrs,
                                           recipients))

    for recipient in recipients:
      data = recipient.strip().split()

      try:
        mail_dest   = data[0]
        fmtstrs     = data[1:numfmtstrs+1]
        attachments = data[numfmtstrs+1:]

        logger.debug('mail_dest: {}\n'
                     'fmtstrs: {}\n'
                     'attachments: {}'.format(mail_dest,fmtstrs,attachments))

        if(len(fmtstrs) != numfmtstrs):
          raise IndexError

        fmtmessage = message.format(*fmtstrs)
        logger.debug('fmtmessage: {}'.format(fmtmessage))

        send_mail(senderadress, mail_dest, subject, fmtmessage,
                  files=attachments, server=mailhost, user=username,
                  password=None, port=port, note=note)

      except IndexError as e:
        logger.warning('Skipping wrongly formated data {}: {}\n{}'.format(data,fmtstrs,e))
        continue
      except Exception as e:
        logger.warning('Error sending {}: {}'.format(data,e))
        continue

      logger.info('Mail to {} successfully send.'.format(mail_dest))
示例#53
0
    try:
        for dirpath, dirnames, files in os.walk(FILE_PATH):
            for i in files:
                file = dirpath + i
                try:
                    LOGGER.info("Transferring file: " + i)
                    insert_csv(file, i)
                except Exception, e:
                    LOGGER.error(e)
                    send_mail(SENDER, RECEIVERS, e)
                finally:
                    os.remove(file)
                LOGGER.info("File successfully removed from " + FILE_PATH + "\n" + "-" * 80)
    except Exception, e:
        LOGGER.error(e)
        send_mail(SENDER, RECEIVERS, e)
        # break


def schedler():
    # try:
    LOGGER.info("Application starts running\n" + "-" * 80)
    while True:
        # print time.time()
        s.enter(5, 1, main, ())
        s.run()
        # #for multi-threaded environments
        # Timer(5, __main__, ()).start()
        # time.sleep(10)  # sleep while time-delay events execute
        # print time.time()
        # except KeyboardInterrupt:
示例#54
0
# -*- coding:utf-8 -*-

import psutil
import re
import os
import sendmail
a=[]
c=[]

def process(x):
    p = psutil.pids()
    for i in p:
        pid=psutil.Process(i)
        name = str(pid.name())
        if re.match(x, name):
            a.append('%i' %i)


try:
    process('java')
    if len(a) < 16:
        for g in a:
            pid=psutil.Process(int(g))
            l=pid.cwd()
            if re.match("^.*\-tdx.*$", l):
               c.append('%i' %int(g))
        sendmail.send_mail('[email protected]@xinyusoft.com','交易程序故障报警','现有进程数:%i\ntdx进程数:%i' %(len(a),len(c)))
        sendmail.send_mail('[email protected]@xinyusoft.com','交易程序故障报警','现有进程数:%i\ntdx进程数:%i' %(len(a),len(c)))
        sendmail.send_mail('[email protected]@xinyusoft.com','交易程序故障报警','现有进程数:%i\ntdx进程数:%i' %(len(a),len(c)))
except Exception as e:
   sendmail.send_mail('*****@*****.**','交易程序故障报警','监控程序异常,请处理\nerror%s' %e)
示例#55
0
	def send_mail(self,tolist,content):
		import sendmail
		tolist = tolist.split(',')
		sendmail.send_mail(tolist,u'报警通知',content)
		self.task.getLog().debug('send mail ok')
    track_hits = 0
    for t in tracked_cases.keys():
        last_status = tracked_cases[t][0]
        cur_status =  tracked_cases[t][1]
        if last_status != cur_status:
            track_hits = track_hits + 1
            case_status_body += 'Case [%s] being tracked has changed from [%s] to [%s]\n' %(
                t, last_status, cur_status)
        else:
            case_status_body += 'Case [%s] status remains unchanged\n' %t

    case_status_subject = 'Visa case status'
    if track_hits:
        case_status_subject += ' (Tracked cases hits: %d)' %track_hits

    return (case_status_subject, case_status_body)

subject, body = parse_221g(last_case_txt_file, cur_case_txt_file)

# dump the body to a case status file for a sample mail format
# also dump the date and issued count to a file that can serve as an input
# to the matplotlib plotter file
file('case_status', 'w').write(body)

num_issued = 0
if case_status_map.has_key('issued'):
    num_issued = len(case_status_map['issued'])
file('case_status_graph.dat', 'a').write(case_datetime + ' ' + str(num_issued) + '\n')

send_mail('*****@*****.**', '*****@*****.**', subject, body) 
示例#57
0
    if now>=start:
        alertsold=alerts
        print dt.datetime.today()
        try:
            stimmen_200, stimmen_target=check_votes()
            spread.write_log(dt.datetime.today(), stimmen_200, stimmen_target, stimmen_target - stimmen_200)
            with open('log.txt', 'a') as logfile:
                logfile.write('{},{},{},{} \n'.format(dt.datetime.today(), stimmen_200, stimmen_target,
                                                      stimmen_target - stimmen_200))
            if stimmen_target<stimmen_200-20:
                print "Too few votes, gogogo!"
                text="Stimmen Platz 200: {}\nStimmen Eigener Verein: {}\nDifferenz: {}\n".format(stimmen_200,stimmen_target,stimmen_target-stimmen_200)
                print text
                subject="Alert: too few Votes at ING!"
                if now>=nextalert:
                    send_mail(from_adress,from_password,to_adress,text,subject,True)
                    alerts+=1
            else:
                print "Vote difference big enough - waiting..."
        except urllib2.URLError:
            print "Website not available"
            subject="Alert: ING Website not available"
            text="\n"
            send_mail(from_adress,from_password,to_adress,text,subject,True)
            alerts+=1
        start=now+check_intervall
        if alerts!=alertsold:
            nextalert+=dt.timedelta(hours=24)
    time.sleep(1)

示例#58
0
                                           tr_style=mt.tr_style,
                                           td_style=mt.td_style,
                                           )
                    )
        for i, sp in enumerate(sorted(sps)):
            body.append('<tr>')
            body.append(mt.td.format(data=i + 1, **css))
            body.append(mt.td.format(data=sp['code'], **css))
            body.append(mt.td.format(data=sp['name'], **css))
            body.append(mt.td.format(data=sp['min_store'], **css))
            body.append(mt.td.format(data=sp['max_store'], **css))
            body.append(mt.td.format(data=sp['store_good'], **css))
            body.append(mt.td.format(data=sp['store_bad'], **css))
            body.append(mt.td.format(data=sp['out_good'], **css))
            body.append(mt.td.format(data=sp['out_bad'], **css))
            body.append('</tr>')

        body.append(mt.footer)

        body.append('<br /><br />')
        body.append(line)
        body.append('<br />')
        body.append(remark)
        send_mail(subject=subject,
                  body=''.join(body),
                  author=author,
                  to=to_list,
                  )

utils.close_connection(conn)