예제 #1
0
파일: debugerror.py 프로젝트: zahna/ebsd
    def emailerrors_internal():
        olderror()
        tb = sys.exc_info()
        error_name = tb[0]
        error_value = tb[1]
        tb_txt = ''.join(traceback.format_exception(*tb))
        path = web.ctx.path
        request = web.ctx.method + ' ' + web.ctx.home + web.ctx.fullpath
        eaddr = email_address
        text = ("""\
------here----
Content-Type: text/plain
Content-Disposition: inline

%(request)s

%(tb_txt)s

------here----
Content-Type: text/html; name="bug.html"
Content-Disposition: attachment; filename="bug.html"

""" % locals()) + str(djangoerror())
        sendmail("your buggy site <%s>" % eaddr,
                 "the bugfixer <%s>" % eaddr,
                 "bug: %(error_name)s: %(error_value)s (%(path)s)" % locals(),
                 text,
                 headers={
                     'Content-Type': 'multipart/mixed; boundary="----here----"'
                 })
예제 #2
0
    def emailerrors_internal():
        error = olderror()
        tb = sys.exc_info()
        error_name = tb[0]
        error_value = tb[1]
        tb_txt = ''.join(traceback.format_exception(*tb))
        path = web.ctx.path
        request = web.ctx.method + ' ' + web.ctx.home + web.ctx.fullpath
        text = ("""\
------here----
Content-Type: text/plain
Content-Disposition: inline

%(request)s

%(tb_txt)s

------here----
Content-Type: text/html; name="bug.html"
Content-Disposition: attachment; filename="bug.html"

""" % locals()) + str(djangoerror())
        sendmail(
          "your buggy site <%s>" % from_address,
          "the bugfixer <%s>" % to_address,
          "bug: %(error_name)s: %(error_value)s (%(path)s)" % locals(),
          text, 
          headers={'Content-Type': 'multipart/mixed; boundary="----here----"'})
        return error
예제 #3
0
파일: apply.py 프로젝트: Turi-fly/opcmdb
def Apply_account():
    mail = request.form.get('mail', '')
    mail_text = mail
    name = request.form.get('name', '')
    depment_id = request.form.get('depment_id', '')

    exists_acc = app.config['cursor'].get_one_result('account_cnt',
                                                     ['accounts'],
                                                     {'accounts': mail})

    depment_list = app.config['cursor'].get_one_result('depment', ['depment'],
                                                       {'id': depment_id})

    _status = apply_utils.validate_apply_acc(name, mail)
    content = '''
                 账号:%s,密码:%s
                 连接方式如下:
                 公司内网
                    1.从通过跳板机登录虚机的使用方法:
                        ssh  %[email protected]
                    2.不通过跳板机的方式:
                        ssh  %[email protected](相关机器的IP)
                 公司外网:
                    1.ssh -p 53122 %[email protected]

              ''' % (mail_text, mail_text, mail_text, mail_text, mail_text)
    if not exists_acc:
        if _status['code'] == 0:
            mail += "@yunniao.me"
            _status_code = utils.sendmail([mail], '', '')
            title = '%s申请的账号' % name
            if _status_code['code'] == 0:
                for _depment in ['dev', 'qa', 'ops']:
                    if depment_list['depment'] == _depment:
                        try:
                            _is_ok = apply_utils.transfer_freeipa(
                                mail_text, name, _depment)
                            if _is_ok:
                                _status_code = utils.sendmail([mail], title,
                                                              content)
                                return json.dumps(_status_code)
                            else:
                                return json.dumps({
                                    'code': 1,
                                    'errmsg': '您已经有自己的账号了!'
                                })
                        except:
                            return json.dumps({
                                'code': 1,
                                'errmsg': traceback.format_exc()
                            })
            else:
                return json.dumps(_status_code)
        else:
            return json.dumps(_status)
    else:
        return json.dumps({'code': 1, 'errmsg': '您已经有自己的账号了!'})
예제 #4
0
파일: apply.py 프로젝트: Turi-fly/opcmdb
def Apply_vm():
    mail = request.form.get('mail', '')
    mail_text = mail
    name = request.form.get('name', '')
    remark = request.form.get('remark', '')
    des_use_id = request.form.get('use_id', '')
    exists_acc = app.config['cursor'].get_one_result('account_cnt', ['id'],
                                                     {'accounts': mail_text})
    _status = apply_utils.validate_apply_res(mail, name, remark)
    if not exists_acc:
        if _status['code'] == 0:
            mail += "@yunniao.me"
            _status_code = utils.sendmail([mail], '', '')
            if _status_code['code'] == 0:
                _res_list = app.config['cursor'].get_one_result(
                    'vm', ['id', 'ip', 'vm', 'admin', 'remark'], {
                        'use_status': 0,
                        'des_use_id': des_use_id
                    },
                    limit=1)
                if _res_list:
                    app.config['cursor'].execute_insert_sql(
                        'account_cnt', {'accounts': mail_text})
                    id = _res_list['id']
                    ip = _res_list['ip']
                    vm = _res_list['vm']
                    _is_ok = apply_utils.transfer_freeipa(
                        mail_text, name, 'dev')
                    app.config['cursor'].execute_update_sql(
                        'vm', {
                            "admin": name,
                            "remark": remark,
                            "use_status": 1
                        }, {'id': id})
                    title = '%s申请的虚拟机资源' % name
                    if not _is_ok:
                        content = '虚拟机名称:%s,ip地址:%s,账号:%s,密码:%s' % (
                            vm, ip, mail_text,
                            '您的账号已经存在密码不在是初始化密码,要是没有更改还是%s' % mail_text)
                    else:
                        content = '虚拟机名称:%s,ip地址:%s,账号:%s,密码:%s' % (
                            vm, ip, mail_text, mail_text)
                    _status_code = utils.sendmail([mail], title, content)
                    return json.dumps(_status_code)
                else:
                    return json.dumps({
                        'code': 1,
                        'errmsg': '虚拟机已经没有了,请联系运维刘宝宝来开通!'
                    })
            else:
                return json.dumps(_status_code)
        else:
            return json.dumps(_status)
    else:
        return json.dumps({'code': 1, 'errmsg': '您已经申请过虚拟机!每人只能拥有一台!'})
예제 #5
0
파일: env.py 프로젝트: Karagul/camp
 def initPwd(self):
     import random
     import string
     import utils
     initpwd = ''.join(random.choice(string.ascii_letters) for i in range(6))
     hex = hashlib.sha1(initpwd).hexdigest()
     utils.sendmail('*****@*****.**', [self.email], u'重设CAMP密码', initpwd)
     q = QtSql.QSqlQuery()
     query = """UPDATE USERS SET PWD='%s', PWD_TEMP=1 WHERE ID=%s""" % (hex, self.id)
     q.exec_(query)
     QtSql.QSqlDatabase().commit()
     self.pwd = hex
예제 #6
0
파일: user.py 프로젝트: TAKSIM/fwm
    def initpwd(self):
        import random
        import string
        import utils

        initpwd = "".join(random.choice(string.ascii_letters) for i in range(6))
        hex = hashlib.sha1(initpwd).hexdigest()
        utils.sendmail("*****@*****.**", [self.email], u"重设家族信托资管平台密码", initpwd)
        q = QtSql.QSqlQuery()
        query = """UPDATE USER SET PWD='%s', PWD_TEMP=1 WHERE ID=%s""" % (hex, self.id)
        q.exec_(query)
        QtSql.QSqlDatabase().commit()
        self.pwd = hex
예제 #7
0
파일: test.py 프로젝트: LoveSn0w/schedule
 def get(self, *args, **kwargs):
     uname = self.get_argument("uname")
     uid = self.get_argument("uid")
     if isinstance(uname, unicode):
         uname = uname.encode("utf-8")
         sso = single_login(uid, uname)
         gen_log.info(sso)
         email = "Student From LJL id=%s, name=%s\n" \
                 "Payed for:%s \n" \
                 "Class Table Link: http://yueke.speiyou.com/timetable/list/moodle?uid=%s&claId=%s\n" \
                 "SSO URL: %s" \
                 % (uid, uname, "test 000", uid, "classId", sso)
         gen_log.info(email)
         sendmail(msg=email, subject="%s Student Pay For Class" % datetime.now())
         self.write("world")
     else:
         self.write("Hello")
예제 #8
0
def fetch_webmention_and_send_email(doc, message_n):
    webmentiondata = doc['messages'][message_n]

    # fetch html
    print 'fetching webmention from', webmentiondata['source'], 'targeting', webmentiondata['target']
    sourcehtml = requests.get(webmentiondata['source']).text
    if not webmention.url_in_source(webmentiondata['target'], sourcehtml):
        print 'no target url in source. deleting webmention.'
        utils.sendmail(frm='*****@*****.**', to='*****@*****.**', subject='no target url in source', html='<pre style="font-family: monospace">' + pformat({'webmention': webmentiondata, 'doc': doc}) + '</pre>')
        doc['messages'].pop(message_n)
        requests.put(CLOUDANT_URL + '/' + doc['_id'], data=json.dumps(doc), headers=headers)
        return

    webmentiondata['html'] = webmention.get_article_html(sourcehtml)

    # send email
    target_domain = urlparse.urlparse(webmentiondata['target']).netloc
    target_email = utils.email_from_domain(target_domain)
    sender_domain = urlparse.urlparse(webmentiondata['source']).netloc
    print 'got html, now sending email to', target_email
    template = Template(open('emailtemplates/got-webmention.html').read())
    mailsent = utils.sendmail(
        frm=sender_domain + '@questo.email',
        to=target_email,
        subject='message left at %s' % target_domain,
        reply_to=doc['emails-in-thread'][0] if doc['emails-in-thread'] else None,
        html=template.render(
            domain=domain,
            source=webmentiondata['source'],
            target_domain=target_domain,
            sender=sender_domain,
            thread_id=doc['_id'],
            message=webmentiondata['html']
        )
    )
    if not mailsent.ok:
        return

    # save it
    mail_id = mailsent.json()['id']
    print 'ok, sent with id', mail_id
    webmentiondata['email-id'] = mail_id
    doc['emails-in-thread'].append(mail_id)

    requests.put(CLOUDANT_URL + '/' + doc['_id'], data=json.dumps(doc), headers=headers)
예제 #9
0
 def T_SendReportMail(self, test): 
     import web_utils
     import sys
     reload(sys)
     sys.setdefaultencoding('utf-8')
     
     creator = test.step
     email_list = []
     email_list.append(creator)
     #email_list = list(creator)
     
     mail_content = ''        
     mail_content += web_utils.iTest_report(self.env, test)
     maildic = {}
     maildic['title'] = 'iTest TestReport: ' + test.name 
     maildic['to'] = email_list
     maildic['content'] = mail_content #mail_content.decode('utf-8') 
     utils.sendmail(self.env, maildic) 
예제 #10
0
    def emailerrors_internal():
        error = olderror()
        tb = sys.exc_info()
        error_name = tb[0]
        error_value = tb[1]
        tb_txt = ''.join(traceback.format_exception(*tb))
        path = web.ctx.path
        request = web.ctx.method + ' ' + web.ctx.home + web.ctx.fullpath

        message = "\n%s\n\n%s\n\n" % (request, tb_txt)

        sendmail(
            "your buggy site <%s>" % from_address,
            "the bugfixer <%s>" % to_address,
            "bug: %(error_name)s: %(error_value)s (%(path)s)" % locals(),
            message,
            attachments=[
                dict(filename="bug.html", content=safestr(djangoerror()))
            ],
        )
        return error
예제 #11
0
파일: debugerror.py 프로젝트: AlinT/socorro
 def emailerrors_internal():
     error = olderror()
     tb = sys.exc_info()
     error_name = tb[0]
     error_value = tb[1]
     tb_txt = ''.join(traceback.format_exception(*tb))
     path = web.ctx.path
     request = web.ctx.method + ' ' + web.ctx.home + web.ctx.fullpath
     
     message = "\n%s\n\n%s\n\n" % (request, tb_txt)
     
     sendmail(
         "your buggy site <%s>" % from_address,
         "the bugfixer <%s>" % to_address,
         "bug: %(error_name)s: %(error_value)s (%(path)s)" % locals(),
         message,
         attachments=[
             dict(filename="bug.html", content=safestr(djangoerror()))
         ],
     )
     return error
예제 #12
0
def sendadminlog( override=0 ):
    """sendadminlog() - send adminlog list to adminemail only if there
        is something in this list.
        If override==1 then admin_notify times are ignored.
    """

    global admin_notify_time
    global adminlog

    if override == 0:
        # if no admin_notify_time set, set one and return
        if admin_notify_time == 0:
            admin_notify_time = time.time() + admin_notify
            return
    
        # if time hasn't reached admin_notify_time then return
        if time.time() < admin_notify_time:
            return

    # time for notify - set new time and send the adminlog
    admin_notify_time = time.time() + admin_notify

    # if there isn't anything in adminlog don't bother
    if len(adminlog) == 0:
        return

    headers = 'To: %s\n' % adminemail
    headers = headers + 'Subject: [%s] Eddie Admin Messages\n' % hostname

    body = "Greetings Eddie Admin '%s', the following log messages are\n" % adminemail
    body = body + "being delivered to you for your perusal.  Enjoy.\n\n"
    body = body + "[Host:%s LogLevel=%d AdminLevel=%d AdminNotify=%s secs]\n" % (hostname,loglevel, adminlevel, admin_notify)
    body = body + "------------------------------------------------------------------------------\n"

    for i in adminlog:
        body = body + "%s" % (i)

    body = body + "------------------------------------------------------------------------------\n"
    r = utils.sendmail( headers, body )

    # clear adminlog
    adminlog = []
예제 #13
0
파일: log.py 프로젝트: hexdump42/eddie-tool
def sendadminlog( override=0 ):
    """sendadminlog() - send adminlog list to adminemail only if there
        is something in this list.
        If override==1 then admin_notify times are ignored.
    """

    global admin_notify_time
    global adminlog

    if override == 0:
        # if no admin_notify_time set, set one and return
        if admin_notify_time == 0:
            admin_notify_time = time.time() + admin_notify
            return
    
        # if time hasn't reached admin_notify_time then return
        if time.time() < admin_notify_time:
            return

    # time for notify - set new time and send the adminlog
    admin_notify_time = time.time() + admin_notify

    # if there isn't anything in adminlog don't bother
    if len(adminlog) == 0:
        return

    headers = 'To: %s\n' % adminemail
    headers = headers + 'Subject: [%s] Eddie Admin Messages\n' % hostname

    body = "Greetings Eddie Admin '%s', the following log messages are\n" % adminemail
    body = body + "being delivered to you for your perusal.  Enjoy.\n\n"
    body = body + "[Host:%s LogLevel=%d AdminLevel=%d AdminNotify=%s secs]\n" % (hostname,loglevel, adminlevel, admin_notify)
    body = body + "------------------------------------------------------------------------------\n"

    for i in adminlog:
        body = body + "%s" % (i)

    body = body + "------------------------------------------------------------------------------\n"
    r = utils.sendmail( headers, body )

    # clear adminlog
    adminlog = []
예제 #14
0
    def email(self, address, subject="", body=""):
        """The standard email action.

        address should be a standard string containing a standard email address
        or list of email addresses separated by ','.

        subject should be either a standard string which will be used as the
        email subject the name of a MSG object.

        body should be a string containing the body of the email.
        """

        if type(subject) != type("string"):
            # if subject is not a string, assume it is a MSG object
            body = subject.message
            subj = subject.subject
        else:
            subj = subject

        # replace text that look like newlines with newlines
        body = body.replace('\\n', '\n')

        # Create problem age and other statistics if this is not the first time
        # the problem was found.
        # Stored in %(problemage)s and %(problemfirstdetect)s
        self.varDict['problemage'] = ''
        self.varDict['problemfirstdetect'] = ''
        t = self.state.faildetecttime
        tl = self.state.lastfailtime
        if tl != t:
            tage = self.state.age()
            agestr = "Problem age: "
            if tage[0] > 0:
                agestr = agestr + " %d year" % tage[0]
                if tage[0] > 1:
                    agestr = agestr + "s"
            if tage[1] > 0:
                agestr = agestr + " %d month" % tage[1]
                if tage[1] > 1:
                    agestr = agestr + "s"
            if tage[2] > 0:
                agestr = agestr + " %d day" % tage[2]
                if tage[2] > 1:
                    agestr = agestr + "s"
            if tage[3] > 0:
                agestr = agestr + " %d hour" % tage[3]
                if tage[3] > 1:
                    agestr = agestr + "s"
            if tage[4] > 0:
                agestr = agestr + " %d minute" % tage[4]
                if tage[4] > 1:
                    agestr = agestr + "s"
            if tage[5] > 0:
                agestr = agestr + " %d second" % tage[5]
                if tage[5] > 1:
                    agestr = agestr + "s"
            if agestr != "":
                self.varDict['problemage'] = agestr
            self.varDict['problemfirstdetect'] = "First detected: %04d/%02d/%02d %d:%02d:%02d" % (t[0], t[1], t[2], t[3], t[4], t[5])


        # run thru utils.parseVars() to substitute variables from varDict
        address = utils.parseVars( address, self.varDict )
        subj = utils.parseVars( subj, self.varDict )
        body = utils.parseVars( body, self.varDict )

        #headers = 'To: ' + address + '\n' + 'Subject: [' + log.hostname + '] ' + subj + '\n'
        headers = 'To: %s\nSubject: [%s] %s\n' % (address,log.hostname,subj)
        r = utils.sendmail( headers, body )

        if r:
            log.log( "<action>action.email(): address='%s' subject='%s' body='%s...' successful)" % (address,subj,body[:20]), 6 )
        else:
            log.log( "<action>action.email(): address='%s' subject='%s' body='%s...' failed)" % (address,subj,body[:20]), 4 )
예제 #15
0
    def email(self, address, subject="", body=""):
        """The standard email action.

        address should be a standard string containing a standard email address
        or list of email addresses separated by ','.

        subject should be either a standard string which will be used as the
        email subject the name of a MSG object.

        body should be a string containing the body of the email.
        """

        if type(subject) != type("string"):
            # if subject is not a string, assume it is a MSG object
            body = subject.message
            subj = subject.subject
        else:
            subj = subject

        # replace text that look like newlines with newlines
        body = body.replace('\\n', '\n')

        # Create problem age and other statistics if this is not the first time
        # the problem was found.
        # Stored in %(problemage)s and %(problemfirstdetect)s
        self.varDict['problemage'] = ''
        self.varDict['problemfirstdetect'] = ''
        t = self.state.faildetecttime
        tl = self.state.lastfailtime
        if tl != t:
            tage = self.state.age()
            agestr = "Problem age: "
            if tage[0] > 0:
                agestr = agestr + " %d year" % tage[0]
                if tage[0] > 1:
                    agestr = agestr + "s"
            if tage[1] > 0:
                agestr = agestr + " %d month" % tage[1]
                if tage[1] > 1:
                    agestr = agestr + "s"
            if tage[2] > 0:
                agestr = agestr + " %d day" % tage[2]
                if tage[2] > 1:
                    agestr = agestr + "s"
            if tage[3] > 0:
                agestr = agestr + " %d hour" % tage[3]
                if tage[3] > 1:
                    agestr = agestr + "s"
            if tage[4] > 0:
                agestr = agestr + " %d minute" % tage[4]
                if tage[4] > 1:
                    agestr = agestr + "s"
            if tage[5] > 0:
                agestr = agestr + " %d second" % tage[5]
                if tage[5] > 1:
                    agestr = agestr + "s"
            if agestr != "":
                self.varDict['problemage'] = agestr
            self.varDict['problemfirstdetect'] = "First detected: %04d/%02d/%02d %d:%02d:%02d" % (t[0], t[1], t[2], t[3], t[4], t[5])


        # run thru utils.parseVars() to substitute variables from varDict
        address = utils.parseVars( address, self.varDict )
        subj = utils.parseVars( subj, self.varDict )
        body = utils.parseVars( body, self.varDict )

        #headers = 'To: ' + address + '\n' + 'Subject: [' + log.hostname + '] ' + subj + '\n'
        headers = 'To: %s\nSubject: [%s] %s\n' % (address,log.hostname,subj)
        r = utils.sendmail( headers, body )

        if r:
            log.log( "<action>action.email(): address='%s' subject='%s' body='%s...' successful)" % (address,subj,body[:20]), 6 )
        else:
            log.log( "<action>action.email(): address='%s' subject='%s' body='%s...' failed)" % (address,subj,body[:20]), 4 )
예제 #16
0
    def pay(self, cla_id='', uid='', uname='NotSupply'):
        """
            支付课程
            1. insert into student_classes
            2. update student_class_select deal as payed
            3. return class data
        """
        flag, selected = self.models.mss.get_selected_for_pay(uid, cla_id)
        dt, valid_time = BaseDBModel.get_valid_date()
        if flag:
            if selected:
                rows = self.models.mwrd.get_valid_dates(selected.workroom, status="used",
                                                        date_now=dt)
                p = []
                for r in rows:
                    if BaseDBModel.check_time(r.class_date, r.start_time):
                        if r.class_type == CheckRoll.TRAIL:
                            p.append((uid, cla_id, r.time_id, r.workroom, r.teacher, r.class_date, CheckRoll.TRAIL))
                        else:
                            p.append((uid, cla_id, r.time_id, r.workroom, r.teacher, r.class_date, CheckRoll.NORMAL))
                rs = self.models.msc.add(p)
                rs1 = self.models.mss.update_by(_id=selected.id, uid=uid, cla_id=cla_id,
                                                fields=["uname", "deal", "lastupdate"],
                                                values=[uname, "payed", datetime.now()])
                if rs and rs1:
                    try:
                        if isinstance(uname, unicode):
                            uname = uname.encode("utf-8")
                        sso = single_login(uid, uname)
                        # teacher_number = self.models.mss.get_teacher_number(rows[0].teacher)
                        # #set flat enrol file
                        # line = "add, student, %s, %s\nadd, teacher, %s, %s"\
                        #        % (uid, selected.workroom,
                        #           # uid, rows[0].teacher.upper(),
                        #           teacher_number, selected.workroom
                        #           # teacher_number, rows[0].teacher.upper()
                        #           )
                        # write_to_file(uid, cla_id, line)
                        # enrol_file = set_file_url(uid, cla_id)
                        # #get moodle cron exe url
                        # cron = get_cron_url()
                        # edit_url = get_edit_classtable(selected.workroom)
                        classtable = get_classtable_url(uid=uid, cla_id=cla_id)
                        #update class table
                        # update_class_table(classtable, selected.workroom)
                        # update_course_shortname(selected.workroom, uname)
                        # set_when_payed(uid, cla_id, uname, selected.workroom)
                        email = "Student From LJL id=%s, name=%s\n" \
                                "Payed for:%s \n" \
                                "Class Table Link:\n %s \n" \
                                "Step 1:\n    %s\nStep 2:\n    %s\nStep 3:\n    %s\n"\
                                "Step 4(Open is different Browser):\n %s" \
                                % (uid, uname, rows[0].workroom, classtable, "Handler", "Handler", "Handler", sso)
                        sendmail(msg=email, subject="%s Student Pay For Class" % datetime.now())
                    except:
                        gen_log.info(traceback.format_exc())

                    return {"rlt": True, "msg": "Success", "data": self.set_response(rows, cla_id, uid)}
                else:
                    return {"rlt": False, "msg": "Failed", "data": "支付失败"}
            else:
                return {"rlt": False, "msg": "Success", "data": "没有选课"}
        else:
            #重复调用
            rows = self.models.mwrd.get_by_workroom(selected.workroom)
            return {"rlt": True, "msg": "Repeat Invoke", "data": self.set_response(rows, cla_id, uid)}