Exemplo n.º 1
0
def create_user(email, school, ip):
    # verify_email_address(email)
    password = User.objects.make_random_password()
    token = ''.join(random.SystemRandom().choice(string.ascii_lowercase +
                                                 string.digits)
                    for _ in range(40))
    welcome_token = ''.join(
        random.SystemRandom().choice(string.ascii_lowercase +
                                     string.ascii_uppercase + string.digits)
        for _ in range(60))
    try:
        user_obj = User.objects.create_user(email=email,
                                            school=school,
                                            password=password,
                                            token=token,
                                            welcomeToken=welcome_token,
                                            registrationIP=ip)
    except IntegrityError:
        raise DuplicateEmailError()
    user_obj.interestedInSchools.set(School.objects.all().values_list(
        'id', flat=True))
    user_obj.save()
    send_mail(user_mail=email,
              password=password,
              subject='welcome',
              welcome_token=welcome_token)
Exemplo n.º 2
0
def main():
    global total

    data = {
        'xnxqdm': '201702',
        'page': 1,
        'rows': 50,
        'sort': 'xnxqdm',
        'order': 'asc',
    }

    url = 'http://jxfw.gdut.edu.cn/xskccjxx!getDataList.action'
    rsp = ss.post(url, headers=headers, data=data)
    score = rsp.json()

    try:
        newtotal = score.get('total')
        if newtotal:
            print('{}查询成功!'.format(datetime.datetime.utcnow()))
        if newtotal > total:  # 条数增加,有更新!
            total = newtotal
            msg = {}
            for item in score.get('rows'):
                subject = item.get('kcmc')
                six = item.get('zcj')
                msg[subject] = six

            send_mail(json.dumps(msg, indent=2, ensure_ascii=False))
    except Exception as e:
        send_mail(str(e))
        exit(1)
Exemplo n.º 3
0
def check(count=1):

    # get attachments from number of files
    attachments = mail.get_attachments(config.imap, count)
    recognized_text = []
    if attachments:
        for attachment in attachments:
            # get sender and batch of files
            sender = attachment[0][0]
            files = attachment[1]
            print("Checking letter from {}. Number of attachments: {}".format(
                sender, len(files)))
            if files:
                for file in files:
                    text = ocr.image_to_text(file)
                    recognized_text.append(text)
            else:
                mail.send_mail(config.smtp, sender, mail.messages['not found'])
                print("No files in mail. Email sent to {}".format(sender))

            if len(recognized_text) == len(files):
                for text in recognized_text:
                    # new_reciept = db.Reciept()
                    # new_reciept.id = text
                    # new_reciept.add()
                    print("Got some text:\n{}".format(text))
            else:
                mail.send_mail(config.smtp, sender, mail.messages['undefined'])
    else:
        print("No mails")
Exemplo n.º 4
0
 def e_mail(self):
     prices = []
     for item in self.item_list:
         prices.append(self.make_link(item))
     day = datetime.now().strftime("%d-%m-%Y")
     message = "".join(prices)
     send_mail(message.encode("ascii", errors="ignore").decode(), day)
Exemplo n.º 5
0
def send_subscribers_email(sender, instance, **kwargs):
    article = instance
    
    if settings.ENABLE_EMAIL:
        subject = u'您订阅的【残阳似血的博客】上的文章有了更新'
        from_email = settings.EMAIL_HOST_USER
        t = loader.get_template("blog/coolblue/subscriberemail.tpl")
        
        for subscriber in Subscriber.enabled_objects.all():
            if ArticleSubscriber.objects.filter(article=article, subscriber=subscriber).count() == 0:
                article_subscriber = ArticleSubscriber(article=article, subscriber=subscriber)
                article_subscriber.save()
                
                to_email = [subscriber.email_address, ]
                
                c = Context({
                    'article': article,
                    'subscriber': subscriber,
                    'parameter': urllib.urlencode({
                                   'email': to_email[0],
                                   'hv': hashlib.md5("%s%s"%(to_email[0], str(subscriber.subscribe_time))).hexdigest()
                                   }),
                    'site': settings.SITE
                })
                html = t.render(c)
                plain_text = strip_html(html)
                send_mail(subject, plain_text, from_email, to_email, html=html)
Exemplo n.º 6
0
def send_email(sender, instance, **kwargs):
    comment = instance
    
    if settings.ENABLE_EMAIL and comment.visible == True:
        t = loader.get_template("blog/coolblue/email.tpl")
        type = 0 if comment.content_type.model == 'article' else 1
        
        c = Context({
            'type': type,
            'comment': comment,
            'site': settings.SITE
        })
        
        html = t.render(c)
        plain_text = strip_html(html)
        
        subject = ''
        to_email = ''
        if not comment.reply_to_comment:
            to_email = [settings.ADMINS[0][1], ]
            if type == 0:
                subject = u'【残阳似血的博客】上的文章刚刚被%s评论了' % comment.username
            else:
                subject = u'【残阳似血的博客】刚刚收到%s的留言' % comment.username
        else:
            to_email = [comment.reply_to_comment.email_address, ]
            if type == 0:
                subject = u'您在【残阳似血的博客】上的评论刚刚被%s回复了' % comment.username
            else:
                subject = u'您在【残阳似血的博客】上的留言刚刚被%s回复了' % comment.username
        
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, plain_text, from_email, to_email, html=html)
Exemplo n.º 7
0
def create_handler(d):
    proj_name = d['req_body']['repository']['name']
    proj_vers = d['req_body']['ref']

    common_cfg, proj_cfg = load_conf(proj_name)

    build_script  = common_cfg['script']

    send_from = common_cfg['send_from']
    send_to   = proj_cfg['notify']

    msg = 'See details in the attachment below\n' + common_cfg['storage_url']

    for dist in proj_cfg['dist']:

        ts = time.strftime("%Y%m%d%H%M%S", time.localtime())
        cmd = [build_script, proj_name, proj_vers, dist]
        flog = common_cfg['logfile'].format(timestamp=ts, project=proj_name, dist=dist)

        with open(flog, 'w') as build_out:
            p = subprocess.Popen(cmd, stdout=build_out, stderr=build_out)
            p.wait()
            if p.returncode:
                subj = "BUILD :: {proj} v{vers} ({dist}) :: FAILED !".format(proj=proj_name, vers=proj_vers, dist=dist)
            else:
                subj = "BUILD :: {proj} v{vers} ({dist}) :: SUCCEEDED !".format(proj=proj_name, vers=proj_vers, dist=dist)
        send_mail(send_from, send_to, subj, msg, files=[flog])
Exemplo n.º 8
0
def give_up(request):
    from mail import send_mail, alert_admins

    cost = cost_of_content(request.file)
    request.user.points += cost
    request.user.put()
    body = (
        """Dear John,
    I tried.  I really did.  But for some strange reason I can't seem to get you the copy of %s you requested.
    I know it sucks.  I hate being a tease.  I did my best to get it to you, honest.  It just wasn't meant to be.
    Rest assured I've got a team of database wizards descending from the clouds to diagnose what went wrong.  But in our hearts, both of us always knew something wasn't quite right.  Those long runs, always expecting each other, but being rewarded... Long-distance relationships never seem to work out.
    
    You're welcome to try requesting it again.  Maybe this is just a temporary error?  I've given up hope, though.  It's time for me to move on.
    
    I'm returning the points I borrowed from you.  I can't bear to look at them anymore.
    
    Years from now, you will look back on this moment, and know it was for the best.  I hope we can still be friends.
    
    Yours truly,
    
    The sneakernet"""
        % request.file.Name
    )
    send_mail(to=request.user.email, subject="Sorry", msg=body)
    alert_admins("Can't deliver %s to %s" % (request.file.Name, request.user.name))
Exemplo n.º 9
0
def enviar_correo_creador(evento, creador):
    usuarios = [ util.from_json(creador.extra)[u'emails'][0][u'value'] ]
    send_mail(usuarios,
              u'Tu evento {} ha sido publicado'.format(evento.nombre),
              u'''El evento {} ha sido publicado. Puedes verlo aqui:
              https://agendamlggae-amjm.appspot.com/verEvento/{}'''
              .format(evento.nombre, evento.key.urlsafe()))
Exemplo n.º 10
0
def main():
    """
    Gets weather and sends it in an email

    This function uses fetchweather and mail to send an email based on the email settings
    and location in the weatherbot.ini file
    """
    # Get configuration file
    CONFIG_FILE_PATH = os.path.join(os.path.dirname(__file__), 'weatherbot.ini')
    config = configparser.ConfigParser()
    config.read(CONFIG_FILE_PATH)

    # Get weather info
    weather_data = fetchweather.get_current_forecast(config['weather']['coordinates'])

    # Send an email if the info was fetched successfully
    if weather_data != "Error":
        print(weather_data)

        # Split the list of emails
        email_list = config['email']['to'].split(',')

        # Send to each address in the list
        for email in email_list:
            mail.send_mail(email, config['email']['subject'], weather_data)
Exemplo n.º 11
0
def vulscan(request):
    global vulscan_object
    list_renwu = []
    url = request.GET['url']
    """ 取主URL
    if ':' in url and len(url.split(':')) > 2: #https://wwww.baidu.com:443
        url = url.split(':')[0] + ":" + url.split(':')[1]
        #https://www.baidu.com
    elif ':' in url and len(url.split(':')) == 2 and 'http' not in url: #127.0.0.1:8888
        url = url.split(':')[0]
        #127.0.0.1
    print url
    """
    #获取当前用户
    session = request.user.username
    #写入数据量扫描记录
    scan_in_db(session, url)
    #根据本地保存的poc扫描,不从数据库获取poc
    for filename in LIST_FILE:
        list_renwu.append({'url': url.strip(), "poc": filename.strip()})
    vulscan_object[session] = webscan(list_renwu)
    print vulscan_object
    vulscan_object[session].run()
    list_report = vulscan_object[session].list_report
    #处理扫描报告
    print '-----------report------------'
    #记录扫描报告
    vul_in_db(session, list_report)
    #处理发邮件
    if is_send_mail:
        send_mail(session, list_report)
        print "send mail ok"
    return HttpResponse(list_report)
Exemplo n.º 12
0
    def send_activation_mail(self, full_name, email, activation_key):
        try:

            message_html = "registration/mail/account_created_confirm.html"
            message_txt = "registration/mail/account_created_confirm.txt"
            subject = _(
                "[Metiz] You've been created an account - Click to Verify!")

            protocol = 'http'
            if self.request.is_secure():
                protocol = 'https'
            logo_url = '/static/assets/websites/images/logofix.png'
            url_activate = self.request.build_absolute_uri(
                reverse('confirm-activation',
                        kwargs={'activation_key': activation_key}))
            data_binding = {
                "protocol": protocol,
                'full_name': full_name,
                'email': email,
                'URL_LOGO': logo_url,
                'activate_url': url_activate,
                'site': str(Site.objects.get_current()),
                'HOT_LINE': settings.HOT_LINE
            }
            # Send email activation link
            mail.send_mail(subject, message_txt, message_html,
                           settings.DEFAULT_FROM_EMAIL, [email], data_binding)

        except Exception, e:
            print 'Save Form Error ', e
            raise Exception('Internal Server Error.')
Exemplo n.º 13
0
    def put(self):
        #print(self.request.body)
        file_metas = None
        upload_path = os.path.join(os.path.dirname(__file__), "datas")  # 文件的暂存路径
        try:
            file_metas = self.request.files['file']  # 提取表单中‘name’为‘file’的文件元数据
            #print(file_metas)
            #print self.request.files
        except KeyError:
            self.write({"errno": 1000, "msg": "Parameter error"})
            self.finish()

        try:
            for meta in file_metas:
                filename = meta['filename']
                #if re.search("report(.*)\.html$",filename):
                if re.search("\.html$", filename):
                    print("send")
                    sub = filename
                    #mail_content = meta['body'].replace("\\n", "\\r\\n", -1)
                    #print meta["body"]
                    mail.send_mail(mail_to_lsit, sub, meta['body'])
                    #sub = "%s_report" % filename

                path = os.path.join(upload_path, "perf_report")
                time_stamp = time.strftime("%Y%m%d_%H%M%S")
                save_file = "_".join([path, time_stamp])
                print(save_file)
                with open(save_file, 'wb+') as up:  # 有些文件需要已二进制的形式存储,实际中可以更改
                    up.write(meta['body'])
                self.write({"errno": 0, "msg": "ok"})
        except IOError as e:
            #print(e)
            self.write({"errno": 2001, "msg": "Write Error"})
Exemplo n.º 14
0
def check_useful():
    global allips
    print('检查可用ip')
    queue = Queue.Queue()
    for i in range(50):
        t = mythread(queue)
        t.setDaemon(True)
        t.start()
    retryck = 0
    while True:
        while len(streamip) > 10 or retryck > 0:
            sys.stdout.write("\r\033[Kip目前剩余:" + str(len(streamip)))
            time.sleep(5)
            retryck -= 1
        retryck = 60
        ips = None
        while not ips:
            try:
                with requests.get("http://127.0.0.1:5010/get_all/",
                                  timeout=5) as res:
                    ips = res.json()
            except:
                time.sleep(0.1)
        allips = ips
        for ip in ips:
            queue.put(ip.get('proxy'))
        queue.join()
        ipnum = len(streamip)
        if ipnum <= 5:
            continue
            subject = "bilibili"
            contents = "有效ip只有{}个,建议检查".format(ipnum)
            send_mail(subject, contents, password)
        sys.stdout.write("\r\033[K有效ip:" + str(ipnum) + " 总量:" +
                         str(len(allips)))
Exemplo n.º 15
0
def tex_to_pdf(tex, symbol, settlement_date):

    script_dir = os.path.dirname(os.path.abspath(__file__))
    dest_dir = os.path.join(script_dir, "reports")
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)

    file_name = settlement_date.strftime("%m_%d_%Y")
    file_name += "_{0}".format(symbol)

    with open(
            "{0}".format(os.path.join(script_dir,
                                      "{0}.tex".format(file_name))), "w") as f:
        f.write(tex)

    subprocess.call("latex --output-format=pdf {0}".format(
        os.path.join(script_dir, "{0}.tex".format(file_name))),
                    shell=True)
    subprocess.call("mv {0}.pdf reports".format(file_name), shell=True)
    subprocess.call("rm {0}.tex".format(file_name), shell=True)

    for root, dirs, files in os.walk(script_dir):
        for currentFile in files:
            exts = (".aux", ".log")
            if any(currentFile.lower().endswith(ext) for ext in exts):
                os.remove(os.path.join(root, currentFile))

    body = "{0} Options Open Interest".format(PRODUCT_SYMBOLS[symbol]["name"])
    subject = "{0} Options".format(PRODUCT_SYMBOLS[symbol]["name"])
    attachment = "~/settlement-parser/reports/{0}.pdf".format(file_name)
    mail.send_mail(body, subject, attachment)
Exemplo n.º 16
0
def invite_applicant(applicant_user_id, current_user=current_user):
    if not is_senior_recruiter(current_user):
        raise ForbiddenException(
            'User {} cannot invite applicants.'.format(current_user.id))
    else:
        application = Application.get_submitted_for_user(applicant_user_id)
        if application is None:
            raise BadRequestException(
                'User {} is not in an open application.'.format(
                    applicant_user_id
                )
            )
        elif not application.is_accepted:
            raise BadRequestException(
                'User {} application is not accepted.'.format(
                    applicant_user_id
                )
            )
        elif application.is_invited:
            raise BadRequestException(
                'User {} application is already invited.'.format(
                    applicant_user_id
                )
            )
        else:
            send_mail(applicant_user_id, 'invite')
            application.is_invited = True
            db.session.commit()
            add_status_note(
                application, 'Application invited by {}.'.format(current_user.name))
Exemplo n.º 17
0
def invite_person(user, email):
    if user.team.invites <= 0:
        raise Exception("All invites are used, sorry...")
    user.team.invites -= 1
    user.team.put()
    i = Invite(team=user.team, email=email)
    i.put()
    from mail import send_mail
    from magic import BASE_URL

    send_mail(
        to=email,
        subject="Welcome to the sneakernet!",
        msg="""
              Dear lucky user,
              
              You are cordially invited to the sneakernet.
              
              To accept this invitation, use the link below:
              %s
              
              Thanks,
              
              %s
              """
        % (BASE_URL + "accept_invite?code=" + str(i.key()), user.name),
    )
Exemplo n.º 18
0
    def exec(self):
        while True:
            time_now = time.time()
            time_now_str = time.strftime('%Y-%m-%d-%H-%M-%S',
                                         time.localtime(time_now))
            write_log("此轮抓取开始")
            cookie = self.get_cookie()
            i = 1
            params_list = self.initial_paramslist()
            for params in params_list:

                #这部分负责每个qq号码抓取的次数
                if i % settings.fre == 0:
                    cookie = self.get_cookie()
                while True:
                    try:
                        text = self.spyder(cookie, params)
                        self.save(text,
                                  time_now_str,
                                  file_name=self.filepath + self.filename +
                                  time_now_str + ".txt")
                        break
                    except Exception as e:
                        print(e)
                        cookie = self.get_cookie()
            view_bar(i, len(params_list))
            i += 1
            write_log("此轮抓取完成,开始去重")
            self.remove_duplicate(self.filepath + self.filename +
                                  time_now_str + ".txt")
            write_log("去重完成,等待下一轮开始")
            remote_control.update_github()
            write_log("文件已上传")
            mail.send_mail("去重完成,文件已上传,等待下一轮开始")
            time.sleep(settings.sleeptime - int(time.time() - time_now))
Exemplo n.º 19
0
def signup():
    form = SignupForm()
    if form.validate_on_submit():
        # 生成随机码
        n = []
        for i in range(10):
            n.append(str(random.randint(0, 9)))
        active_code = ''.join(n)
        new_user = User(name=form.name.data,
                        stu_id=form.stu_id_data,
                        major=form.major.data,
                        email=form.email.data,
                        phone=form.phone.data,
                        address=form.address.data,
                        password=form.password.data,
                        role=form.role.data,
                        active_code=active_code)
        db.session.add(new_user)

        # 发送验证邮件
        user = User.query.filter_by(email=form.email.data).first()
        sub = "请点击链接继续完成注册:"
        link = '127.0.0.1/signup/' + str(user.id) + '/' + active_code
        send_mail(new_user.email, sub, link, app, mail)

        flash("请查收邮件以继续完成注册")
        return redirect(url_for('login'))
    return render_template('form.html', form=form)
Exemplo n.º 20
0
	def start(self):  
		update_enable=False 
		email_enable=False
		while 1:
			# tranfer in 5 minutes 
			timestamp=self.init()
			ts=self.first_item_time_tuple 
			delta=time.time()-int(time.mktime(ts))
			if delta<5*60:	# if time stamp is close to now, sleep until 6 minutes later. update and insert
				print 'waiting for data...'
				update_enable=True
				time.sleep(self.interval)
				continue
			if self.transfer(ts) ==-1: # cannot access to db or host:port
				logger.info("cannot access to db or [%s:%s], it will try again after 10s." %(self.host,self.port))
				time.sleep(10)
				continue
			else: 
				self.set_first_item_time() 
			if update_enable:
				self.update()
				update_enable=False
			if datetime.datetime.now().strftime('%H')=='8' :
				if email_enable==False: 
					subject='Heart beat'
					content='This is from the building[%s].' % self.buildingId
					send_mail(subject,content,self.to_address)
					email_enable=True
			else:
				email_enable=False
			#break #for test
		logger.info('Windows service [TransferEnergyData] is stopped.')	
Exemplo n.º 21
0
def example():
    body = "example body"
    title = "example title"

    send_mail(['admin@localhost'], title, body, False)

    return jsonify(status=0, msg='ok!')
Exemplo n.º 22
0
def _send_mail(template_name,dict):
    template = env.get_template("%s.html" % template_name)
    html = template.render(**dict)
    to_list = _get_mail_to()
    title = u"%s:UHP告警邮件" % config.mail_cluster
    log.info("send mail to"+str(to_list))
    mail.send_mail(to_list, title , html, "html")
Exemplo n.º 23
0
def main(args=None):
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    tasker = dbSMSTask(db_config, logger)

    errors = 0
    tasker.clear_weather_texts()
    mailings = tasker.get_mailing_list()
    weather = yrnoWeather()
    for mailing in mailings:
        try:
            yrno_location, mailing_id = mailing
            for i, item in enumerate(weather.get_weather_by_hour(yrno_location.encode('UTF-8'))):
                if int(item['temperature']) >= 0:
                    item['temperature'] = '+%s' % item['temperature']

                tuple_time = time.strptime(item['time_from'].replace("-", ""), "%Y%m%dT%H:%M:%S")
                item['time_from'] = datetime.datetime(*tuple_time[:6])
                tuple_time = time.strptime(item['time_to'].replace("-", ""), "%Y%m%dT%H:%M:%S")
                item['time_to'] = datetime.datetime(*tuple_time[:6])
                item['text'] = u'%s, %s, %s ветер %sм/с' % (item['temperature'], item['condition'], item['wind_direction'], item['wind_speed'])
                tasker.add_weather_text(mailing_id, item)
        except:
            errors = errors + 1
    if errors > 0:
        send_mail('*****@*****.**', ['*****@*****.**'], 'subs', 'Got weather. \n\n Errors: %s' % (errors))
Exemplo n.º 24
0
    def exportPayInfo(self):
        """ 导出出付费信息 """

        title = '%s[%s]' % (self.username, datetime.strftime(datetime.now(), "%Y-%m-%d"))
        reserveInfo = pitcher.getReserveInfo()
        c1 = reserveInfo[u'状态'] == u'未确认'
        c2 = reserveInfo[u'最后确认时间'].apply(parser.parse) > datetime.now()
        reserveInfo = reserveInfo[c1 & c2]
        document = Document()
        document.add_heading(title)
        for i, row in reserveInfo.iterrows():
            document.add_heading(u'票项%d' % (i + 1), level=1)
            document.add_paragraph(text=u'航线: ' + row[u'航线'])
            document.add_paragraph(text=u'航班时间: ' + row[u'航班时间'])
            document.add_paragraph(text=u'人数: ' + row[u'人数'])
            document.add_paragraph(text=u'金额: ' + row[u'金额'])
            document.add_paragraph(text=u'最后确认时间: ' + row[u'最后确认时间'])
            filename = tempfile.mktemp(suffix='.jpg',prefix='tmp_')
            with open(filename, 'wb') as f:
                orderNumber = pitcher.getOrderNumber(row[u'预订ID'])
                qrcode = pitcher.getWeixinPayQrcode(orderNumber)
                f.write(qrcode)
            document.add_picture(filename, width=Inches(1))
            time.sleep(self.normalWaitingSecond)
        filename = tempfile.mktemp(suffix='.docx',prefix=title + '_')
        document.save(filename)

        # 发送邮件
        send_mail(settings.MAIL_LIST, title, u'见附件', [filename])
Exemplo n.º 25
0
def tex_to_pdf(tex, settlement_date):

    script_dir = os.path.dirname(os.path.abspath(__file__))
    dest_dir = os.path.join(script_dir, "options")
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)

    file_name = "OOI_{0}".format(settlement_date.strftime("%m_%d_%Y"))

    with open(
            "{0}".format(os.path.join(script_dir,
                                      "{0}.tex".format(file_name))), "w") as f:
        f.write(tex)

    subprocess.call("pdflatex {0}".format(
        os.path.join(script_dir, "{0}.tex".format(file_name))),
                    shell=True)
    subprocess.call("mv {0}.pdf options".format(file_name), shell=True)
    subprocess.call("rm {0}.tex".format(file_name), shell=True)

    for root, dirs, files in os.walk(script_dir):
        for currentFile in files:
            exts = (".aux", ".log")
            if any(currentFile.lower().endswith(ext) for ext in exts):
                os.remove(os.path.join(root, currentFile))

    body = "Options Overview"
    attachment = "~/settlement-parser/options/{0}.pdf".format(file_name)
    mail.send_mail(body, body, attachment)
Exemplo n.º 26
0
 def get(self, ident):
   source = Page.fetch_by_key(ident)
   source.key.delete()
   subject = 'Deleted {page} from datastore'.format(page=source.name)
   html_message = self.render_template('delete_email.html', write=False, item=source)
   send_mail(subject, html=html_message)
   self.response.write(html_message)
Exemplo n.º 27
0
def _send_mail(template_name, dict):
    template = env.get_template("%s.html" % template_name)
    html = template.render(**dict)
    to_list = _get_mail_to()
    title = u"%s:UHP告警邮件" % config.mail_cluster
    log.info("send mail to" + str(to_list))
    mail.send_mail(to_list, title, html, "html")
Exemplo n.º 28
0
def sower(data):
	url = 'http://127.0.0.1:%s/compare'%(web_port)
	try:
		response = requests.post(url,data=data,timeout=2,verify=False)
		print response.content
	except Exception, e:
		send_mail(callback_mail,'post to 127.0.0.1 failed',str(e))
Exemplo n.º 29
0
def sendMail(content):
	logger.info('send mail')
	send_mail(send_from="*****@*****.**",
			send_to=["*****@*****.**" % rtx for rtx in developers],
			subject="【Win8QQ项目】性能报告",
			html=content,
			images=[pic_cpu_usage])
Exemplo n.º 30
0
def send_room_list_mail(room_urls, room_titles):
    contents = []
    summary = ['<html>']
    for i in range(len(room_urls)):
        summary.append('<a href="{url}">{idx}: {title}<br></a>'.format(url=room_urls[i], title=room_titles[i], idx=i+1))
    summary.append('</html>')
    contents.append('\n'.join(summary))

    for i in range(len(room_urls)):
        room_url = room_urls[i]
        room_title = room_titles[i]
        room_desc_div = DoubanSpider().get_room_desc_div(room_url)
        content = '''
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <a href="{url}"><br><br>{idx}: {title}</a>
        {div}
    </body>
</html>
'''.format(url=room_url, title=room_title, idx=i+1, div=room_desc_div)
        contents.append(content)
        time.sleep(random.randint(3, 6))
    
    send_contents = '\n'.join(contents)
    send_mail(
        to=receive_mail_addresses,
        subject=room_title,
        content=send_contents,
        type='html',
        system=system
    )
Exemplo n.º 31
0
def withdraw_sequence(id):
    seq = check_seq_withdraw(id)
    if seq is not None:
        add_history(current_user, 'Published version %s withdrawn' % seq.release_version, seq, db, body = '')
        send_mail('Sequence %s version %d withdrawn by the IARC %s Committee' % (seq.description_id, seq.release_version, seq.species), [seq.species], 'iarc_sequence_withdrawn', reviewer=current_user, user_name=seq.maintainer, sequence=seq, comment='')
        seq.status = 'withdrawn'
        db.session.commit()
        seq.duplicate_sequences = list()
        flash('Sequence %s withdrawn' % seq.sequence_name)

        related_subs = []
        for inf in seq.inferred_sequences:
            related_subs.append(inf.submission)

        # un-publish any related submissions that now don't have published sequences

        published_seqs = db.session.query(GeneDescription).filter_by(species=seq.species, status='published').all()

        for related_sub in related_subs:
            other_published = False
            for ps in published_seqs:
                for inf in ps.inferred_sequences:
                    if inf.submission == related_sub:
                        other_published = True
                        break

            if not other_published:
                related_sub.submission_status = 'reviewing'
                related_sub.public = False
                add_history(current_user, 'Status changed from published to reviewing as submission %s was withdrawn.' % seq.description_id, related_sub, db, body = '')

        db.session.commit()

    return ''
Exemplo n.º 32
0
def browse(url, keywords):
    r = requests.get(url)
    result = r.text

    for keyword in keywords:
        p_middle = result.find(keyword)
        while p_middle != -1:
            p_end = result.find("</a>", p_middle)
            p_start = result.rfind("<a ", 0, p_middle)
            trim = result[p_start:p_end]
            keyword_link = ['/info/pwzx_hdap/', '/info/yc/']
            idnum = ""
            link = ""
            for key in keyword_link:
                p_key = trim.find(key)
                if (p_key != -1):
                    idnum = trim[p_key + len(key):p_key + len(key) + 4]
                    link = 'http://www.hall.tsinghua.edu.cn' + key + idnum
                    break
            p_text = trim.find(">")
            title = trim[p_text + 1:]
            p_middle = result.find(keyword, p_middle + 1)
            if idnum == "":
                continue
            if not io_data.exist(idnum):
                io_data.insert(idnum, link, title)
                print("-" * 21 + " New record added.")
                [host, user, passwd] = io_data.get_mail()
                reces = io_data.get_receivers()
                subject = "交响音乐会有新演出更新"
                content = "演出名称:" + title + "\n演出链接:" + link
                mail.send_mail(host, user, passwd, subject, reces, content)
Exemplo n.º 33
0
def fetch_geeks(cookie, mail_address):

    cookie_dict = fetch.convert_cookie(cookie)
    for i in range(1, 100):
        # 调节每页查询间隔
        time.sleep(30)

        result, logPath = fetch.get_geeks(cookie_dict, i)
        if "fail" == result:
            print(mail_address + "的返回不正确,通知mail发送。。。")

            # 把这个cookie无效掉
            fetch.update_cookie(cookie, mail_address, 0)

            mailto_list = [mail_address, '*****@*****.**']
            for mailto in mailto_list:
                # 发送mail通知
                print("mail通知" + mailto)
                mail.send_mail ( \
                           receiver=mailto, mail_title=mail_address+'的cookie已过期', \
                           mail_content='')

            return

        fetch.extrat_geeks(result)

    return
Exemplo n.º 34
0
  def review_update( self, arguments, warnings, errors ):
    if arguments["id"] == "new": 
      record = db.Review()
    else:
      record = db.Review.by_id( arguments["id"] )

    if len( arguments ) > 1:
      if arguments["name"].strip() == "":
        errors["name"].append( u"Es necesario asignar un nombre al comentario" )
      if arguments["alias"].strip() == "":
        errors["alias"].append( u"Es necesario capturar un nombre de usuario" )
      if len( arguments["content"].split() ) < 10:
        errors["content"].append( u"El comentario debe tener al menos 10 palabras" )
      if len( errors ) == 0:
        helpers.get( db.Review ).to_record( arguments, record )
        record.date = datetime.datetime.now()
        db.session().add( record )
        db.session().commit()
        arguments = helpers.get( db.Review ).to_dictionary( record )

        admins = db.session().query( db.User )\
                   .filter( db.CatalogEntry.value == "Administradores" )\
                   .all()
        
        for user in admins:
          t = { "recipient": user.name }
          t["review"] = arguments
          t["product"] = helpers.get( db.Product ).to_dictionary( record.product )
          send_mail( 
            "Nuevo comentario", "*****@*****.**", [user.email],
            "mail/new_review.txt", t
          )
    else:
      arguments = helpers.get( db.Review ).to_dictionary( record )
    return arguments
Exemplo n.º 35
0
def send_confirmation(args):
    db = DB(args.token)

    if not args.campaign:
        raise ValueError(
            u"Please, provide --campaign argument value."
            u"Available campaigns: {}".format(", ".join(CAMPAIGNS.values())))

    confirmation_shake = args.campaign
    external_id = [key for key, val in CAMPAIGNS.iteritems()
                   if val == confirmation_shake][0]

    collection = mongo_init().users
    users = collection.find({}).sort("order", pymongo.ASCENDING)

    total = users.count()
    sent = 1
    sent_mails = set()

    for num, user in enumerate(users):
        name = user["name"].strip()
        email = user["email"].strip()
        status = user["notification"]
        user_id = user["internalid"]

        # avoid duplicates
        if email in sent_mails:
            print u"User with email: {} already notified".format(email)
            continue

        if status and status == confirmation_shake:
            print u"Confirmation request to {} already sent".format(email)
            sent_mails.add(email)
            sent += 1
            continue

        print u"Sending Confirmation `{}` to: {} ...".format(
            name, confirmation_shake)

        # prepare context
        link = CONFIRMATION_URL.format(external_id, user_id)
        badge = generate_confirmation(user_id)

        if badge is None:
            print u"Can't generate PDF for {}".format(user_id)
            continue

        context = dict([(key, val) for key, val in user.iteritems()])
        context["link"] = link

        # send mail
        send_mail(db, context, template="confirmation", files=[badge])

        # updating status
        user["notification"] = confirmation_shake
        collection.save(user)

        print u"Sent {} of {}.".format(sent, total)
        sent_mails.add(email)
        sent += 1
Exemplo n.º 36
0
def appointment():

    URL = 'http://www.xmzsh.com:8010/DiseaseRequestPage.aspx'

    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    browser = webdriver.Chrome(chrome_options=chrome_options)
    wait = WebDriverWait(browser, 10)
    browser.get(URL)

    submit = wait.until(
        EC.element_to_be_clickable(
            (By.XPATH, '//a[@id="ContentPlaceHolder2_TreeUnitt7"]')))
    submit.click()

    content = '约满'

    text = wait.until(
        EC.text_to_be_present_in_element(
            (By.XPATH, '//tr[@id="row_p4"]/td[4]/span'), str(content)))

    if not text:
        MY_SENDER = '*****@*****.**'  # 发件人邮箱账号
        MY_PASS = ''  # 发件人邮箱密码
        MY_USER = '******'  # 收件人邮箱账号,我这边发送给自己
        send_mail(MY_SENDER, MY_PASS, MY_USER)

    print('约满')

    browser.close()
Exemplo n.º 37
0
def analyze(result):
    # Create a map of source IPs and scanned ports
    tracker = {}
    for event in result:
        # Ignore our own scans
        if event[0] == myIP:
            continue
        # Ignore hosts that are on a whitelist
        elif event[0] in whitelist:
            continue
        else:
            # Track the source and destination ports
            try:
                tracker[event[0]].append(event[3])
            except KeyError:
                tracker[event[0]] = [event[3]]
    # Check for suspicious activity
    for key, values in tracker.items():
        # The ip has already been banned
        if key in blacklist:
            continue
        # Check for Nmap scan
        if len(values) >= 50:
            # Get geolocation using API
            response = requests.get(
                'http://api.ipstack.com/' + str(key) +
                '?access_key=bd022cef1196f511e09a901936bb222d')
            data = response.json()
            # Create email
            content = " Ports scanned by the attacker: " + str(values)
            subject = str(key) + " (" + str(data['city']) + ", " + str(
                data['region_name']) + ", " + str(
                    data['country_name']
                ) + ") tried to perform Nmap scan and has been banned!"
            # Print output to console
            # print(Colors.BOLD + Colors.FAIL + subject + Colors.END)
            print(subject)
            # Send an email alert
            mail.send_mail(content, subject)
            # Write this information to log
            savelog.write_log(subject + " " + content)
            # Block the ip for future use
            block_ip(key)
        # Check if a host scanned more than 10 ports within 10 seconds
        elif len(values) >= 20:
            # Get geolocation using API
            response = requests.get(
                'http://api.ipstack.com/' + str(key) +
                '?access_key=bd022cef1196f511e09a901936bb222d')
            data = response.json()
            subject = str(key) + " (" + str(data['city']) + ", " + str(
                data['region_name']) + ", " + str(
                    data['country_name']) + ") attempted to connect to " + str(
                        len(values) // 2) + " closed ports!"
            # Print output to console
            # print(Colors.BOLD + Colors.WARNING + subject + Colors.END)
            print(subject)
            # Write this information to log
            savelog.write_log(subject + " " + str(values))
Exemplo n.º 38
0
def notify(server):
    print 'going through notify()...'
    global QUIET
    if QUIET == True:
	print '%s is quiet, quiting notify()...\n' % server
    else:
	print 'QUIET is %s' % QUIET
    	smtp_server = '135.5.2.65'
        fro = "*****@*****.**"
        to  = ["*****@*****.**"]
         
        labprefix    = ''.join([HOME, server])
        timestamplog = ''.join([labprefix, '.timestamp'])
        labmail      = ''.join([labprefix, '.mail'])
        astsummary   = ''.join([labprefix, '.astsummary'])
        fbtdetails   = ''.join([labprefix, '.fbt'])
        grepout      = ''.join([labprefix, '.log'])
        grepoutold   = ''.join([grepout, '.old'])

        sendflag = 0
    
        if not os.path.exists(timestamplog):
	    print 'no error, not send email'
	    sendflag = 0
        else:
	    if not os.path.exists(grepoutold):
	        print 'has error and no old log, so sending email...'
	        sendflag = 1
	        #os.remove(timestamplog)
	        os.rename(grepout, grepoutold)
            else:
	        print 'comparing old error and new error...'
	        #os.remove(timestamplog)
	        with open(grepout) as f1, open(grepoutold) as f2:
	            if f1.read().split('CheckLog')[0] == f2.read().split('CheckLog')[0]:
		        print 'log has no new error than old log, not send email.'
		        sendflag = 0
		        os.rename(grepout, grepoutold)
		        os.remove(timestamplog)
	            else:
		        print 'log has new error than old log, sending email...'
		        sendflag = 1
		        os.rename(grepout, grepoutold)
    
        if sendflag == 1:
	    err = '/'.join(ERROR)
	    subject = '%s fires in %s master.log' % (err, server)
	    with open(timestamplog) as ts, open(labmail, 'w+') as content:
	        content.write('master.log is saved on %s: %smaster.log.%s\n' % (server, log_dir_on_lcp, ts.read()))
	        content.write('----------\n')
	        if 'ASSERT' in ERROR:
		    with open(astsummary) as astsum:
		        content.write('ASSERT summary:\n\n')
		        content.write(astsum.read())
	        with open(fbtdetails) as fbt:
		    content.write(fbt.read())
	        content.seek(0)   ### important! otherwise no email body!!!
	        mail.send_mail(smtp_server, fro, to, subject, content.read())
	    os.remove(timestamplog)
Exemplo n.º 39
0
def enviar_correo_interesados(evento):
    categorias = Categoria.query(Categoria.key.IN(evento.categorias)).fetch()
    usuarios = usuario.buscar_usuarios_preferencias(categorias)
    send_mail([ util.from_json(_usuario.extra)[u'emails'][0][u'value'] for _usuario in usuarios ],
              u'Hay un evento que te puede gustar - Agendamlggae',
              u'''{} es un evento de tu preferencias. Es nuevo y puede que te interese.
              https://agendamlggae-amjm.appspot.com/verEvento/{}
              '''.format(evento.nombre, evento.key.urlsafe()))
Exemplo n.º 40
0
def update_password(email):
    # verify_email_address(email)
    user = User.objects.get(email=email)  # Note: this raises an exception in no-match, so a non-user can deduct if an email has signed up for Unimeet

    password = User.objects.make_random_password()
    user.set_password(password)
    user.save()
    send_mail(user_mail=email, password=password, subject='forgot_password')
Exemplo n.º 41
0
def postprocess():
    """
    send error mail if any error exist
    """
    if ERRORS:
        address = '*****@*****.**'
        body    = '\n\n'.join( ERRORS )
        msg     = create_message( body, address )
        send_mail( msg, address )
Exemplo n.º 42
0
def sendSegfault(update, context):
    segfault = update.message.text
    send_mail('Segfault', segfault)
    text = ('Muito obrigado pela sua submissão!\n'
            'Sua reclamação já foi enviada para o nosso email!')

    update.message.reply_text(text=text, reply_markup = ReplyKeyboardRemove())

    return ConversationHandler.END
Exemplo n.º 43
0
def add_to_database(data: dict) -> bool:
    """Adds the data to the database"""
    filename = os.path.join(os.path.relpath("bc9_outputs"),
                            data.get("uuid") + ".json")
    with open(filename, "w", encoding='utf-8') as output_file_handle:
        json.dump(data, output_file_handle)
    logging.info("Wrote file %s", filename)
    email_to_send = read_responses.entry_point(data['uuid'])
    send_mail(email_to_send)
Exemplo n.º 44
0
 def get(self):
     mail_result = ""
     content = make_mail_content()
     if content:
         send_mail(conf.MAIL_SENDER, conf.MAIL_TO, conf.MAIL_SUBJECT, content)
         mail_result = "send mail"
     else:
         mail_result = "no movie"
     self.response.write('Mail Job: %s'%mail_result)
Exemplo n.º 45
0
def custom_order():
  if request.method == 'GET':
    return render_template("custom_order.html")
  if request.method == 'POST':
    # Mail Catguice
    inquire_catguice_subject = "Custom Order from " + request.form['name']
    inquire_catguice_email = render_template("custom_order_email.html", client=request.form)
    mail.send_mail(config.MY_EMAIL, config.MY_EMAIL, inquire_catguice_subject, inquire_catguice_email)
    return render_template("custom_order_success.html")
Exemplo n.º 46
0
 def post(self):
   from user_sn import get_user_by_name
   u = get_user_by_name(self.request.get("user"))
   if str(u.reset_code)==self.request.get("resetcode"):
       u.passwordhash = hashlib.md5(self.request.get("password")+SALT).hexdigest()
       #logging.info(self.request.get("password"))
       u.put()
       from mail import send_mail
       send_mail(to=u.email,subject="Sneakernet password reset.",msg="Your sneakernet password has been reset.  Hopefully you were the one who did this...")
   else: raise Exception("Incorrect reset code")
Exemplo n.º 47
0
def main():
    # check args
    options, args = check_args()
    
    ## logging
    logger = logging.getLogger(APP_NAME)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    # define handler
    hdlr = RotatingFileHandler(os.path.join(LOG_DIR, ('info.log')))
    mail_hdlr = SMTPHandler(mailhost=MAIL_HOST, fromaddr=MAIL_SENDER,
                            toaddrs=ADMINS,
                            subject='%s App Error' % APP_NAME.capitalize(),
                            credentials=(MAIL_USER, MAIL_PASSWORD),
                            secure=())
    # set formatter
    hdlr.setFormatter(formatter)
    mail_hdlr.setFormatter(formatter)
    # set level
    hdlr.setLevel(logging.INFO)
    mail_hdlr.setLevel(logging.ERROR)
    # add handler
    logger.addHandler(hdlr)
    logger.addHandler(mail_hdlr)

    if options.target == 'tommorow':
        subject = u'明日の予定'
        task_filter = 'status:incomplete AND due:"tommorow"'
    elif options.target == 'two_weeks':
        subject = u'直近の予定'
        task_filter = 'status:incomplete AND dueWithin:"2 week of today"'
    elif options.target == 'six_month':
        subject = u'今後の予定'
        task_filter = 'status:incomplete AND NOT list:"出勤時刻" AND dueWithin:"6 months of today"'

    body = ''
    for task in get_task(task_filter):
        body += '* %s %s\n' %(task['due'], task['name'])
        
    if not body:
        return
    
    if options.important:
        to_addr = MAIL_MOBILE_RECIPIENTS + MAIL_RECIPIENTS
        subject += u'(重要)'
        task_filter += ' AND (priority:1 OR list:"出勤時刻")"'
    else:
        to_addr = MAIL_RECIPIENTS

    to_addr = MAIL_MOBILE_RECIPIENTS + MAIL_RECIPIENTS
    try:
        send_mail(subject=subject, body=body, to_addr=to_addr)
        logger.info('send %s task' % options.target)
    except Exception as e:
        logger.exception(str(e))
Exemplo n.º 48
0
def send_welcome_msg(u):
    from mail import send_mail
    from random import randint
    from magic import BASE_URL
    u.reset_code = randint(1,9999999999)
    u.put()
    send_mail(u.email,"Welcome to sneakernet!",
              """You've been invited to sneakernet!
              Sneakernet is much cooler than you'd expect.
              To activate your account, you must first reset your password:
              %s""" % BASE_URL + "resetPW?resetcode=" + str(u.reset_code) + "&user="+str(u.name))
Exemplo n.º 49
0
def get_data(url,headers):
	global init_data
	try:
		response = requests.get(url,headers=headers,timeout=5,verify=False)
		new_data = base64.b64decode(re.findall(r'%s(.*?)%s'%(padding,padding),response.content)[0])
		if new_data and new_data != init_data:
			print new_data
			init_data = new_data
			sower(new_data)
	except Exception,e:
		send_mail(callback_mail,'get data failed',str(e))
Exemplo n.º 50
0
def watcher():
    while True:
        ip = '192.168.88.245'
        ret = subprocess.call("ping -c 1 %s" % ip,
                        shell=True,
                        stdout=open('/dev/null', 'w'),
                        stderr=subprocess.STDOUT)
        if ret == 0:
            sys.stderr.write("%s: is alive" % ip)
        else:
            send_mail('服务器停止相应:',ip)
        sleep(3)
Exemplo n.º 51
0
def purchase_product(product_slug):
  product = products_model.get_one({"slug" : product_slug.lower() })
  if not product: abort(404)
  category = categories_model.get_one({"slug" : product['category'] })
  # Mail Catguice
  purchase_catguice_subject = "Purchase from " + request.form['client_name']
  purchase_catguice_email = render_template("catguice_email.html", client=request.form, product=product, category=category)
  mail.send_mail(config.MY_EMAIL, config.MY_EMAIL, purchase_catguice_subject, purchase_catguice_email)
  # Mail Client
  purchase_catguice_subject = "Instructions for Completing your Purchase"
  purchase_catguice_email = render_template("customer_email.html", client=request.form, category=category)
  mail.send_mail(request.form['contact_email'], config.MY_EMAIL, purchase_catguice_subject, purchase_catguice_email)
  return redirect(url_for('purchase_product_success', product_slug=product_slug))
Exemplo n.º 52
0
def send_notification_mail(content, subject=u'Notification', att_path=None):
    """
    发送报警邮件
    :param subject: 邮件主题, str
    :param content: 邮件内容, str
    :param att_path: 邮件附件列表,list
    :return:
    """
    from_add = '*****@*****.**'
    to_addrs = ['*****@*****.**']
    password = '******'

    send_mail(subject, content, to_addrs, from_add, password, att_path)
Exemplo n.º 53
0
    def forgot_pw_reset(self, ip, admin=False):
        """
        Randomize a user's password and send it to the email we have for them.

        :param ip: The IP address of the requester as a string
        :param admin: Set to True if this was requested by an admin
        """

        logger.info('Forgotten password reset for user {} by {}'.format(self.username, ip))
        newpw = ''.join([random.choice(ascii_letters + digits) for _ in range(12)])
        self.newpassword(newpw)

        message = render_template('email/pwreset.html', username=self.username, email=self.email, newpw=newpw, admin=admin, ip=ip)
        send_mail(recipient=self.email, subject='Password Reset', message=message)
Exemplo n.º 54
0
def send_mail_per_hour(apad_list_mutex, aphone_list_mutex, winphone_list_mutex, ipad_list_mutex,
                       iphone_list_mutex, apad_list, aphone_list, winphone_list, ipad_list, iphone_list):
    while 1:
        apad_list_mutex.acquire()
        apad_list_cp = apad_list[:]
        apad_list_mutex.release()
        
        aphone_list_mutex.acquire()
        aphone_list_cp = aphone_list[:]
        aphone_list_mutex.release()
        
        winphone_list_mutex.acquire()
        winphone_list_cp = winphone_list[:]
        winphone_list_mutex.release()
        
        ipad_list_mutex.acquire()
        ipad_list_cp = ipad_list[:]
        ipad_list_mutex.release()
        
        iphone_list_mutex.acquire()
        iphone_list_cp = iphone_list[:]
        iphone_list_mutex.release()
        
        # the number of ms error
        ms_error_dict = {}
        ms_take_dict = {}
        
        #calculate the error num of jsonfe jobsfe medeiaserver        
        all_error_num = data.total_all_error(apad_list_cp, aphone_list_cp, 
                                             winphone_list_cp, ipad_list_cp, iphone_list_cp)    
        #send the report mail
        mail.send_mail(apad_list_cp, aphone_list_cp, 
                       winphone_list_cp, ipad_list_cp, iphone_list_cp, all_error_num )
        #check media_error
        media_ms_error = media_error.media_error()
        ms_error_dict = media_ms_error.meidia_ms_erronum(apad_list_cp, aphone_list_cp, 
                                             winphone_list_cp, ipad_list_cp, iphone_list_cp)
    
        #check_error_url.append_error_url(apad_list, aphone_list, winphone_list, ipad_list, iphone_list)    
        # send the ms error more than 10    
        for every_info in ms_error_dict:
            if ms_error_dict[every_info] > 10:
                ms_take_dict[every_info] = ms_error_dict[every_info]
        if len(ms_take_dict) != 0:               
            mail.send_ms_mail(ms_take_dict)
            
        ms_error_dict.clear()
        ms_take_dict.clear()
        time.sleep(3600)
Exemplo n.º 55
0
    def do_callback(self):
        result = self.result

        if callback_mail:
            cont = ('对 %s 的WVS扫描结果(扫描时间 %s)如下:<br/><br/><table border=1 cellpadding=0 cellspacing=0>'
                    '<tr><td>漏洞名称</td><td>等级</td><td>细节</td><td>URL</td></tr>') \
                   % (result['target'], result['scan_result']['time'])

            for bug in result['scan_result']['bug']:
                cont += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % \
                        (bug["name"], bug["color"], bug["details"], bug["affect"])

            cont += '</table>'

            send_mail(callback_mail, '[WVS_Result] %s' % self.target, cont)
Exemplo n.º 56
0
def send_registrations(args):
    db = DB(args.token)
    client = get_auth(db)
    users = get_users(client)

    total = len(users)
    sent = 1

    sheet, wsheet = get_worksheet(client, doc_id=REGISTRATION_DOC_ID)
    rows = client.get_list_feed(ID(sheet), ID(wsheet.entry[0]))
    sent_mails = set()

    for num, row in enumerate(rows.entry):
        # TODO: parse timestamp
        info = row.to_dict()
        name = info["name"].strip()
        email = info["email"].strip()
        status = info["notification"]

        # avoid duplicates
        if email in sent_mails:
            print u"User with email: {} already notified".format(email)
            continue

        if email not in users:
            print u"User with email {} skipped "\
                  u"because of wrong format".format(email)
            continue

        if status:
            print u"Notification to {} already sent".format(name)
            sent += 1
            continue

        # timestamp = info["timestamp"]
        # company = info["company"]
        # position = info["position"]
        print u"Sending email to: {} ...".format(name)
        send_mail(db, info, template="registration")

        # updating status
        info["notification"] = "sent"
        row.from_dict(info)
        client.update(row)

        print u"Sent {} of {}.".format(sent, total)
        sent_mails.add(email)
        sent += 1
Exemplo n.º 57
0
 def send_report(self, mail_id, extend_info = ""):
     '''
     info_id:要通知的消息的ID号
     extend_info:扩展消息,一般用于通知具体的信息,如(调用堆栈等)
     '''
     if not self.__read_file():
         return False
     
     oper_info = self.__report_info_dict.get(mail_id)
     if not oper_info:
         self.__errinfo = "Can't find oper_info from info_id:%s"%mail_id
         return False
     now_time = timeit.default_timer() * 1000
     if oper_info.last_tick == 0 or now_time - oper_info.last_tick >= oper_info.limit_interval:
         content = oper_info.info
         if extend_info:
             content += "\r\n" + "-----------------"*4
             content += "\r\n" + extend_info
         ret, ret_info = mail.send_mail(self.__smtp_host, self.__sender_mail, self.__sender_psw, 
                        oper_info.recver_list, oper_info.subject, content)
         oper_info.last_tick = now_time
         if not ret:
             self.__errinfo = ret_info
             twisted_log.INFO('send mail error! error_info = %s'%self.__errinfo)
             return False
     return True