コード例 #1
0
ファイル: api.py プロジェクト: polms/siteweb
 def notify(self, msg, importance, title=''):
     if not title:
         title = 'Message' if importance != 3 else 'IMPORTANT'
     if self.share.cfg.get("notif", "mail") == "True":
         sendMail(title, msg, self.share)
     if self.share.cfg.get("notif", "push") == 'True':
         sendPush(title, msg, self.share)
コード例 #2
0
ファイル: run.py プロジェクト: KodeKracker/Ophio-Foodly
def job2():
    # Set Logger Object
    logger = logging.getLogger(LOGGER_NAME)

    logger.info('Job-2 Start')
    # Store the results
    result = {}

    # Get Items
    items = fetchItems()

    # Get Votes
    votes = fetchVotes()

    # Get items by category
    result = getItemsByCategory(items, votes)

    # Get top items
    result = getTopItems(result, TOP)

    # Save Result to file
    filename = 'logs/' + getTodayDate() + '.log'
    with open(filename, 'w') as f:
        data = result
        if not data:
            data = {'No data for today'}
        f.write(json.dumps(result, ensure_ascii=False))

    # Send mail to users
    if result:
        sendMail(result)
    else:
        logger.info('No data so No mail for today')
    logger.info('Job-2 Completed')
コード例 #3
0
def main():
    courseStart.draw()
    username=courseStart.getUser()
    password=courseStart.getPwd()
    header={'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'zh-CN,zh;q=0.8','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}
    s=requests.session()
    course=courseStart.getCourse()

    success=False
    sender=courseStart.getMail()
    mailPassword=courseStart.getMailPwd()
    sucSubject='Congratulations!'
    falSubject='Sorry'
    sucBody='I have caught your course.'
    falBody='I can not catch your course.'
    
    try:
        login(username,password,header,s)
    except:
        print('failed to login, please try again!')

    try:
        success=getCourse(header,s,str(course))
    except:
        print('failed to catch the course!')

    try:
        if success:
            mail.sendMail(sender,mailPassword,sender,sucSubject,sucBody)
        else:
            mail.sendMail(sender,mailPassword,sender,falSubject,falBody)
    except:
        print('failed to send the mail.')
コード例 #4
0
def stargateContactForm():
    try:
        form = flask.request.form
        sendMail(form['email'], form['name'], form['subject'], form['message'])
        return flask.render_template('stargate/thank_you.html')
    except:
        return flask.abort(500)
コード例 #5
0
ファイル: upload.py プロジェクト: bigerous/buaa_spider
def report(username, password, email):
    global todaySuccess
    s = requests.Session()
    encodedStr = 'sfzx=1&tw=0&area=北京市 海淀区&city=北京市&province=北京市&address=北京市海淀区花园路街道北京航空航天大学北京航空航天大学学院路校区&geo_api_info={"type":"complete","position":{"Q":39.980123969185,"R":116.35079806857698,"lng":116.350798,"lat":39.980124},"location_type":"html5","message":"Get geolocation success.Convert Success.Get address success.","accuracy":40,"isConverted":true,"status":1,"addressComponent":{"citycode":"010","adcode":"110108","businessAreas":[{"name":"五道口","id":"110108","location":{"Q":39.99118,"R":116.34157800000003,"lng":116.341578,"lat":39.99118}},{"name":"牡丹园","id":"110108","location":{"Q":39.977965,"R":116.37172700000002,"lng":116.371727,"lat":39.977965}}],"neighborhoodType":"生活服务;生活服务场所;生活服务场所","neighborhood":"北京航空航天大学","building":"","buildingType":"","street":"学院路","streetNumber":"141号","country":"中国","province":"北京市","city":"","district":"海淀区","township":"花园路街道"},"formattedAddress":"北京市海淀区花园路街道北京航空航天大学北京航空航天大学学院路校区","roads":[],"crosses":[],"pois":[],"info":"SUCCESS"}&sfcyglq=0&sfyzz=0&qtqk=&askforleave=0'
    data = (urllib.parse.parse_qs(encodedStr))
    login(s, username, password)
    myLog.logger.info("get index: %s" % getParam(s).replace('\n', ' '))
    result = upload(s, data)
    myLog.logger.info("upload response: %s" % result.replace('\n', ' '))
    now = time.localtime()
    if ('成功' in result or '您已上报过' in result):
        myLog.logger.info(username + " 填报成功!")
        try:
            if '成功' in result and email != '':
                sendMail('成功%s 温度上报!' % time.strftime("%Y-%m-%d %H:%M", now),
                         "haha", email)
        except Exception as e:
            myLog.logger.error(username + ' 发送邮件失败')

        todaySuccess = True
        return True
    else:
        myLog.logger.fatal("填报失败!")
        return False
    s.close()
コード例 #6
0
ファイル: main.py プロジェクト: ficho2/Njuskalo-Notificator
def kreni(url, price, oib, maddr, fdata):
    i = 0
    msg = 'Ovo je novo:\n '
    flag = 0

    oglasi = []
    for item in url:
        try:
            oglasi = sc.getOglasi(item, price[i])
        except:
            pass
        i = i + 1
        for ogl in oglasi:
            if ogl.oib not in oib:
                msg = msg + ogl.ime + '\n' + str(
                    ogl.cijena) + '\n' + ogl.link + '\n\n\n'
                oib.append(ogl.oib)
                flag = 1
    if flag == 1:
        flag = 0
        print msg
        #**********************************************************************
        #Maknuti # ispred mail/face.sendMail da bi se slala obavjest tim putem ili staviti da ne bi
        #Remove # befor mail.sendMail/ face.sendMail to start notificator
        #**********************************************************************
        try:
            mail.sendMail(msg, maddr)
        except:
            pass
        try:
            face.sendMail(msg, fdata)
        except:
            pass

    return oib
コード例 #7
0
def send_to_user(note_dict, detail_dict, note_type='TJ_notifier'):
    """ 向每个用户发送通知邮件 """
    """ note_dict是一个id-标题的字典,detail_dict是一个id-正文的字典,note_type指代通知的来源 """
    conn = sqlite3.connect('TJ_notice.db')
    cursor = conn.cursor()
    cursor.execute('select * from user')
    result = cursor.fetchall()
    with open('mail', 'r') as fp:
        host_address = fp.readline().strip('\n')
        password = fp.readline().strip('\n')

    for key in detail_dict:
        title = '【{}】'.format(note_type) + note_dict[key]
        body = detail_dict[key]
        mail_list = []
        for mail_address in result:
            mail_list.append(mail_address[0])

        try:
            mail.sendMail(host_address, password, mail_list, title, body)
            env_build.write_to_log('send a mail {}'.format(note_dict[key]))
        except:
            env_build.write_to_log('failed to send a mail {}'.format(
                note_dict[key]))

    cursor.close()
    conn.commit()
    conn.close()
コード例 #8
0
 def _printOffout(self, alarmtime, racknum, voltage, recipients_list):
     msg = 'At:' + alarmtime + ': Rack shutdown would have fired (No actual shutdown initiated)'
     title = 'Rack ' + str(
         racknum) + 's full shutdown action would have activated'
     m.sendMail(msg, title, recipients_list)
     self.logging.info("RackController: " + msg + title)
     return
コード例 #9
0
ファイル: kreni.py プロジェクト: ficho2/Njuskalo-Notificator
def kreni(url, price, oib):
    import scraper as sc
    import mail
    oib = []
    i = 0
    msg = 'Ovo je novo:\n '
    flag = 1

    oglasi = []
    for item in url:
        print i, price[i]
        oglasi = sc.getOglasi(item, price[i])
        i = i + 1
        for ogl in oglasi:
            if ogl.oib not in oib:
                msg = msg + ogl.ime + '\n' + str(
                    ogl.cijena) + '\n' + ogl.link + '\n\n\n'
                oib.append(ogl.oib)
                flag = 1
    if flag == 1:
        flag = 0
        print msg
        mail.sendMail(msg)

    return oib
コード例 #10
0
def autoWeather():
    nw = getNewWeatherMsg()
    if nw.autoTips != 1 and nw.status != 1 and (int(getHouse()) < 22 or int(getHouse()) > 7):
        oldWeather = getOldSendWeather()
        oldWarning = getWarning(oldWeather.id)
        nowForecast = ''
        nowWarning = ''
        content = ''

        nWarning = getWarning(nw.id)
        nWarnIndex = 0
        tipsType = 0
        if len(nWarning) > 0:
            while nWarnIndex < len(nWarning):
                oWarnIndex = 0

                while oWarnIndex < len(oldWarning):
                    if nWarning[nWarnIndex].warnTitle != oldWarning[oWarnIndex].warnTitle:
                        tipsType += 1
                    oWarnIndex += 1

                if tipsType == len(oldWarning):
                    tipsType = -1
                    break
                nWarnIndex += 1

        if oldWeather.temperature - nw.temperature <= -5 or oldWeather.temperature - nw.temperature >= 5 or \
                (oldWeather.weather_condition != nw.weather_condition and oldWeather.weather_condition != nw.weather_condition and nw.weather_condition.find(
                        '晴') == -1 and nw.weather_condition.find('多云') == -1 and nw.weather_condition.find(
            '阴') == -1) or tipsType == -1:
            nForecast = getNewForecast(nw.id)
            title = "X.M Auto Tips: "
            content = ''
            if oldWeather.temperature - nw.temperature <= -5 or oldWeather.temperature - nw.temperature >= 5:
                title += '温差过大! '
                content += '温差' + str(int(oldWeather.temperature) - int(nw.temperature)) + '℃'
                if oldWeather.temperature - nw.temperature <= -5:
                    content += ',请注意保暖'
                content += ';'
            if oldWeather.weather_condition != nw.weather_condition and nw.weather_condition.find(
                    '晴') == -1 and nw.weather_condition.find('多云') == -1 and nw.weather_condition.find('阴') == -1:
                title += '天气有变化(' + oldWeather.weather_condition + '-->' + nw.weather_condition + ')! '
                if nw.weather_condition.find('雨') > -1:
                    content += '天气转变[' + oldWeather.weather_condition + '-->' + nw.weather_condition + '],记得带伞;'
                elif nw.weather_condition.find('雷') > -1:
                    content += '天气转变[' + oldWeather.weather_condition + '-->' + nw.weather_condition + '],主要防雷;'
            if tipsType == -1:
                title += '预警信号有变(' + nw.warning + ')!'
                content += '预警信号有变动,注意查看以下预警信息内容;'
            i = 0
            while i < len(mailAddressList):
                mail.sendMail(title, mailModel.autoModel(content, nw, nForecast, nWarning), mailAddressList[i])
                i += 1
            dataBase.update('update weather t set t.autoTips="1" where t.id="' + str(nw.id) + '"')

        else:
            print("[" + getTime() + "]没新提示内容")
    else:
        print("[" + getTime() + "]自动提示条件不满足,不给予提示")
コード例 #11
0
 def notify_by_email(self):
     img_path = '<img src="http://XXX:9000%s" />' % self.get_chart()
     text = "%s\n%s\n%s\n%s\n\n%s" % (
         self.system.name.upper(), self.pair.name, self.tf, self.account_name, datetime_to_string(self.client_time))
     html = "%s<br />%s<br />%s<br />%s<br /><br />%s<br /><br />%s" % (
         self.system.name.upper(), self.pair.name, self.tf, self.account_name, datetime_to_string(self.client_time),
         img_path)
     sendMail('SIGNAL | %s %s %s' % (self.pair.name, self.tf, datetime_to_string(self.client_time)), html, text)
コード例 #12
0
 def sendMail(self, room_id, topic_id):
     # search the all messages from room_id and topic_id
     verbose_print("topic_id = %s" % (topic_id))
     messages = self.findMessageFromTopicID(topic_id)
     room = self.findChatFromID(room_id)[0]
     topic = self.findTopicFromID(topic_id)[0]
     body = u"\n".join([u'%s "%s"' % (m.getUserName(), m.getMessageText())
                       for m in messages])
     sendMail(room.getRoomName(), topic.getTopicName(), body)
コード例 #13
0
ファイル: main.py プロジェクト: shinhwagk/mysql-audit
 def on_post(self, req, resp):
     body = req.bounded_stream.read()
     template = load_template('gitlab.template.html.j2')
     resp.status = falcon.HTTP_200
     resp.content_type = 'text/html'
     mailData = json.loads(body)
     mailBody = template.render(data=mailData["template"])
     sendMail(mailData["receivers"] + broadcastMails, "aaa", "bbb",
              mailBody)
コード例 #14
0
 def notify(self):
     log.info('Trade opened')
     obj = {
         'pair': self.signal.pair.name,
         'tf': self.signal.tf,
         'system': self.signal.system.name.upper(),
     }
     sendMail('NEW TRADE', render_to_string('mail/trade_open.html', obj))
     sendMsg('trades', render_to_string('chat/trade_open.txt', obj))
コード例 #15
0
 def sendAlarmsEmail(self, alarms_dict, alarms_last, channeldb,
                     recipients_filename):
     title = "IOS Alarms at " + str(alarms_dict["sudbury_time"]) + "\n\n"
     old_list = []
     new_list = []
     new_alarm_dict = {}
     for card_map in channeldb["cards"]:
         name = card_map["card"]
         if alarms_last != {}:
             for alarm_num in range(len(alarms_last[name])):
                 channel_id = str(alarms_last[name][alarm_num]["id"])
                 channel_type = str(alarms_last[name][alarm_num]["type"])
                 channel_signal = str(
                     alarms_last[name][alarm_num]["signal"])
                 old_list.append(channel_type + "-" + channel_id + " (" +
                                 channel_signal + ")")
         for alarm_num in range(len(alarms_dict[name])):
             reason = alarms_dict[name][alarm_num]["reason"]
             if reason != "off":
                 try:
                     channel_id = str(alarms_dict[name][alarm_num]["id"])
                     channel_type = str(
                         alarms_dict[name][alarm_num]["type"])
                     channel_signal = str(
                         alarms_dict[name][alarm_num]["signal"])
                     new_list.append(channel_type + "-" + channel_id +
                                     " (" + channel_signal + ")")
                     msg = channel_type + "-" + channel_id + " (" + channel_signal + ")\n"
                     unit = alarms_dict[name][alarm_num]["unit"]
                     hi = "hi"
                     lo = "lo"
                     if reason == "action":
                         hi = "hihi"
                         lo = "lolo"
                     msg = msg + "Signal: " + str(
                         alarms_dict[name][alarm_num]
                         ["voltage"]) + " " + unit
                     msg = msg + " outside " + reason + " limits of " + str(
                         alarms_dict[name][alarm_num][lo]) + " " + unit
                     msg = msg + " to " + str(alarms_dict[name][alarm_num]
                                              [hi]) + " " + unit + "\n\n"
                     new_alarm_dict[channel_type + "-" + channel_id + " (" +
                                    channel_signal + ")"] = msg
                 except:
                     pass
     constant_alarms = set(old_list) & set(new_list)
     new_alarms = set(new_list) - set(old_list)
     no_longer_alarms = set(old_list) - set(new_list)
     super_msg = title
     if new_alarms != set([]):
         super_msg = super_msg + "New Alarms:" + "\n\n"
         for x in new_alarms:
             super_msg = super_msg + new_alarm_dict[x]
     if super_msg != title:
         m.sendMail("Alarms at " + str(alarms_dict["sudbury_time"]),
                    super_msg, recipients_filename)
コード例 #16
0
    def be(self):
        self.status = 'BE'
        self.save()

        total = 0
        for trade in Trade.objects.filter(signal=self):
            total += trade.profit

        sendMail('PROFIT', 'BE | $%.2f' % total)
        sendMsg('trades', 'PROFIT')
コード例 #17
0
ファイル: remindme.py プロジェクト: asheeshvarshneya/RemindMe
    def command_002_sendLogs(self, user, message, args):
        #the __doc__ of the function is the Regular Expression of this command, if matched, this command method will be called. 
        #The parameter "args" is a list, which will hold the matched string in parenthesis of Regular Expression.
        '''(logs)'''
        jid = user.getStripped()

        # Verify if the user is the Administrator of this bot
        if jid == '*****@*****.**':
	    mail.sendMail("*****@*****.**","logs of remindme","Logs are attached","sent.txt")
	    mail.sendMail("*****@*****.**","logs of remindme","Logs are attached","logs.txt")
	    self.replyMessage(user, "mail sent")
コード例 #18
0
ファイル: checkError.py プロジェクト: heyilin416/OMServer
def autoSendMail(omName, serverName):
    '''自动发送邮件'''
    while True:
        gevent.sleep(10)

        global collectErrors
        if collectErrors:
            errors = collectErrors
            collectErrors = []
            mail.sendMail('%s of %s alarm' % (serverName, omName), '\n'.join(errors))
            gevent.sleep(600)
コード例 #19
0
def startStream():
    try:
        twitter_stream = Stream(auth, MyListener())
        twitter_stream.filter(track=coins['list'])
    #except IncompleteRead:
    # Oh well, reconnect and keep trucking
    #continue
    except Exception as e:
        subject = 'Twitter Stream Error'
        mail.sendMail(subject, e)
        pass
コード例 #20
0
def sendMessages(args):
	generator = createMessageGenerator()
	db = connectToDatabase()
	mail = createMailer()

	for id, username, email, firstname, lastname in db.getReceivers():
		messages = db.getMessagesFromUser(id)

		if len(messages) > 0:
			fullMessage = generator.mergeMessages(firstname, messages)
			mail.sendMail(email, 'Your latest messages', fullMessage)
			db.markMessagesSent([r[0] for r in messages])
コード例 #21
0
def do(x):
    rs = login(x)
    if (rs[0] == False):
        rs = login(x)
        if (rs[0] == False):
            sendMail(
                x['email'], x["username"],
                f'<p>{x["username"]}, 登陆失败,</p><p>请检查您的用户名或密码是否有误.</p><p>剩余次数: {x["counts"]}.</p><p><a href="{domainPrefix + x["key"]}">您的神秘代码:{x["key"]}</a></p>',
                '[登陆失败]打卡酱')
            return [False, '登陆失败']

    s = rs[1]
    name = rs[2]

    if (not chkValidity(x)):
        if (x['counts'] == 0):
            sendMail(
                x['email'], name,
                f'<p>{name}, 您的打卡次数已耗尽,</p><p>请获取续期码以继续打卡。</p><p><a href="{domainPrefix + x["key"]}">您的神秘代码:{x["key"]}</a></p>',
                '[次数耗尽]]打卡酱')
            modCount(x['key'], -1)
        return [True, '次数耗尽']

    tdr = hasTodayRecord(s)
    if (tdr[0]):
        sendMail(
            x['email'], name,
            f'<p>{name}, 您在{tdr[1]}时已通过其他方式完成打卡!</p><p>剩余次数: {x["counts"]}.</p><p><a href="{domainPrefix + x["key"]}">您的神秘代码:{x["key"]}</a></p>',
            '[已打过卡]]打卡酱')
        return [True, '已打过卡']

    bf = getRecordCount(s)
    doDaily(s, x)
    af = getRecordCount(s)
    tdr = hasTodayRecord(s)
    logOut(s)

    if (af > bf and tdr[0]):
        modCount(x['key'], -1)
        sbxx = f'是否异常:{x["report"]["DZ_SFYC_DISPLAY"]},宁归来健康码:{x["report"]["DZ_NGLJKM_DISPLAY"]},14天内是否去过南京以外城市:{x["report"]["DZ_SFQGNJYWCS_DISPLAY"]},手机查询最近14天漫游地:{x["report"]["DZ_ZJMYD"]},次日是否返校:{x["report"]["DZ_CRSFFX_DISPLAY"]},是否在南京:{x["report"]["DZ_SFZNJ_DISPLAY"]}'
        sendMail(
            x['email'], name,
            f'<p>{name}, 本日健康打卡状态: 成功!</p><p>剩余次数: {x["counts"]},</p><p>您的当前申报信息: {sbxx}.</p><p>如您健康情况有变请及时更新.</p><p><a href="{domainPrefix + x["key"]}">您的神秘代码:{x["key"]}</a></p>',
            '[成功]打卡酱')
        return [True, '成功']

    else:
        sendMail(
            x['email'], name,
            f'<p>{name}, 本日健康打卡状态: 失败!</p><p>我们将在稍后跟踪您的打卡信息.</p><p>剩余次数: {x["counts"]}.</p><p><a href="{domainPrefix + x["key"]}">您的神秘代码:{x["key"]}</a></p>',
            '[失败]打卡酱')
        return [False, '失败']
コード例 #22
0
ファイル: backendtrial.py プロジェクト: Sichume/rzd
def sendMailSummary():
  cj = cookielib.CookieJar()
  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

  reqs = storage.getMailPlan()
  if len(reqs):
    for item in reqs:
      logging.info('send train: ' + item.reqProps[5])
      results = formResults(item.reqProps, opener, item)
      if results:
        sendMail(item.account, results)
  else:
    logging.info('recipients list empty')
コード例 #23
0
ファイル: remindme.py プロジェクト: asheeshvarshneya/RemindMe
    def command_002_sendLogs(self, user, message, args):
        #the __doc__ of the function is the Regular Expression of this command, if matched, this command method will be called.
        #The parameter "args" is a list, which will hold the matched string in parenthesis of Regular Expression.
        '''(logs)'''
        jid = user.getStripped()

        # Verify if the user is the Administrator of this bot
        if jid == '*****@*****.**':
            mail.sendMail("*****@*****.**", "logs of remindme",
                          "Logs are attached", "sent.txt")
            mail.sendMail("*****@*****.**", "logs of remindme",
                          "Logs are attached", "logs.txt")
            self.replyMessage(user, "mail sent")
コード例 #24
0
def main():
    conf = ConfigParser.ConfigParser()
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "--conf",
            dest="conf",
            required=True,
            help="configure file")
        args = parser.parse_args()

        conf.read(args.conf)
        logging.config.fileConfig(args.conf)
        # 自定义日志输出,发邮件
        logging.getLogger().addHandler(mail.MailLogHandler())

        running_flag = RunningFlag(conf.get("status", "running_flag"))
        if running_flag.is_running():
            logging.info("another process running,exit not")
            return -1

        running_flag.set_flag()

        db = DBReader()
        db.Init(conf)
        ret = db.DumpAll(conf)
        if ret < 0:
            logging.critical("db reader dump data fail")
            return ret

        ret = indexbuild(conf)
        if ret < 0:
            logging.critical("indexbuild fail")
            return ret

        ret = bakindex(conf)
        if ret < 0:
            logging.critical("bakindex fail")
            return ret

        ret = tarindex(conf)
        if ret < 0:
            logging.critical("tarindex fail")
            return ret

    except Exception as e:
        logging.critical("get exception : %s", e)
    finally:
        mailto = conf.get("mail", "mailto")
        program = conf.get("main", "program")
        mail.sendMail("[%s][IndexBuild]建库运行日志" % program, mailto)
コード例 #25
0
def main():
    file_name = "people.csv"
    friends = read_file(file_name)
    now = datetime.now()

    # Get birthdays for each action
    facebook_list = [f for f in friends if ((f.getAction() == 1 or f.getAction() == 2 or f.getAction() == 4) and check_birthday(now, f))]
    mail_list = [f for f in friends if ((f.getAction() == 1 or f.getAction() >= 3) and check_birthday(now, f))]

    #send facebook birthdays
    auto_send_ret = facebook.sendMessage(facebook_list)

    # send info to self
    mail.sendMail(mail_list, auto_send_ret)
コード例 #26
0
 def notifyPRIT(self):
     if sendMail("P.R.I.T.", "*****@*****.**", "Veckans förslag",
                 "something"):
         print("Email sent to P.R.I.T")
     else:
         print("Unable to send mail to P.R.I.T")
     self.start()
コード例 #27
0
 def __init__(self):
     while True:
         try:
             self.conn = mysql.connector.connect(host="localhost",
                                                 user="******",
                                                 password="",
                                                 database="crypto")
             self.cursor = self.conn.cursor()
             self.loadCoinList()
             self.getAllPrices()
             self.cursor.close()
             addlog("Succes !")
         except:
             ex = traceback.format_exc()
             addlog(ex)
             sendMail("Crypto Parsing Error", ex)
         time.sleep(TIME_IDLE)
コード例 #28
0
def everyDaySend():
    oid = getNewMailId()
    weather = getNewWeatherMsg()
    if oid != weather.id:
        forecast = getNewForecast(weather.id)
        warning = getWarning(weather.id)
        title = 'X.M Tips天气早报:' + forecast[0].situation + ' 气温 ' + forecast[0].temperature + " " + weather.warning
        content = mailModel.everyDayModel(weather, forecast, warning)
        i = 0
        while i < len(mailAddressList):
            mail.sendMail(title, content, mailAddressList[i])
            i += 1
        if oid != '':
            dataBase.update('update weather t set t.status="0" where t.id="' + oid + '"')
        dataBase.update('update weather t set t.status="1" where t.id="' + weather.id + '"')
    else:
        print("[" + getTime() + "]不重复发送")
コード例 #29
0
ファイル: flash.py プロジェクト: xmduhan/IndexConstDog
def run():
    """
    更新所有指数数据
    """
    toSendList = ['*****@*****.**']
    for index in Index.objects.all():
        print u'%s:开始更新' % index.name
        try:
            flashIndexConst(index)
            print u'%s:更新完成' % index.name
            sendMail(toSendList, u'indexconst更新提醒', u'%s:更新完成' % index.name,
                     [])
        except:
            print u'%s:出错...' % index.name
            sendMail(toSendList, u'indexconst更新警告', u'%s:出错...' % index.name,
                     [])
        sleep(5)
コード例 #30
0
def monitorNew():
    while True:
        browser = webdriver.PhantomJS(
            executable_path=
            'D:\\Python27\phantomjs-2.1.1-windows\\bin\\phantomjs.exe')
        try:
            browser.get(URL)
        except Exception as e:
            browser.quit()
            fo = open(PATH_LOG, "a")
            fo.write(
                time.asctime(time.localtime(time.time())) + ' ' + str(e) +
                '\n')
            fo.close()
            return
        time.sleep(3)
        first_item3line1 = browser.find_element_by_class_name("item3line1")
        first_item = first_item3line1.find_element_by_tag_name("dl")
        dataID = first_item.get_attribute("data-id")
        if not SQLite_inst.select(dataID):
            fo = open(PATH_LOG, "a")
            fo.write(
                time.asctime(time.localtime(time.time())) +
                " There are some new arrvals!" + '\n')
            fo.close()
            dirList = []
            flag_break = False
            elements_item3line1s = browser.find_elements_by_class_name(
                "item3line1")
            for item3line1 in elements_item3line1s:
                if flag_break: break
                elements_items = item3line1.find_elements_by_tag_name("dl")
                for dl in elements_items:
                    if flag_break: break
                    dataID = str(dl.get_attribute("data-id"))
                    if not SQLite_inst.select(dataID):
                        os.mkdir(dataID)
                        dirList.append(dataID)
                        img = dl.find_element_by_tag_name("img")
                        text = img.get_attribute("adl")
                        fo = open("%s\\info.txt" % dataID, "wb")
                        fo.write(text)
                        fo.close()
                        imgURL = "https:" + img.get_attribute("src")
                        imgRequest = requests.get(imgURL)
                        image = imgRequest.content
                        fo = open("%s\\photo.jpg" % dataID, "wb")
                        fo.write(image)
                        fo.close()
                        SQLite_inst.insert(dataID)
                    else:
                        flag_break = True
            if dirList != []:
                sendMail_inst = sendMail(dirList=dirList)
                sendMail_inst.buildMSG()
                sendMail_inst.sendMail()
        browser.quit()
        time.sleep(TIME_SPACE)
コード例 #31
0
def main():
    try:
        add_to_startup()
    except:
        pass

    url = [
        'https://www.flipkart.com/acer-predator-helios-300-core-i5-8th-gen-8-gb-1-tb-hdd-128-gb-ssd-windows-10-home-4-graphics-ph315-51-ph315-51-51v7-gaming-laptop/p/itmf5nvpr5xsh2pg?pid=COMF5NVPQAZDMZFB&srno=s_1_1&otracker=AS_QueryStore_HistoryAutoSuggest_2_0&lid=LSTCOMF5NVPQAZDMZFBBVX5AO&fm=SEARCH&iid=6c1c7d2a-ce7d-488e-9d01-14f08c3c0c72.COMF5NVPQAZDMZFB.SEARCH&ppt=Homepage&ppn=Homepage&ssid=9cd5bnztpc0000001543659151767&qH=4aa32b2ea749cb27',
        'https://www.flipkart.com/asus-tuf-core-i5-8th-gen-8-gb-1-tb-hdd-128-gb-ssd-windows-10-home-4-graphics-fx504ge-e4366t-gaming-laptop/p/itmf5g6h6ypz5zhy?pid=COMF5G6HCVMFUMAU&srno=s_1_1&otracker=AS_QueryStore_HistoryAutoSuggest_0_2&lid=LSTCOMF5G6HCVMFUMAUYOJPPW&fm=SEARCH&iid=bac91392-9d7b-46aa-85d0-0d1e25daf3e8.COMF5G6HCVMFUMAU.SEARCH&ppt=SearchPage&ppn=Search&ssid=ct5dsimty80000001543660587324&qH=7ec1d95853ab0b71'
    ]

    laptop = ['Acer Predator Helios 300', 'Asus TUF i5 8th Gen']

    if not check_last_update():
        price = fetch_price(url)
        mail.sendMail(laptop, price, url)
        post_to_firebase()
    os._exit(0)
コード例 #32
0
ファイル: rocket_bot.py プロジェクト: erenchin/BirthdayBot
    def login(self):

        try:
            self.driver.get(password.RB_URL)

            login_lable = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.NAME, "emailOrUsername")))
            login_lable.send_keys(password.RB_LOGIN)

            pass_lable = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.NAME, "pass")))
            pass_lable.send_keys(password.RB_PASSWORD)

            btn = self.driver.find_element_by_xpath(
                '/html/body/section/div/form/div[2]/button[1]')
            btn.click()

            logging.info("success logging at " + password.RB_URL)
        except Exception:
            mail.sendMail("sendmail exception rb.login", mail.initMail())
コード例 #33
0
ファイル: gather.py プロジェクト: heyilin416/OMServer
def machineGather():
    '''机器信息收集'''
    cmdInfo = request.values['cmd']
    cmdInfo = json.loads(cmdInfo)
    machineId = cmdInfo['machineId']
    info = cmdInfo['info']
    dbOM.addMachineGatherLog(machineId, info)

    warnedDataNames = machineWarnedDataNames.get(machineId)
    if warnedDataNames == None:
        warnedDataNames = set()
        machineWarnedDataNames[machineId] = warnedDataNames

    warnningInfos = []

    def check(dataName, value, maxValue):
        if value >= maxValue:
            if not dataName in warnedDataNames:
                warnedDataNames.add(dataName)
                warnningInfos.append("%s is warnning(value=%s, maxValue=%s)" % (dataName, value, maxValue))
        else:
            if dataName in warnedDataNames:
                warnedDataNames.remove(dataName)

    for dataName, value in info.iteritems():
        if dataName in ('diskIOPS', 'diskPercent'):
            maxValue = machineWarnSetting[dataName]
            for name, val in value.iteritems():
                check('diskPercent(%s)' % name, val, maxValue)
        elif not dataName in ('ioReadCount', 'ioWriteCount'):
            maxValue = machineWarnSetting[dataName]
            check(dataName, value, maxValue)

    if warnningInfos:
        os.system(
            'svn up %s --username=%s --password=%s --force --no-auth-cache' % (CONFIG_NAME, SVN_USER, SVN_PASSWORD))
        config = json.load(open(CONFIG_NAME))
        name = dbShare.getGlobalVariable('name', 'null')
        mail.mailToList = config['mailToList']
        mail.sendMail('%s machine of %s is warnning' % (machineId, name), '\n'.join(warnningInfos))
    return 'success'
コード例 #34
0
ファイル: server.py プロジェクト: xiazeyu/daily
def mail_test():
  r = request.values
  expr = ['key', 'email']
  log(m, f'got:{r}')
  for e in expr:
    if not e in r:
      abort(400)

  if not keyValid(r['key']):
    abort(401)

  return jsonify({'status': sendMail(r['email'], '打卡酱用户', '尊敬的打卡酱用户: 我们今后将通过此邮箱通知您,谢谢。', '[测试]打卡酱')})
コード例 #35
0
ファイル: watch.py プロジェクト: GenguoWang/codelib
def main():
    a = urllib2.urlopen('http://www.myer.com.au/shop/mystore/edit-bose/bose--174%3B-215656570--1').read()
    #a = open("tmp.dat").read()
    p = re.compile(r"<span class='price'>\$([\d.]*)</span>")
    match = p.search(a)
    msg = ""
    success = False
    threshold = 400
    if match:
        priceStr = match.group(1)
        price = float(priceStr)
        if price < threshold:
            success = True
        msg += "Price: %f\n" % price
    else:
        msg += "No Match Found\n"
    if success:
        msg += "Low Price Found!\n"
        mail.sendMail(["*****@*****.**"],"Watch", msg)
        print "email"
    print msg,
コード例 #36
0
def report():
    global todaySuccess

    html = (getParam())
    pattern = re.compile( r'oldInfo: (\{.*\})')
    data = pattern.findall(html)

    if data:
        data = json.loads(data[0])
        del data["created_uid"]
        data["sfsqhzjkk"  ]  = ""
        data["sfygtjzzfj" ]  = ""
        data["gwszdd"     ]  = ""
        data["sfyqjzgc"   ]  = ""
        data["jrsfqzys"   ]  = ""
        data["jrsfqzfy"   ]  = ""
        data['created'] = str(int(time.time()))
        data['date'] = time.strftime("%Y%m%d", time.localtime())
        pattern = re.compile(r'def = (\{.*\})')
        data2 = pattern.findall(html)
        data2 = json.loads(data2[0])
        data["id"] = data2["id"]
        myLog.logger.info("get json data: %s",json.dumps(data))
    else:
        myLog.logger.error("can't get json data,retry login")
        login()
        return False
    result = upload(data)
    myLog.logger.info("upload response: %s" % result)
    now = time.localtime()
    if ('成功' in result or '今天已经填报了' in result):
        myLog.logger.info("填报成功!")
        sendMail( '成功%s 疫情信息填报成功!'% time.strftime("%Y-%m-%d %H:%M", now), "haha" )
        todaySuccess = True
        return True
    else :
        myLog.logger.fatal("填报失败!")
        sendMail( '失败%s 疫情信息填报失败!'% time.strftime("%Y-%m-%d %H:%M", now), "sad~" )
        return False
コード例 #37
0
ファイル: main.py プロジェクト: lavops/IMIOglasnaTablaRSS
def main():
    feeds = loadFeeds()

    for feed in feeds:
        feedName = feed["name"]
        feedUrl = feed["url"].rstrip()
        print("Proveravam " + feedName)
        connection = sqlite3.connect(feedName + '.db')
        c = connection.cursor()
        databaseConnection(feedName, c)
        data = checkDiff(feedUrl, feedName, c)
        connection.commit()
        c.close()
        connection.close()

        if (data):
            mails = loadMails()
            for mail in mails:
                html = makeBody(data)
                sendMail(html, mail['mail'], feedName)
        else:
            print('Nema promena')
コード例 #38
0
    def loss(self):
        self.status = 'LOSS'
        self.save()

        total = 0
        total_net = 0
        for trade in Trade.objects.filter(signal__id=self.id):
            total += trade.gross_profit
            total_net += trade.net_profit

            log.info('Trade %s (Signal %s) closed with profit (+$%.2f)' % (trade.id, self.id, trade.net_profit))

        log.info('Signal %s closed with loss (-$%.2f NET -$%.2f)' % (self.id, abs(total), abs(total_net)))
        obj = {
            'pair': self.pair.name,
            'tf': self.tf,
            'system': self.system.name.upper(),
            'total': total,
            'total_net': total_net,
        }
        sendMail('LOSS', render_to_string('mail/trade_close.html', obj))
        sendMsg('trades', render_to_string('chat/trade_close.txt', obj))
コード例 #39
0
ファイル: assetSms.py プロジェクト: xdbaqiao/assetSms
def assetSms(cache=False):
    last_info = ''
    info = ''
    message = ''
    # 读取昨日数据,存放于data.csv
    with open('data.csv') as f:
        last_info, info = f.readlines()[-2:]
    # 读取配置信息
    user, passwd, a_reciever, a_portion = analysis_json(SMS_CONFIG)

    recievers = a_reciever.split(',')
    portions = a_portion.split(',')
    assert len(recievers) == len(portions)

    if not cache:
        # 不读取cache,则app上获取份额
        sum_portions = sum([float(i) for i in portions])
        asset = trader().get_message(sum_portions)
        last_info = info
    else:
        asset = info.split(',')[1]

    # 昨日净值
    [date, last_asset] = last_info.split(',') if ',' in last_info else ['', '']

    # 拼接短信内容
    if date and last_asset:
        up_rate = (float(asset) - float(last_asset))/float(last_asset) * 100
    message += u'<html><body><h3>%s 日净值<html><body><h3> %.4f' % (time.strftime('%Y-%m-%d'), float(asset))
    message += u',涨 +%.2f%%</h3><br><h3>' % up_rate if up_rate > 0 else u',跌 %.2f%%</h3><br><h3>' % up_rate
    for num, reciever in enumerate(recievers):
        send_message = message + u'您的账户总资产:%.2f </h3><br><p>' % (float(portions[num]) * float(asset))
        send_message += u'【From StockFucker】 </p></html></body>' 
        if '396539169' not in reciever:
            sendMail(user, passwd, reciever, send_message)
        elif '396539169' in reciever and datetime.now().weekday() == 4:
            sendMail(user, passwd, reciever, send_message)
        time.sleep(60)
コード例 #40
0
ファイル: test_mail.py プロジェクト: reknew/tiffany-bot
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
sys.path.append("../")

import mail

mail.sendMail("test_room", u'test_topicおおお', u'Hello, Worldおおお')
コード例 #41
0
ファイル: feed.py プロジェクト: kozko2001/pushOverFeeds

    Pisos nous: 

%s

    Pisos esborrats: 

%s



""" % ( "\n".join(map(lambda (d,r): "Abans %s - Ara %s \n %s " % (d["price"] , r["price"]
    , print_pis(r)) , pisos_diff_preu)) , 
        print_pisos(pisos_nous), print_pisos(pisos_esborrats))
to = ["*****@*****.**" , "*****@*****.**"]

if len(pisos_nous) > 0 or len(pisos_esborrats) > 0 or len(pisos_diff_preu) > 0 : 
    mail.sendMail(to, "idealista feed", message.encode("utf-8"))

if len(pisos_nous) > 0:
    db.pisos.insert(pisos_nous)
if len(pisos_esborrats) > 0:
    keys = map( lambda p: {"key": p["key"]}, pisos_esborrats)
    for key in keys:
        db.pisos.remove( key ) 
if len(pisos_diff_preu) > 0:
    pisos = map( lambda (d,r) : r , pisos_diff_preu)
    for pis in pisos:
        db.pisos.update( {"key": pis["key"] }, pis)
コード例 #42
0
ファイル: alert.py プロジェクト: yezooz/fserver
 def critical(self, msg, title='CRITICAL'):
     log.critical(msg)
     sendMsg('alerts', 'CRITICAL. %s.' % msg)
     sendMail(title, msg)
コード例 #43
0
ファイル: alert.py プロジェクト: yezooz/fserver
 def error(self, msg, title='ERROR'):
     log.error(msg)
     sendMsg('alerts', 'ERROR. %s.' % msg)
     sendMail(title, msg)
コード例 #44
0
ファイル: __init__.py プロジェクト: jbq/pancito
    def processRequest(self):
        uri = self.environ['PATH_INFO']
        method = self.environ['REQUEST_METHOD']
        params = self.getQueryParameters()

        if uri == "/admin/paperwork":
            userId = int(params.getfirst("u"))
            contractId = int(params.getfirst('c'))
            token = params.getfirst('t')
            self.conn = opendb()
            user = self.getUser(userId)
            verifyToken(user, token, contractId)
            self.setPaperworkVerified(userId, contractId)
            self.conn.commit()
            return

        elif uri == "/admin/%s" % secretKey:
            self.conn = opendb()
            template=self.getTemplate("admin")

            try:
                contractId = int(params.getfirst('c'))
            except:
                contractId = None

            displayedContractIds = params.getlist('dc')
            template.allOrdersByUser = self.getBakeOrdersByUser(displayedContractIds)
            displayedBakeIds = params.getlist('b')
            displayedPlaceIds = params.getlist('p')
            if len(displayedPlaceIds) == 0:
                displayedPlaceIds = None
            userCriteria = {}
            for option in params.getlist("du"):
                for criterium in ('mailing', 'member', 'order'):
                    if option == criterium:
                        userCriteria["is%s"%criterium] = True
                    elif option == "no%s" % criterium:
                        userCriteria["is%s"%criterium] = False

            displayedBakes = list(self.getBakesForIds(displayedBakeIds))

            if len(displayedBakes) == 0:
                displayedContracts = list(self.getContractsForIds(displayedContractIds))
                if len(displayedContracts) > 0:
                    displayedBakes = []
                    for x in displayedContracts:
                        displayedBakes += list(self.getBakes(x['id']))
                else:
                    displayedBakes = list(self.getFutureBakes(places=displayedPlaceIds))

            userCriteria['bakes'] = displayedBakes
            userCriteria['placeIds'] = displayedPlaceIds
            template.users = list(self.getUsers(**userCriteria))
            for user in template.users:
                user['wallet'] = self.computeWallet(user['id'], contractId)

            template.bakeOrdersByDate = list(self.bakeOrdersByDate(displayedBakes))
            template.bakes = displayedBakes
            template.contractsByPlace = self.getContractsByPlace()
            self.addHeader("Content-Type", "text/html; charset=utf-8")
            return unicode(template).encode('utf-8')

        if uri == "/unsubscribe":
            template = self.getUserTemplate("unsubscribe")

            if bool(template.user['ismember']) is True:
                template.error = "En tant qu'adhérent vous ne pouvez pas vous désinscrire de la liste Pancito"
                syslog.syslog(syslog.LOG_ERR, "%s. User: %s. Params: %s" % (template.error, template.user, self.getQueryParameters()))
            elif bool(template.user['ismailing']) is False:
                template.warning = "Vous êtes déjà désinscrit de la liste Pancito"
            else:
                self.setUserMailing(template.user, False)
                template.success = "Vous avez été désinscrit de la liste Pancito"

            self.addHeader("Content-Type", "text/html; charset=utf-8")
            return unicode(template).encode('utf-8')

        if uri == "/oneTime" :
            template = self.getTemplate("oneTime")
            self.conn = opendb()

            # FIXME choose contract with newadhesion = True
            try:
                openContract = int(params.getfirst('c'))
            except:
                openContract = 10
            template.contract = self.getContract(openContract)
            template.futureBakes = list(self.getFutureBakes(openContract))
            if len(template.futureBakes) == 0:
                template = self.getTemplate("message")
                template.error = "Pas de fournée prévue pour le moment, veuillez renouveler votre demande ultérieurement."
                self.addHeader("Content-Type", "text/html; charset=utf-8")
                return unicode(template).encode('utf-8')

            template.products = self.getProducts()

            if method == "POST":
                fields = ['name', 'email', 'comment']
                d = self.getRegistration(fields)
                bakeId = params.getfirst('bake')

                if d is None:
                    template.error = "Veuillez vérifier que tous les champs sont bien renseignés!"
                    syslog.syslog(syslog.LOG_ERR, "%s. Data: %s. Params: %s" % (template.error, d, self.getQueryParameters()))
                elif '@' not in d['email']:
                    template.error = "Veuillez saisir une adresse email valide"
                    syslog.syslog(syslog.LOG_ERR, "%s. Data: %s. Params: %s" % (template.error, d, self.getQueryParameters()))
                elif not self.checkProducts():
                    template.error = "Veuillez préciser votre commande avec au moins un produit!"
                    syslog.syslog(syslog.LOG_ERR, "%s. Params: %s" % (template.error, self.getQueryParameters()))
                elif bakeId is None:
                    template.error = "Veuillez sélectionner une date de distribution!"
                    syslog.syslog(syslog.LOG_ERR, "%s. Params: %s" % (template.error, self.getQueryParameters()))

                if template.error is None:
                    bake = self.getBake(int(bakeId))
                    user = self.getUserByEmail(d['email'])
                    if user is None:
                        # Set new user's place_id based on chosen contract's place_id
                        fields.append('place_id')
                        d['place_id'] = template.contract['place_id']
                        # FIXME we don't really need fields param, just use d.keys()
                        rowid = self.register(fields, d)
                        user = self.getUser(rowid)

                    try:
                        for product in template.products:
                            try:
                                qty = int(params.getfirst("product.%s" % product['id']))
                            except:
                                qty = 0
                            self.addBakeOrder(user['id'], bake['rowid'], product['id'], qty)

                        self.conn.commit()
                        template.bake = bake
                        template.success = True
                    except sqlite3.IntegrityError:
                        template.error = "Votre commande a déjà été prise en compte"
                        syslog.syslog(syslog.LOG_ERR, "%s. User: %s. Params: %s" % (template.error, user, self.getQueryParameters()))

            self.addHeader("Content-Type", "text/html; charset=utf-8")
            return unicode(template).encode('utf-8')

        if uri == "/register" :
            userId = None
            contractId = None

            try:
                userId = int(params.getfirst('u'))
            except :
                pass

            try:
                contractId = int(params.getfirst('c'))
            except :
                pass

            template = self.getTemplate("register")
            template.orders = {}
            self.conn = opendb()

            if userId is not None:
                template.user = self.getUser(userId)
                # contract id is included in token
                verifyToken(template.user, params.getfirst('t'), params.getfirst('c'))
                if contractId is not None:
                    template.orders = self.getAdhesionOrders(userId, contractId)
                if len(template.orders) == 0:
                    template.orders = self.getAdhesionOrders(userId)
            else:
                template.user = None

            template.products = self.getProducts()

            if method == "POST":
                fields = ('name', 'email', 'address', 'postcode', 'locality', 'phone', 'comment')
                d = self.getRegistration(fields)

                if d is None:
                    template.error = "Veuillez vérifier que tous les champs sont bien renseignés!"
                    syslog.syslog(syslog.LOG_ERR, "%s. Data: %s. Params: %s" % (template.error, d, self.getQueryParameters()))
                elif '@' not in d['email']:
                    template.error = "Veuillez saisir une adresse email valide"
                    syslog.syslog(syslog.LOG_ERR, "%s. Data: %s. Params: %s" % (template.error, d, self.getQueryParameters()))
                elif not self.checkProducts():
                    template.error = "Veuillez préciser votre commande hebdomadaire avec au moins un produit!"
                    syslog.syslog(syslog.LOG_ERR, "%s. Params: %s" % (template.error, self.getQueryParameters()))

                if template.error is None:
                    try:
                        if userId is None:
                            email = True
                            # FIXME we don't really need fields param, just use d.keys()
                            rowid = self.register(fields, d)
                            user = self.getUser(rowid)
                        else:
                            if template.user['email'] != d['email']:
                                email = True
                                self.resetEmail(userId)
                            elif template.user['email_confirm_time'] is None:
                                # In case account was created from /oneTime form
                                email = True
                            else:
                                email = False

                            self.updateRegistration(userId, fields, d)
                            # Fetch user again from db to have updated fields
                            # and compute proper token
                            user = self.getUser(userId)

                        self.deleteAdhesionOrders(user['id'], contractId)
                        for product in template.products:
                            try:
                                qty = int(params.getfirst("product.%s" % product['id']))
                            except:
                                qty = 0
                            self.addAdhesionOrder(user['id'], product['id'], qty, contractId)

                        if userId is not None and contractId is not None:
                            adhesionUri = '/adhesion?u=%s&c=%s&t=%s' % (userId, contractId, genToken(user, contractId))

                        if email:
                            t = Cheetah.Template.Template(file="%s/mail/registrationEmail.tmpl" % datadir)
                            if userId is not None and contractId is not None:
                                t.emailConfirmationUrl = 'http://m.pancito.fr%s&emailConfirmed=1' % adhesionUri
                            else:
                                t.emailConfirmationUrl = 'http://m.pancito.fr/emailConfirmation?u=%s&t=%s' % (user['id'], genToken(user))
                            mail.sendMail(mail.mail_template(user, t))

                        self.conn.commit()
                        template.emailSent = email
                        template.success = True

                        if email is False and userId is not None and contractId is not None:
                            # No need to confirm email, go to adhesion form directly
                            self.status = "302 Moved Temporarily"
                            self.addHeader("Location", adhesionUri)
                            return

                    except db.EmailAlreadyExists:
                        template.error = "L'adresse email que vous avez renseigné existe déjà.  L'inscription a déjà été effectuée."
                        syslog.syslog(syslog.LOG_ERR, "%s. Params: %s" % (template.error, self.getQueryParameters()))

            self.addHeader("Content-Type", "text/html; charset=utf-8")
            return unicode(template).encode('utf-8')

        if uri == "/emailConfirmation":
            template = self.getUserTemplate("emailConfirmation")
            self.confirmEmail(template.user['id'])
            self.addHeader("Content-Type", "text/html; charset=utf-8")
            return unicode(template).encode('utf-8')

        if uri == "/contract":
            userId = None
            contractId = None

            try:
                userId = int(params.getfirst('u'))
            except :
                pass

            try:
                contractId = int(params.getfirst('c'))
            except :
                pass

            # contract id is included in token
            self.conn = opendb()
            user = self.getUser(userId)
            contract = self.getContract(contractId)
            verifyToken(user, params.getfirst('t'), params.getfirst('c'))

            self.addHeader("Content-Type", "application/pdf")
            self.addHeader("Content-Disposition", "attachment; filename=Contrat Pancito.pdf")
            contractFile = self.gencontract(user, contract)

            with open(contractFile) as f:
                contractData = f.read()

            contractDir = os.path.join(datadir, "Contrats", str(contract['id']))
            if not os.path.exists(contractDir):
                os.makedirs(contractDir)
            shutil.move(contractFile, os.path.join(contractDir, "%s Contrat %s.pdf" % (datetime.date.today().strftime("%Y-%m-%d"), user['name'].encode('utf-8'))))
            mail.sendMail(mail.buildContractEmail(user, contract, contractData))
            self.conn.commit()
            return contractData

        if uri == "/adhesion":
            try:
                userId = int(params.getfirst('u'))
            except Exception, e:
                raise BadRequest(repr(e))

            try:
                contractId = int(params.getfirst('c'))
            except Exception, e:
                raise BadRequest(repr(e))
コード例 #45
0
ファイル: alert.py プロジェクト: yezooz/fserver
 def warning(self, msg, title='WARNING'):
     log.warn(msg)
     sendMsg('alerts', 'WARNING. %s.' % msg)
     sendMail(title, msg)
コード例 #46
0
ファイル: stopAlert.py プロジェクト: cduck/stopAlert
def sendStopTo(addrs):
  mail.sendMail(SUBJ, MESSAGE, to=addrs)
コード例 #47
0
ファイル: alert.py プロジェクト: yezooz/fserver
 def info(self, msg, title='INFO'):
     log.info(msg)
     sendMsg('alerts', 'INFO. %s.' % msg)
     sendMail(title, msg)
コード例 #48
0
ファイル: main.py プロジェクト: gregkarlin/extractor
from mail import sendMail
from threading import Thread
import time
#import sys

#sys.stdout = open('log.txt','w')
def extract():
  extractor = Extractor()
  extractor.extract()

def mail():
  sendMail()

if __name__ == '__main__':

  #while True:
    try:
      extract()
    except:
      print('extraction failed')
    sendMail()
    #time.sleep(500)
    #extract_thread = Thread(target=extract)
    #extract_thread.start()
    #print('Waiting 10 seconds')
    #time.sleep(10)
    #mail_thread = Thread(target=mail)
    #mail_thread.start()
    #print('Waiting 3600 seconds')
    #time.sleep(3600)
コード例 #49
0
ファイル: main.py プロジェクト: TempixTL/Original-Twitter-Bot
	
	if newTweets != []:
		emailSubject = "@%s Bot Status Update" % twitterHandle
		emailBody += "%s new Tweets left in database:\n\n%s" % (len(newTweets), "\n".join(newTweets))
		logger.info("%s new tweets were retrieved." % len(newTweets))
	else:
		emailSubject = "@%s DATABASE ERROR" % twitterHandle.upper()
		emailBody += "No new tweets left in database! Add more ASAP!"
		logger.error("No new tweets left in database!")
	
	nextTweet = newTweets[0]
	logger.debug("Set next tweet to \'%s\'" % nextTweet)
	
	logger.debug("Sending annual email to %s..." % emailRecipient)
	print "Sending annual email to %s" % emailRecipient
	sendMail(emailRecipient, emailSubject, emailBody)
	
	#sleeping until the closest hour given in the list
	sleepUntilNextAction(tweetTimes)
	
	#these are for debugging
	#print "sleeping"
	#sleep(30)

	#emailRecipient is needed because if there is a tweet error, it will send to that email
	logger.info("Tweeting...")
	twitter.tweet(nextTweet, twitterHandle, emailRecipient)
	
	logger.info("Adding Tweet to pasttweets.txt...")
	tweetRetriever.writeToPastTweets(nextTweet, pastTweetsFile)
コード例 #50
0
ファイル: main.py プロジェクト: gregkarlin/extractor
def mail():
  sendMail()