Esempio n. 1
0
 def send_confirmation_mail(self):
     recipient = UsersModel.find_by_id(self.user_id).email
     quantity = str(self.quantity)
     isbn = str(self.isbn)
     subject = 'Order confirmation'
     message = 'Has comprat ' + quantity + ' llibre/s amb isbn ' + isbn
     send_email(recipient, subject, message)
Esempio n. 2
0
def send_email(self,
               send_to,
               subject,
               body,
               from_addr=None,
               cc=None,
               attachments=None):
    try:
        mail.send_email(send_to,
                        subject,
                        body,
                        from_addr,
                        cc=cc,
                        attachments=attachments,
                        timeout=conf.email_server.timeout)
    except Exception as e:
        if self.request.retries >= self.max_retries - 1:
            exception_to_sentry()
        else:
            logbook.warning(
                "Exception during sending email to {} with subject {}: {} from: {}",
                send_to,
                subject,
                e,
                from_addr,
                exc_info=True)
            send_email.retry(exc=e)
Esempio n. 3
0
    def post(self, request):
        """
        提交请求重置密码
        ---
        request_serializer: ApplyResetPasswordSerializer
        """
        serializer = ApplyResetPasswordSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            captcha = Captcha(request)
            if not captcha.check(data["captcha"]):
                return error_response(u"验证码错误")
            try:
                user = User.objects.get(email=data["email"])
            except User.DoesNotExist:
                return error_response(u"用户不存在")
            if user.reset_password_token_create_time and (now() - user.reset_password_token_create_time).total_seconds() < 20 * 60:
                return error_response(u"20分钟内只能找回一次密码")
            user.reset_password_token = rand_str()
            user.reset_password_token_create_time = now()
            user.save()
            email_template = codecs.open(settings.TEMPLATES[0]["DIRS"][0] + "utils/reset_password_email.html", "r", "utf-8").read()

            email_template = email_template.replace("{{ username }}", user.username).\
                replace("{{ website_name }}", settings.WEBSITE_INFO["website_name"]).\
                replace("{{ link }}", request.scheme + "://" + request.META['HTTP_HOST'] + "/reset_password/t/" + user.reset_password_token)

            send_email(settings.WEBSITE_INFO["website_name"],
                       user.email,
                       user.username,
                       settings.WEBSITE_INFO["website_name"] + u" 登录信息找回邮件",
                       email_template)
            return success_response(u"邮件发送成功,请前往您的邮箱查收")
        else:
            return serializer_invalid_response(serializer)
Esempio n. 4
0
def do_user(user_name):
    user = models.User(user_name)
    with user.lock:
        user.sync_from_db()
        try:
            if not (user.enabled and drivers[user.target].check_settings(
                    user.target_settings)):
                return  # Drivers should always return True or throw Exception. This means user disabled somewhere, we skip the user.
        except SyncException as e:
            if e.disable_user:
                user.enabled = False
                user.update()
            if e.logout_user:
                user.last_target = user.target
                user.target = None
                user.update()
            if e.send_email:
                mail.send_error_to_user(user.email, e.message,
                                        traceback.format_exc(), locals())
            else:
                mail.send_error_to_admin(traceback.format_exc(), locals())
            return
        except Exception as e:
            mail.send_error_to_admin(traceback.format_exc(), locals())  # TODO
            return
    try:
        if not api.ivle.validate_token(user):
            mail.send_email(
                user.email, 'IVLE Login Expired.',
                "Your IVLE login has expired. Please refresh by accessing our page and re-enable syncing."
            )
            with user.lock:
                user.sync_from_db()
                user.enabled = False
                user.update()
            return
    except Exception as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())  # TODO
        return

    try:
        file_list = api.ivle.read_all_file_list(user)
    except ConnectionError as e:
        return
    except Exception as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())
        return  # TODO: Should be Json Parsing Exception & Network Exception - We skip the user and inform the admin

    for file in file_list:
        if file['ID'] not in user.synced_files and not file_queue.fetch_job(
                '%s:%s' % (user_name, file['ID'])):
            file_queue.enqueue_call(func=do_file,
                                    args=(user_name, file['ID'], file['path'],
                                          file['size']),
                                    job_id='%s:%s' % (user_name, file['ID']),
                                    timeout=-1)
 def run_test(self):
     '''总程序执行'''
     p = subprocess.Popen('pytest -s -v {} --alluredir {}'.format(
         CASE_DIT, self.report_original_name))
     p.wait()
     cmd_new = 'allure generate {} -o {}'.format(self.report_original_name,
                                                 self.report_final_name)
     os.system(cmd_new)
     zip_files(self.zip_file, self.email_zip_file)
     send_email().email_init(self.email_zip_file, self.zip_name)
Esempio n. 6
0
    def __init__(self):
        self.sleep_time = settings.TIME
        # self.sleep_time = 20
        self.d_db = None    # 一次申报从数据库获取数据的子进程
        self.d_ftp = None   # 一次申报从ftp获取文件的子进程
        self.n_db = None    # 核注清单从数据库获取数据的子进程
        self.n_ftp = None   # 核注清单从ftp获取文件的子进程
        self.p_db = None    # 核放单从数据库获取数据的子进程
        self.p_ftp = None   # 核放单从ftp获取文件的子进程
        self.run_d_db()     # 启动时先执行一次程序(一次申报)
        self.run_d_ftp()    # 启动时先执行一次程序(一次申报)
        self.run_n_db()     # 启动时先执行一次程序(核注清单)
        # self.run_n_ftp()  # 启动时先执行一次程序(核注清单)
        self.run_p_db()     # 启动时先执行一次程序(核放单)
        self.run_p_ftp()  # 启动时先执行一次程序(核放单)

        while 1:
            try:
                while 1:
                    time.sleep(self.sleep_time)  # 休息10分钟,判断程序状态
                    self.monitor_process(self.d_db, self.run_d_db, '一次申报db')
                    self.monitor_process(self.d_ftp, self.run_d_ftp, '一次申报ftp')
                    self.monitor_process(self.n_db, self.run_n_db, '核注清单db')
                    # self.monitor_process(self.n_ftp, self.run_n_ftp, '核注清单ftp')
                    self.monitor_process(self.p_db, self.run_p_db, '核放单db')
                    self.monitor_process(self.p_ftp, self.run_p_ftp, '核放单ftp')

                    # if self.d_db.is_alive():
                    #     logger.info("%s,运行正常" % self.d_db.name)
                    #     # print("现在运行的是:%s,运行正常" % self.p.name)
                    # else:
                    #     logger.error("未检测到db进程运行状态,准备启动程序")
                    #     # print("未检测到程序运行状态,准备启动程序")
                    #     self.run_d_db()
                    #
                    # if self.d_ftp.is_alive():
                    #     logger.info("%s,运行正常" % self.d_ftp.name)
                    #     # print("现在运行的是:%s,运行正常" % self.p.name)
                    # else:
                    #     logger.error("未检测到ftp进程运行状态,准备启动程序")
                    #     # print("未检测到程序运行状态,准备启动程序")
                    #     self.run_d_ftp()
            except Exception as e:
                logger.exception(e)
                logger.error("程序异常,重启")
                mail.send_email(text=str(traceback.format_exc()), subject="ftp或db进程异常终止,请火速前往处理")
                logger.warn("ftp或db进程异常终止,以邮件通知")
                time.sleep(settings.EXCEPTION_WAIT_TIME)

                self.reload_process(self.d_db, self.run_d_db(), '一次申报db')
                self.reload_process(self.d_ftp, self.run_d_ftp(), '一次申报ftp')
                self.reload_process(self.n_db, self.run_n_db(), '核注清单db')
                # self.reload_process(self.n_ftp, self.run_n_ftp(), '一次申报ftp')
                self.reload_process(self.p_db, self.run_p_db(), '核注清单db')
                self.reload_process(self.p_ftp, self.run_p_ftp(), '一次申报ftp')
Esempio n. 7
0
File: mail.py Progetto: deti/boss
def send_email(self, send_to, subject, body, from_addr=None, cc=None, attachments=None):
    try:
        mail.send_email(send_to, subject, body, from_addr, cc=cc,
                        attachments=attachments, timeout=conf.email_server.timeout)
    except Exception as e:
        if self.request.retries >= self.max_retries - 1:
            exception_to_sentry()
        else:
            logbook.warning("Exception during sending email to {} with subject {}: {} from: {}",
                            send_to, subject, e, from_addr, exc_info=True)
            send_email.retry(exc=e)
Esempio n. 8
0
def do_file(user_name, file_id, file_path, file_size):
    user = models.User(user_name)
    url = api.ivle.get_file_url(user, file_id)
    if file_id in user.synced_files:
        return
    try:
        if not (user.enabled and drivers[user.target].check_settings(user.target_settings)):
            return
        if file_size > GLOBAL_MAX_FILE_SIZE or file_size > drivers[user.target].MAX_FILE_SIZE:
            raise SyncException(
                'File %s is too big to be automatically transferred. Please manually download it <a href="%s">here</a>. Sorry for the inconvenience!' % (
                    file_path, url), retry=False, send_email=True, disable_user=False, logout_user=False)
        if not api.ivle.validate_token(user):
            mail.send_email(user.email, 'IVLE Login Expired.', "Your IVLE login has expired. Please refresh by accessing our page and re-enable syncing.")
            with user.lock:
                user.sync_from_db()
                user.enabled = False
                user.update()
            return
        if drivers[user.target].transport_file(user, url, file_path):
            with user.lock:
                user.sync_from_db()
                user.synced_files.append(file_id)
                user.update()
        else:
            raise SyncException("transport_file returned False", retry=True, send_email=False, disable_user=False, logout_user=False)
    except SyncException as e:
        if not e.retry:
            with user.lock:
                user.sync_from_db()
                user.synced_files.append(file_id)
                user.update()
        if e.send_email:
            mail.send_error_to_user(user.email, e.message, traceback.format_exc(), locals())
        else:
            mail.send_error_to_admin(traceback.format_exc(), locals())
        if e.disable_user:
            with user.lock:
                user.sync_from_db()
                user.enabled = False
                user.update()
        if e.logout_user:
            with user.lock:
                user.sync_from_db()
                user.last_target = user.target
                user.target = None
                user.update()
        return
    except api.ivle.IVLEUnknownErrorException as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())
        return  # TODO: Walao eh IVLE bug again, skip it and inform the admin
    except Exception as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())
        return
Esempio n. 9
0
 def thread_get_remote_file(self):
     """从ftp获取文件的线程"""
     while 1:
         try:
             logger.info('ftp download start')
             self.task_start()
             logger.info('ftp download end')
             time.sleep(settings.LOOP_TIME)
         except Exception as e:
             logger.exception(e)
             mail.send_email(text=str(traceback.format_exc()), subject="下载回执线程异常,请火速前往处理")
             logger.warn("下载回执线程异常,以邮件通知")
             time.sleep(settings.EXCEPTION_WAIT_TIME)
Esempio n. 10
0
 def thread_analyze_receipt_upload_to_mdn(self):
     """分析回执,生成回执上传到mdn文件夹的线程"""
     while 1:
         try:
             logger.info('ftp analyze upload start')
             self.task_analyze_receipt_upload_to_mdn()
             logger.info('ftp analyze upload end')
             time.sleep(settings.LOOP_TIME)
         except Exception as e:
             logger.exception(e)
             mail.send_email(text=str(traceback.format_exc()),subject="分析-生成-上传回执线程异常,请火速前往处理")
             logger.warn("分析-生成-上传回执线程异常,以邮件通知")
             time.sleep(settings.EXCEPTION_WAIT_TIME)
def main():
    option_parser, opts, args = parse_command_line_parameters(**script_info)
    really = opts.really

    # if level is set to DEBUG log messages will be written
    logging.basicConfig(filename=opts.output_log_fp, level=logging.DEBUG, \
        format='[%(asctime)s].%(levelname)s: %(message)s')

    ag_data_access = data_access_factory(ServerConfig.data_access_type,
    'american_gut')

    # cursor to update the sent e-mails
    con = ag_data_access.getMetadataDatabaseConnection()

    cursor = ag_data_access.dynamicMetadataSelect("""
        select  al.name, al.email, ak.kit_verification_code, ak.supplied_kit_id, ak.kit_password, ak.swabs_per_kit
        from ag_login al
            inner join ag_kit ak
            on al.ag_login_id = ak.ag_login_id
            where ak.verification_email_sent = 'n'
        order by al.email""")

    for entry in cursor:
        recipient_name, target_email, verification_code, supplied_kit_id,\
            kit_password, swabs_per_kit = entry

        logging.debug('\n+++++++++++++++++++++++++++++++++++++++++++++++++++\n')

        logging.debug("""recipient_name {0}, target_email {1}, """
            """verification_code {2}, supplied_kit_id {3}, kit_password {4}, """
            """swabs_per_kit {5}\n""".format(recipient_name, target_email,
            verification_code, supplied_kit_id, kit_password, swabs_per_kit))

        buffer_message = BODY_MESSAGE.format(recipient_name, supplied_kit_id, verification_code)

        try:
            logging.debug('Message is %s\n' % buffer_message)
            logging.debug('Sent to %s\n' % target_email)
            
            if really == True:
                send_email(buffer_message, SUBJECT, target_email)
                query_string = "update ag_kit set verification_email_sent = 'y' where supplied_kit_id = '{0}'".format(supplied_kit_id)
                con.cursor().execute(query_string)
                con.cursor().execute('commit')
            else:
                logging.debug('DRY RUNNING, NOT SENDING A MESSAGE\n')
        except Exception, e:
            logging.debug('Exception value is %s\n' % str(e))
            logging.debug('ERROR SENDING TO: %s' % target_email)

        logging.debug('+++++++++++++++++++++++++++++++++++++++++++++++++++\n\n')
Esempio n. 12
0
 def run(self):
     if not settings.DB_TASK:
         return
     while 1:
         try:
             logger.info('%s start' % self.name)
             self.exec_task()
             logger.info('%s end' % self.name)
             time.sleep(settings.LOOP_TIME)
         except Exception as e:
             logger.exception(e)
             mail.send_email(text=str(traceback.format_exc()),
                             subject="db线程异常,请火速前往处理")
             logger.warn("db线程异常,以邮件通知")
             time.sleep(settings.EXCEPTION_WAIT_TIME)
    def _send_email(self, data_node_ip, text):
        try:
            # send email
            host_ip = getHostIp()
            version_str = '{0}-{1}'.format(__app__, __version__)
            subject = "[%s] %s" % (data_node_ip, text)

            body = "[%s] %s" % (data_node_ip, text)
            body += "\n" + version_str[0] + "\nip:" + host_ip

            #            email_from = "%s <noreply@%s>" % (options.sitename, options.domain)
            if options.send_email_switch:
                send_email(options.admins, subject, body)
        except Exception, e:
            logging.error("send email process occurs error", e)
Esempio n. 14
0
def login_send_email(request):
    if request.method == "POST":
        email = request.POST.get("email")
        is_email = User.objects.filter(email=email)
        if is_email.exists():
            if cache.get(email, 0):
                return JsonResponse({
                    'code': 1007,
                    'msg': '180内不能重复发送',
                })
            else:
                send = send_email(email)
                if send:
                    return JsonResponse({
                        'code': 1,
                        'msg': 'success',
                    })
                else:
                    return JsonResponse({'code': 1005, 'msg': '服务器正忙'})
        else:
            return JsonResponse({
                'code': 1004,
                'msg': '用户未注册',
            })
    else:
        return JsonResponse({'code': 1003, 'msg': '请求方式错误'})
Esempio n. 15
0
def do_user(user_name):
    user = models.User(user_name)
    with user.lock:
        user.sync_from_db()
        try:
            if not (user.enabled and drivers[user.target].check_settings(user.target_settings)):
                return  # Drivers should always return True or throw Exception. This means user disabled somewhere, we skip the user.
        except SyncException as e:
            if e.disable_user:
                user.enabled = False
                user.update()
            if e.logout_user:
                user.last_target = user.target
                user.target = None
                user.update()
            if e.send_email:
                mail.send_error_to_user(user.email, e.message, traceback.format_exc(), locals())
            else:
                mail.send_error_to_admin(traceback.format_exc(), locals())
            return
        except Exception as e:
            mail.send_error_to_admin(traceback.format_exc(), locals())  # TODO
            return
    try:
        if not api.ivle.validate_token(user):
            mail.send_email(user.email, 'IVLE Login Expired.', "Your IVLE login has expired. Please refresh by accessing our page and re-enable syncing.")
            with user.lock:
                user.sync_from_db()
                user.enabled = False
                user.update()
            return
    except Exception as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())  # TODO
        return

    try:
        file_list = api.ivle.read_all_file_list(user)
    except ConnectionError as e:
        return
    except Exception as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())
        return  # TODO: Should be Json Parsing Exception & Network Exception - We skip the user and inform the admin

    for file in file_list:
        if file['ID'] not in user.synced_files and not file_queue.fetch_job('%s:%s' % (user_name, file['ID'])):
            file_queue.enqueue_call(func=do_file, args=(user_name, file['ID'], file['path'], file['size']), job_id='%s:%s' % (user_name, file['ID']),
                                    timeout=-1)
    def _send_error_email(self, exception):
        try:
            # send email
            host_ip = getHostIp()

            version_str = '{0}-{1}'.format(__app__, __version__)
            subject = "[%s]Internal Server Error" % options.sitename

            exception += "\n" + version_str + "\nhost ip :" + host_ip

            #            body = self.render_string("errors/500_email.html", exception=exception)

            #            email_from = "%s <noreply@%s>" % (options.sitename, options.domain)
            if options.send_email_switch:
                send_email(options.admins, subject, exception)
        except Exception:
            logging.error(traceback.format_exc())
Esempio n. 17
0
    def _send_email(self, data_node_ip, text):
        try:
            # send email
            host_ip = getHostIp()
            invokeCommand = InvokeCommand()
            cmd_str = "rpm -qa beehive"
            version_str = invokeCommand._runSysCmd(cmd_str)
            subject = "[%s] %s" % (data_node_ip, text)

            body = "[%s] %s" % (data_node_ip, text)
            body += "\n" + version_str[0] + "\nip:" + host_ip

            #            email_from = "%s <noreply@%s>" % (options.sitename, options.domain)
            if options.send_email_switch:
                send_email(options.admins, subject, body)
        except Exception, e:
            logging.error("send email process occurs error", e)
Esempio n. 18
0
 def reload_process(self, process, run_process, name):
     """
     重启进程
     :param process: 进程
     :param run_process: 进程启动函数
     :param name: 进程名称(一次申报、核注单、核放单)
     :return: None
     """
     try:
         process.terminate()
     except Exception as e:
         logger.exception(e)
         logger.error("{}进程结束发生异常,重启{}进程".format(name, name))
         mail.send_email(text=str(traceback.format_exc()), subject="{}进程结束发生异常,请火速前往处理".format(name))
         logger.warn("{}进程结束发生异常,以邮件通知".format(name))
     finally:
         run_process()
Esempio n. 19
0
 def post(self):
     if request.form and 'cancel' in request.form:
         return redirect(url_for('index'))
     email = request.form.get('email', None)
     status = check_email(email)
     if status:
         return render_template('account.forget.html', error=status[1])
     user = get_user_by_email(email=email)
     if user:
         stub = create_token(20)
         try:
             send_email(user.email, \
                 config.FORGET_EMAIL_TITLE,
                 origin_render('email.html', user=user, stub=stub))
         except:
             logger.exception("send mail failed")
         create_forget(user.id, stub)
     return render_template('account.forget.html', send=1)
    def _send_error_email(self, exception):
        try:
            # send email
            host_ip = getHostIp()
            invokeCommand = InvokeCommand()
            cmd_str = "rpm -qa beehive"
            version_str = invokeCommand._runSysCmd(cmd_str)
            subject = "[%s]Internal Server Error" % options.sitename

            exception += "\n" + version_str[0] + "\nhost ip :" + host_ip

            #            body = self.render_string("errors/500_email.html", exception=exception)

            #            email_from = "%s <noreply@%s>" % (options.sitename, options.domain)
            if options.send_email_switch:
                send_email(options.admins, subject, exception)
        except Exception:
            logging.error(traceback.format_exc())
Esempio n. 21
0
    def _send_error_email(self, exception):
        try:
            local_ip = get_host_ip()
            invokeCommand = InvokeCommand()
            cmd_str = "rpm -qa jetty-manager"
            version_str = invokeCommand._runSysCmd(cmd_str)
            logging.info("version_str :" + str(version_str))
            # send email
            subject = "[%s]Internal Server Error " % options.sitename
            body = self.render_string("errors/500_email.html",
                                      exception=exception)

            body += "\n" + version_str[0] + "\nip:" + local_ip

            #            email_from = "%s <noreply@%s>" % (options.sitename, options.domain)
            if options.send_email_switch:
                send_email(options.admins, subject, body)
        except Exception:
            logging.error(traceback.format_exc())
Esempio n. 22
0
    def _send_error_email(self, exception):

        try:
            local_ip = getHostIp()

            version_str = '{0}-{1}'.format(__app__, __version__)
            logging.info("version_str :" + str(version_str))
            # send email
            subject = "[%s]Internal Server Error " % options.sitename
            body = self.render_string("../templates/errors/500_email.html",
                                      exception=exception)

            body += "\n" + version_str + "\nip:" + local_ip

            #            email_from = "%s <noreply@%s>" % (options.sitename, options.domain)
            if options.send_email_switch:
                send_email(options.admins, subject, body)
        except Exception:
            logging.error(traceback.format_exc())
Esempio n. 23
0
    def form_valid(self, form):
        form.submit()

        subject, body = self.prepare_message(**form.cleaned_data)
        success = send_email(to_email=self.to_email,
                             subject=subject,
                             message=body)
        if success:
            return super().form_valid(form)

        return redirect("feedback_error", err_type="send")
Esempio n. 24
0
def notify(rp, action_taken=False):
    if rp['email_alert']:

        # Check last email sent time and send condition
        let = Cacher().get_last_email_time(rp['app'], rp['dyno'],
                                           rp['category'])
        if int(time.time()) - let > settings.EMAIL_COOLING_PERIOD_PER_TOPIC:
            # Send email
            logging.warning("Sending email. Topic: {}:{}:{}".format(
                rp['app'], rp['dyno'], rp['category']))
            sub = "{} Error Detected in {}:{}".format(rp['category'],
                                                      rp['app'], rp['dyno'])
            msg = "Atleast {} error(s) of type {} detected in the last {} seconds. ".format(
                rp['least_count'], rp['category'], rp['time_window'])
            msg += "Action taken: {}".format(
                rp['action']) if action_taken else ""
            send_email(sub, msg)
            Cacher().set_last_email_time(rp['app'], rp['dyno'], rp['category'])
            return True

    return False
Esempio n. 25
0
def main(argv):

    last_prices = []

    log_path = os.path.dirname(
               os.path.abspath(__file__)) + data.get("logger",{}).get("path", "")

    logger = logging_setup(__name__, log_path)

    r = requests.get(data.get("api",""))
    raw_result = r.text
    result = json.loads(raw_result)

    current_price = 0.0

    for cex_data in result.get("data", []):
        for track in data.get("track", []):
            if cex_data.get("symbol1","") == track.get("symbol1", "") and cex_data.get("symbol2","") == track.get("symbol2",""):
                current_price = float(cex_data.get("lprice"))
                last_bought_price = get_eth_price()

                for price in last_prices:
                    if price >= current_price + 100:
                        send_email(data.get("alerts",{}).get("user",""), data.get("alerts",{}).get("password",""), data.get("alerts",{}).get("to",[]), "ALERTA COMPRAR DINEROS", "Bajón de precio a {}. ¡Comprando ETH!".format(current_price)))
                        save_eth_price(current_price)
                        break

                if last_bought_price > 0:
                    if last_bought_price + 100 <= current_price:
                        send_email(data.get("alerts",{}).get("user",""), data.get("alerts",{}).get("password",""), data.get("alerts",{}).get("to",[]), "ALERTA COMPRAR DINEROS", "Subidón de precio a {}. ¡Vendiendo ETH!".format(current_price)))
                        save_eth_price(0)
                        break

                last_prices.append(current_price)
                if len(last_prices) > 6:
                    del last_prices[0]

                logger.info("{} current price: {} {}".format(cex_data.get("symbol1",""), current_price, cex_data.get("symbol2","")))

                if current_price <= track.get("limits",{}).get("min", 0):
                    send_email(data.get("alerts",{}).get("user",""), data.get("alerts",{}).get("password",""), data.get("alerts",{}).get("to",[]), "ALERTA DINEROS", "{0} por debajo del limite ({3} {2})\n\nPrecio actual: {1} {2}".format(track.get("symbol1", ""), current_price, cex_data.get("symbol2",""), track.get("limits",{}).get("min", 0)))
Esempio n. 26
0
    def send_email(cls, user_id, transactions):
        recipient = UsersModel.find_by_id(user_id).email

        msg = "Has comprat els seguents llibres:\n - " + ",\n - ".join(
            transactions)
        send_email(recipient, 'Confirmacio del correu', msg)
Esempio n. 27
0
 def send_email(self, email, url_root):
     message = f"Gràcies per registrarte a BookShelter! Accedeix a {url_root}verify?key={self.key} "\
               f"per confirmar el teu email. \n L'enllaç deixarà de ser vàlid en {self.VALID_UNTIL}"
     send_email(email, 'Verify your email', message)
Esempio n. 28
0
import unittest
from utils.HTMLTestRunner import HTMLTestRunner
from utils.mail import send_email

# 1,加载所用的测试用例
# unittest自动到case文件夹下去查找test_*.py的里面的所用继承untest.testCase的test_方法.
testcase = unittest.defaultTestLoader.discover("case", "test_*.py")

# 2,使用htmltestrunner运行测试用例,并收集测试报告
filepath = "./report/report.html"
title = '测试报告'
desc = "这个测试报告描述"
# wb w=写 b=字节  以字节的方式写入它 as f 用一个f的变量保存起来
with open(filepath, "wb") as f:
    runner = HTMLTestRunner(stream=f, title=title, description=desc)
    runner.run(testcase)

# 3.发送邮件,发送最新测试报告html
send_email(filepath)
Esempio n. 29
0
def _send_email(from_name, to_email, to_name, subject, content):
    send_email(from_name, to_email, to_name, subject, content)
Esempio n. 30
0
def do_file(user_name, file_id, file_path, file_size):
    user = models.User(user_name)
    url = api.ivle.get_file_url(user, file_id)
    if file_id in user.synced_files:
        return
    try:
        if not (user.enabled
                and drivers[user.target].check_settings(user.target_settings)):
            return
        if file_size > GLOBAL_MAX_FILE_SIZE or file_size > drivers[
                user.target].MAX_FILE_SIZE:
            raise SyncException(
                'File %s is too big to be automatically transferred. Please manually download it <a href="%s">here</a>. Sorry for the inconvenience!'
                % (file_path, url),
                retry=False,
                send_email=True,
                disable_user=False,
                logout_user=False)
        if not api.ivle.validate_token(user):
            mail.send_email(
                user.email, 'IVLE Login Expired.',
                "Your IVLE login has expired. Please refresh by accessing our page and re-enable syncing."
            )
            with user.lock:
                user.sync_from_db()
                user.enabled = False
                user.update()
            return
        if drivers[user.target].transport_file(user, url, file_path):
            with user.lock:
                user.sync_from_db()
                user.synced_files.append(file_id)
                user.update()
        else:
            raise SyncException("transport_file returned False",
                                retry=True,
                                send_email=False,
                                disable_user=False,
                                logout_user=False)
    except SyncException as e:
        if not e.retry:
            with user.lock:
                user.sync_from_db()
                user.synced_files.append(file_id)
                user.update()
        if e.send_email:
            mail.send_error_to_user(user.email, e.message,
                                    traceback.format_exc(), locals())
        else:
            mail.send_error_to_admin(traceback.format_exc(), locals())
        if e.disable_user:
            with user.lock:
                user.sync_from_db()
                user.enabled = False
                user.update()
        if e.logout_user:
            with user.lock:
                user.sync_from_db()
                user.last_target = user.target
                user.target = None
                user.update()
        return
    except api.ivle.IVLEUnknownErrorException as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())
        return  # TODO: Walao eh IVLE bug again, skip it and inform the admin
    except Exception as e:
        mail.send_error_to_admin(traceback.format_exc(), locals())
        return
Esempio n. 31
0
 def send_email(self, email, url_root):
     message = f"Has sol·licitat una recuperació de contrasenya. Accedeix a {url_root}reset?key={self.key} "\
               f"per canviar de contrasenya. \n L'enllaç deixarà de ser vàlid en {self.VALID_UNTIL} o si es torna " \
               f"a solicitar un canvi en la mateixa compte."
     send_email(email, 'Password recovery', message)
Esempio n. 32
0
aggregated_data = {}

for symbol in symbols.split(","):
    currency = data[symbol]
    name = currency["name"]
    symbol = currency["symbol"]
    circulation_supply = currency["circulating_supply"]
    total_supply = currency["total_supply"]
    quotes = currency["quote"]["USD"]

    price = quotes["price"]
    market_cap = quotes["market_cap"]
    percent_change_1h = quotes["percent_change_1h"]
    percent_change_24h = quotes["percent_change_24h"]
    percent_change_7d = quotes["percent_change_7d"]

    currency_data = {}
    currency_data["Name"] = name
    currency_data["Circulation Supply"] = circulation_supply
    currency_data["Total Supply"] = total_supply
    currency_data["Market Cap"] = market_cap
    currency_data["Hour Change"] = str(percent_change_1h)
    currency_data["Day Change"] = str(percent_change_24h)
    currency_data["Week Change"] = str(percent_change_7d)
    currency_data["Price"] = price

    aggregated_data[symbol] = currency_data

if __name__ == "__main__":
    send_email(aggregated_data)