Ejemplo n.º 1
0
def stream(model):
    with picamera.PiCamera() as camera:
        camera.resolution = (IMG_WIDTH, IMG_LENGTH)
        x, y, w, h = 0.20, 0.37, 0.59, 0.8
        camera.zoom = x, y, w, h
        camera.rotation = 180
        camera.start_preview()
        incorrect_parking_counter = 0
        while True:

            image = np.empty((IMG_WIDTH, IMG_LENGTH, IMG_CHANNEL),
                             dtype=np.uint8)
            camera.capture('image.jpg')
            image = cv2.imread('./image.jpg')
            #camera.capture(image, 'rgb')
            #camera.stop_preview()

            #print(image.shape)
            image = cv2.resize(image, (IMG_LENGTH, IMG_WIDTH))
            image = image.reshape(1, IMG_WIDTH, IMG_LENGTH, IMG_CHANNEL)
            #print(image)
            prediction = model.predict(image)
            if (prediction == 0):
                incorrect_parking_counter += 1
                blink()
                if incorrect_parking_counter >= 15 and is_same_misparked_car != True:
                    print("Sending email...")
                    send_email()
                    is_same_misparked_car = True
                    incorrect_parking_counter = 0
            else:
                is_same_misparked_car = False
                incorrect_parking_counter = 0
Ejemplo n.º 2
0
def register():
    """
    Register new User. Creates a new User object, updates the database and returns the session token.
    :return: Session token if successful, an Error otherwise.
    """
    # Get new User details from form:
    email = request.form['email']
    password = request.form['password']  # The given password is already hashed
    notification_token = request.form['notification_token']
    postcode = request.form['postcode']
    # Check for errors:
    if type(password) is not str or not password:
        return jsonify({"error": "password_error"})
    if type(notification_token) is not str or "ExponentPushToken[" not in notification_token:
        return jsonify({"error": "notification_token_error"})
    if type(postcode) is not str or len(postcode) < 6 or len(postcode) > 8:  # Check that the postcode is valid
        return jsonify({"error": "postcode_error"})
    if not email_sender.is_valid_email(email):  # Check that the given email is a valid email address
        return jsonify({"error": "email_error"})

    if not is_new_address(email):  # Check if the given email is already in use
        return jsonify({"error": "email_in_use_error"})

    # Add new user to the database:
    new_user = core.User(email, password, notification_token, postcode, create_session_token())  # Create new user
    add_user_to_database(new_user)  # Add new User to the database
    # Send email to user's email address
    email_sender.send_email(new_user.email, "Insight: Registration", "Thanks for registering to use the Insight app!"
                                                                     "\n\n-The Insight team")
    # Return the session token
    return jsonify({"session_token": new_user.session_token})
Ejemplo n.º 3
0
def send_message():
    """
    Sends an email to a member of parliament specified by the user.
    Requires user verification, MP id and the message itself.
    :return: A success message, if the email was sent successfully, otherwise an error message
    """
    # Get user info for verification
    email = request.form['email']
    session_token = request.form['session_token']
    # Get information to send email
    mp_id = request.form['mp_id']
    message = request.form['message']
    # Verify the user:
    if not verify_user(email, session_token):  # Verify the user
        return jsonify({"error": "invalid_credentials"})  # Verification unsuccessful

    mp = fetch_mp(mp_id)  # Construct and return the parliament member by following given id

    if mp:  # If the MP was successfully constructed
        try:
            email_sender.send_email(mp.email, "Insight Update!", message)  # Send the email
            return jsonify({"success": "email_sent"})  # If sent without errors, return success message
        except Exception as e:
            return jsonify({"error": "email_failed_to_send"})  # Error with mail sending

    return jsonify({"error": "mp_database_error"})  # Could not build ParliamentMember
Ejemplo n.º 4
0
    def _relay_messages_to_email(self, user_id):
        chat_bubbles = ChatBubble.select().where(
            ChatBubble.user_id == user_id).order_by(ChatBubble.timestamp.asc())

        messages = []
        for chat_bubble in chat_bubbles:
            messages.append("> " + chat_bubble.message)

        ChatBubble.delete().where(ChatBubble.user_id == user_id).execute()

        try:
            participant = Participant.select().where(
                Participant.line_mid == user_id).get()
            email_id = participant.email_id
            name = participant.name
        except:
            email_id = '%30x' % random.randrange(16**30)
            name = generate_random_name()
            participant = Participant(line_mid=user_id,
                                      email_id=email_id,
                                      name=name)
            participant.save()

        recipient = f"{email_id}@{self.email_domain}"
        body = "\n".join(messages)

        subject = f"Incoming Message from {name}"
        send_email(recipient, name, self.to_email, self.to_name, subject, body)

        if (self.enquiry_received_reply):
            self.line_bot_api.push_message(
                user_id, TextSendMessage(text=self.enquiry_received_reply))
Ejemplo n.º 5
0
def server_call(filename, config, email):
    tempdir = tempfile.TemporaryDirectory()
    TEMPDIR = Path(tempdir.name)
    CDTESTDIR = TEMPDIR / "cd-test"
    OUTPUTDIR = TEMPDIR / "output"

    if not Path(OUTPUTDIR).is_dir():
        os.mkdir(OUTPUTDIR)

    subprocess.run([
        "git", "clone", "https://git.labs.nuance.com/nlps-qa/cd-test",
        str(CDTESTDIR)
    ],
                   check=True)

    dest_filename = OUTPUTDIR / f"{filename}.xlsx"
    for i in config:
        branch = i['branch']
        folder = i['folder']
        update_tests_for_branch(branch, CDTESTDIR)
        convert.generate_excel(CDTESTDIR / folder,
                               OUTPUTDIR / f"{branch}+{folder}.xlsx")

    merge.merge_excel(OUTPUTDIR, dest_filename)
    email_sender.send_email(dest_filename, filename, email)
Ejemplo n.º 6
0
def stocks():
    if request.method == 'POST':
        data = request.form.to_dict() 
        email_sender.send_email(data["email"])
        return render_template('/thankyou.html')   
    else:
        'error'
 def borrow_a_book(book_id, user_email, name):
     """
     This methods will execute the POST request to the REST API and provided users additional services...
     :param book_id: id of the book the user want to borrow_a_book
     :param user_email: email of the user who is currently using this application
     :param name: name of the user
     :return: a string to remind of the user of due date
     """
     user_id = BorrowService.get_instance().get_user_id_from_email(user_email, name)
     # Check if user has already borrowed the book and has not returned
     req = requests.post(url=borrow_a_book_route(book_id, user_id))
     res = req.json()
     if "message" in res.keys():
         print("Error: {}".format(res["message"]))
         print("Cancelling transaction...")
         time.sleep(3)
     else:
         g_cal_option = input("Would you like to be reminded of the due date via Google Calendar (Y/n)? ")
         if g_cal_option.strip().upper() == 'Y':
             event_id = event_insert(user_email, book_id, name)
             if event_id is None:
                 print("Not a Gmail account. Calendar services are unavailable!")
                 print("Cancelling transaction...")
                 time.sleep(3)
             else:
                 borrow_id = res['id']
                 BorrowService.get_instance().remind_via_google_calendar(borrow_id, event_id)
         opt_in_qr = input("Would you like to use the Quick Return service (Y/n)? ")
         if opt_in_qr.strip().upper() == 'Y':
             qr_generator(res['id'])
             send_email(user_email)
         print("Success!")
         return "Please return this book before: {}".format(res['due_date'])
Ejemplo n.º 8
0
def upload():
    body = json.loads(request.data)
    longitude = body.get("longitude")
    latitude = body.get("latitude")
    base64 = body.get("base64")
    email = body.get("email")
    if base64 is None:
        return json.dumps({"error": "No base64 URL to be found!"})
    cat = Cat(name=f"Cat {get_rand_name()}")
    db.session.add(cat)
    db.session.commit()
    entry = Entry(longitude=longitude,
                  latitude=latitude,
                  base64_str=base64,
                  cat_id=cat.id)
    db.session.add(entry)
    db.session.commit()
    send_email(
        email=email or
        "[email protected],[email protected],[email protected],[email protected],[email protected]",
        subject=f"{cat.name} has been spotted!",
        body=f"Here's the pic of the cat!",
        s3_url=entry.s3_url,
    )
    return success_response(entry.serialize(), 201)
def add_user(jira, issue, cs, username, first_name, last_name, display_name,
             password, email, ticket_number, lastAuthenticated):
    ''' Adds user, adds attributes, adds groups, transitions workflow to complete, and finally sends an email to new user '''
    if cs.add_user(username,
                   first_name=first_name,
                   last_name=last_name,
                   display_name=display_name,
                   password=password,
                   email=email):
        print "---- " + username + " has been successfully added! ----"
        if cs.set_user_attribute(username, 'Ticket Number',
                                 ticket_number) & cs.set_user_attribute(
                                     username, 'lastAuthenticated',
                                     lastAuthenticated):
            print "---- Attributes have been added! ----"
        if cs.add_user_to_group(
                username, 'confluence-users') & cs.add_user_to_group(
                    username, 'jira-developers') & cs.add_user_to_group(
                        username, 'jira-users'):
            print "---- User has been added to groups! ----"
        jira.transition_issue(issue, '971')
        send_email(username, email)
        return 1
    else:
        print "---- Failed to add user for some reason ----"
        return 0
def send_certificate():
    """ 
    Iterate through the attendee list from the CSV file,
    Insert the attendee name on the center of the certificate image,
    then opens Outlook Application and sends the email to the recipients that includes the certificate attachment
    """
    for attendee in attendee_list:
        img = cv2.imread(template_path)
        imgResize = cv2.resize(img, imageWxH)

        name = attendee[0]        
        email = attendee[1]
        textSize = cv2.getTextSize(name, font, 2, 2)[0]

        # Center text on image based on image and text size
        textX = int((imgResize.shape[1] - textSize[0]) / 2)
        textY = int((imgResize.shape[0] + textSize[1]) / 2)

        # Insert attendee name on certificate template
        cv2.putText(imgResize, name, (textX, textY), font, fontScale, fontColor, lineType)

        try:
            # Use Attendee Name as File Name and save it on certificate folder
            certificatePath = os.path.join(os.getcwd(), "certificate", name.replace(" ", "").replace(".", "").lower() + ".png")
            cv2.imwrite(certificatePath, imgResize)

            emailBody = generate_email_body(name)

            esender.send_email(email, emailSubject, emailBody, certificatePath, not isDebug)
        except Exception as e:
            print(e)
Ejemplo n.º 11
0
def diff_send_email(**kwargs):
    try:

        not_matching_records = bs(Variable.get('usdtoinr_non_match_records'),
                                  'html.parser')
        not_matching_records_len = int(
            Variable.get('usdtoinr_non_match_record_cnt'))
        today = str(datetime.now().replace(microsecond=0)).replace(
            ' ', '_').replace(':', '_')

        if not_matching_records_len >= 1:
            logging.info('Preparing to send email notification')
            EMAIL_ADDRESS = os.getenv('EMAIL_ADDRESS')
            #print(EMAIL_ADDRESS)
            EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')
            #print(EMAIL_PASSWORD)
            subject = "Today's Best US Dollars to Indian Rupees (USD to INR) Exchange Rate: " + today
            to = EMAIL_ADDRESS
            bcc = eval(Variable.get('airflow_usd_to_inr_bcc_list'))
            content1 = """Below are the updated rates:
            """
            content2 = """
Today's USD to INR rates:
            """
            footer = """
            
            
Thanks,
Sudhakar
            
            """
            file_name = ''
            #attachig the file to email
            #with open('remetely_rate_difference.csv','w') as f:
            #    not_matching_records.to_csv(f,index=False,sep='\t',float_format='%.2f')

            try:
                data_set = Variable.get('usdtoinr_non_match_records')
                today_data_set = Variable.get('usdtoinr_today_agent_data')

                body = {
                    content1: data_set,
                    content2: today_data_set,
                    footer: ''
                }
                #logging.info(body)

                email_sender.send_email(EMAIL_ADDRESS, EMAIL_PASSWORD, subject,
                                        to, bcc, body, file_name)
                logging.info('Sent email sucessfully')
            except BaseException as e:
                logging.error('Failed process of sending email: {0}'.format(e))
                raise Exception(
                    'Failed process of sending email: {0}'.format(e))
        else:
            logging.info('No difference found in agent rates')
    except BaseException as e:
        logging.error('send_email method logic issue: {0}'.format(e))
        raise Exception('send_email method logic issue: {0}'.format(e))
Ejemplo n.º 12
0
def submit_form():
    if request.method == 'POST':
        data = request.form.to_dict()
        dataio.add_data('first_collection', data)
        send_email({
            'to': '*****@*****.**',
            'from': data['email'],
            'subject': 'ZTM Lead ' + data['name'],
            'message': data['message']
        })
    return 'Form Submitted'
Ejemplo n.º 13
0
def reactivate_user(jira, issue, cs, username, first_name, last_name, display_name, password, email, ticket_number, lastAuthenticated):
    print 'Attempting to reactivate user ....'
    if cs.set_active(username, True):
        print "---- " + username + " has been successfully reactivated! ----"
        if cs.set_user_attribute(username,'Ticket Number',ticket_number) & cs.set_user_attribute(username,'lastAuthenticated',lastAuthenticated):
            print "---- Attributes have been adjusted! ----"
        jira.transition_issue(issue, '971')
        send_email(username, email)
        return 1
    else:
        print "---- Failed to reactivate - please check the user for further information. ----"
        return 0
Ejemplo n.º 14
0
def notify_by_email(addressee, status_ok, output_html_path, msg=''):
    from email_sender import send_email  # from /bioseq/bioSequence_scripts_and_constants/
    if not msg:
        msg = f"{CONSTS.PIPELINE_NAME} pipeline {'FINISHED' if status_ok else 'FAILED'}. Results can be found at {output_html_path}."
    logger.info(msg)
    send_email(
        CONSTS.SMTP_SERVER,
        CONSTS.ADMIN_EMAIL,
        addressee,
        subject=
        f"{CONSTS.PIPELINE_NAME} {'FINISHED' if status_ok else 'FAILED'}",
        content=msg)
Ejemplo n.º 15
0
def activate_user(jira, issue, cs, username, first_name, last_name, display_name, password, email, ticket_number, lastAuthenticated):
    print 'Attempting to add new user ....'
    if cs.add_user(username, first_name=first_name, last_name=last_name, display_name=display_name, password=password, email=email):
        print "---- " + username + " has been successfully added! ----"
        if cs.set_user_attribute(username,'Ticket Number',ticket_number) & cs.set_user_attribute(username,'lastAuthenticated',lastAuthenticated):
            print "---- Attributes have been added! ----"
        if cs.add_user_to_group(username,'confluence-users') & cs.add_user_to_group(username,'jira-developers') & cs.add_user_to_group(username,'jira-users'):
            print "---- User has been added to groups! ----"
        jira.transition_issue(issue, '971')
        send_email(username, email)
        return 1
    else:
        print "---- Failed to add - attempting to reactivate user instead. ----"
        return reactivate_user(jira, issue, cs, username, first_name, last_name, display_name, password, email, ticket_number, lastAuthenticated)
Ejemplo n.º 16
0
def scrape_and_check(store, username, password, gmail_user, gmail_password):
    old_appartments = store.get('appartments', [])
    old_urls = [oa.get('url') for oa in old_appartments]
    appartments = scraper.scrape(username, password)
    new_appartments = []
    for a in appartments:
        if a.get('url') not in old_urls:
            print(get_timestamp() + " NEW " + a.get('url'))
            new_appartments.append(a)

    store['appartments'] = appartments
    for a in new_appartments:
        email_sender.send_email(gmail_user, gmail_password, "Ny lgh!",
                                create_body(a))
Ejemplo n.º 17
0
def notify_user(run_number, email, job_title, msa_name, tree_name):
    job_name = f'{job_title}\n' if job_title else ''
    notification_content = f'Your submission details are:\n\n{job_name}'

    notification_content += f'Multiple sequence alignment: {msa_name}\n'
    notification_content += f'Phylogenetic tree: {tree_name}\n'

    notification_content += f'Once the analysis will be ready, we will let you know! Meanwhile, you can track the ' \
        f'progress of your job at:\n{CONSTS.WEBSERVER_URL}/results/{run_number}/{CONSTS.RESULT_WEBPAGE_NAME}\n\n'

    send_email(
        smtp_server=CONSTS.SMTP_SERVER,
        sender=CONSTS.ADMIN_EMAIL,
        receiver=f'{email}',
        subject=
        f'{CONSTS.WEBSERVER_NAME.upper()} - your job has been submitted! (Run number: {run_number})',
        content=notification_content)
Ejemplo n.º 18
0
async def main(args):
    emails = parse_emails(args.file_path)
    if emails:
        for email in emails:
            task = asyncio.create_task(
                send_email(args.host, args.username, email, args.password,
                           args.port, args.subject, args.message))
            await asyncio.wait([task])
Ejemplo n.º 19
0
def success():
    rent = RentingCart(session['username'], mysql)
    content = rent.viewcartdetails()
    cost = rent.calprice(content)
    cart_now = Orders(rent, session['username'], mysql)
    cart_now.placeorder(cost)
    cur = mysql.connection.cursor()
    q = 'SELECT email FROM MyUsers WHERE username LIKE %s'
    cur.execute(q, [session['username']])
    mail.init_app(app)
    email = cur.fetchone()[0]
    template = f'<p>Your Order is successful you can visit and verify from our website' \
               f'<br><p>Thank U for shopping in our website</p><br><p>Cheers!</p> '
    send_email(app.config['DEFAULT_MAIL_SENDER'], email,
               f"{session['username']}, Your Order has been conformed",
               template)
    return '<h1>Success</h1> <a class="dropdown-item" href="/account_info#MyOrders">Redirect to account Info</a>'
Ejemplo n.º 20
0
def wrapped_email_sender(config_dict=dict(), xls_format=False):
    try:
        if xls_format:
            email_context = config_dict["email_context"].replace('txt', 'csv')
        else:
            email_context = config_dict["email_context"]

        email_sender.send_email(from_addr=config_dict["from_addr"],
                                password=config_dict["password"],
                                smtp_server=config_dict["smtp_server"],
                                to_addr=config_dict["to_addr"],
                                email_context=email_context,
                                xls_format=xls_format)
    except Exception as e:
        print(e)

    print("Waring Email Sent!",
          "To addr: {addr}".format(**{'addr': config_dict["to_addr"]}))
Ejemplo n.º 21
0
def add_student_to_course(course, student):
    # serialization of objects
    student_binary = pickle.dumps(student)
    course_binary = pickle.dumps(course)

    if not student in course.students:
        collection.update_one({'_id': course.unique_id}, {
            '$set': {
                'course': course_binary
            },
            '$push': {
                'students': student_binary
            },
        },
                              upsert=True)
        course.add_student(student)
        send_email(student, course, 'verification')
    else:
        raise StudentExistsException()
Ejemplo n.º 22
0
 def get(self, str_page, n_index):
     if str_page == 'process':
         user_email = request.headers['email']
         if n_index == 0:
             #Head & Neck
             # main_head_neck.main(user_email)
             email_sender.send_email(
                 user_email, None, os.path.join(var.name_dir_output, user_email, var.name_output_file))
             print(f'Email sent to: {user_email}')
             shutil.rmtree(os.path.join(var.name_dir_output, user_email))
             return var.json_success, 200
         else:
             return var.json_failure, 400
     elif str_page == 'image':
         user_email = request.headers['email']
         code = DicomImage.get_random_image_base64text(user_email)
         return {var.str_base64_key: code}, 200
     else:
         return var.json_failure, 400
Ejemplo n.º 23
0
def success():
    if request.method == 'POST':
        email = request.form['email_name']
        height = request.form['height_name']


        if db.session.query(Data).filter(Data.email == email).count() == 0:
            data = Data(email, height)
            db.session.add(data)
            db.session.commit()
            average_hight = db.session.query(func.avg(Data.height)).scalar()
            average_hight = round(average_hight)

            count = db.session.query(Data.height).count()

            send_email(email, height, average_hight, count)

            return render_template('success.html')

        return render_template('index.html', text = "Email already used")
Ejemplo n.º 24
0
def main(csv_file):
    with open(csv_file) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        print(csv_file, '\n', csv_reader)
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                print(
                    f'\t{row[0]} email id is \t\t{row[2]} works at \t{row[3]}.'
                )
                line_count += 1
                first_name, email = email_sender.set_content(
                    to_email_id=row[2], first_name=row[0])
                email_sender.send_email(first_name, email)
                if line_count == 2:
                    break
        print(f'Processed {line_count} lines.')
Ejemplo n.º 25
0
def login():
    """
    Log in to the application using the user's password. Checks if the email address is used, and checks the password.
    :return: Message with the user's unique token if successful, or an error message explaining why login failed.
    """
    # Get form information:
    email = request.form['email']
    password = request.form['password']
    if is_new_address(email):
        return jsonify({"error": "new_email_error"})  # Email does not correspond to a User
    # Get user from database using username, check if user is valid.
    user = fetch_user(email)  # Construct the user object
    if user and user.verify_password(password):
        # Send email to user address informing of new login
        email_sender.send_email(user.email, "Insight: new login", "A new device signed in to your Insight account. We'"
                                                                  "re sending you this email to make sure it was you!"
                                                                  " If it wasn't, please respond to this email to let "
                                                                  "us know!\n\n-The Insight team")
        return jsonify({"session_token": user.session_token})  # Return the session token
    # Return the session token
    return jsonify({"error": "incorrect_password_error"})  # Given wrong password
    def core_test(self, timestamp, image_path_list):

        send_email(self.project_conf, timestamp, image_path_list)

        sleep(2)

        msg, test_email_id = self.retrieve_email("INBOX")
        im_num = 0
        for part in msg.walk():
            self.assertIn(part.get_content_type(), self.MAIL_CONTENT_TYPES,
                          "Unexpected message part")
            if part.get_content_type() == self.MAIL_CONTENT_TYPES[0]:
                receivers = ", ".join(self.project_conf["email_list_to_alert"])
                self.assertEqual(part["To"], receivers)
            elif part.get_content_type() == self.MAIL_CONTENT_TYPES[1]:
                formated_timestamp = strftime("%A %d %B %Y %H:%M:%S",
                                              localtime(timestamp))
                text_msg = "PiCamera has detected motion"\
                           "\r\nTimestamp: {}".format(formated_timestamp)
                self.assertEqual(part.get_payload(), text_msg)
            elif part.get_content_type() == self.MAIL_CONTENT_TYPES[2]:
                self.assertEqual(part.get_filename(),
                                 path.basename(image_path_list[im_num]))
                image_email = part.get_payload(decode=True)
                image_email_hash = hashlib.sha256(image_email).hexdigest()
                with open(image_path_list[im_num], "rb") as image_raw:
                    image = image_raw.read()
                image_hash = hashlib.sha256(image).hexdigest()
                self.assertEqual(image_email_hash, image_hash)
                im_num += 1

        self.mail_server.store(test_email_id, '+X-GM-LABELS', '\\Trash')
        self.mail_server.expunge()

        msg, test_email_id = self.retrieve_email("Trash")
        self.mail_server.store(test_email_id, '+FLAGS', '\\Deleted')

        self.mail_server.expunge()
        self.mail_server.close()
        self.mail_server.logout()
Ejemplo n.º 27
0
def process_recording():
    session_id = str(uuid.uuid4())
    temp_rec_file_name = f'{session_id}.wav'
    try:
        recording_file = request.files['recording_file']
        email = request.form['email']
        print(
            f'Got a new request for email {email}. Assigned {session_id} as the session id'
        )
        recording_file.save(temp_rec_file_name)
        trans_results = transcribe_rev_ai(temp_rec_file_name)
        s3_dir_name = f'{email}_{session_id}'
        upload_transcription(s3_dir_name, trans_results, temp_rec_file_name)
    except Exception as ex:
        os.remove(temp_rec_file_name)
        print(f'Error while processing request [{ex}]')
        return "General error. We're about to fire someone.", 500

    os.remove(temp_rec_file_name)
    send_email(email, session_id)
    print(f'Finished processing request for {email}')
    return 'OK'
Ejemplo n.º 28
0
def check_spots():
    if courses:
        for course in courses:
            try:
                if is_course_available(course):
                    for student in course.students:
                        send_email(student, course, 'notification')
                    remove_course(course)
                    courses.remove(course)
            except RequestException:
                logging.error('Error when connecting to SSC', exc_info=True)
            except (gaierror, ConnectionRefusedError):
                logging.error(
                    'Failed to connect to the server. Bad connection settings?',
                    exc_info=True)
            except smtplib.SMTPServerDisconnected:
                logging.error('Failed to connect to the server.',
                              exc_info=True)
            except smtplib.SMTPException:
                logging.error('SMTP error', exc_info=True)
            except Exception as e:
                logging.error('Error occurred while checking courses',
                              exc_info=True)
Ejemplo n.º 29
0
Archivo: app.py Proyecto: g4mp3a/sink
def success():
    #global file
    if request.method == 'POST':
        email = request.form["name_email"]
        height = request.form["name_height"]
        """
        file = request.files["file"]
        file.save(secure_filename("uploaded_" + file.filename))

        with open("uploaded_" + file.filename, "a") as f:
            f.write("Newly added lines...\nAnother one.")
        """
        if db.session.query(Height).filter(
                Height._email == email).count() == 0:
            data = Height(email, height)
            db.session.add(data)
            db.session.commit()
            avg_ht = round(
                db.session.query(func.avg(Height._height)).scalar()
            )  # ,1 to round to 1 decimal place
            send_email(email, height, avg_ht)
            return render_template("success.html")
        return render_template(
            "index.html", text="We have surveyed that email address already!")
Ejemplo n.º 30
0
def notify_user(job_title, database_file_name, elution_file_name,
                flowthrough_file_name, el_peptides_file_name,
                ft_peptides_file_name, digestion_enzyme, enrichment_threshold,
                run_number, email):
    job_name = f'Job title: {job_title}\n' if job_title else ''
    notification_content = f'Your submission details are:\n\n{job_name}BCR-Seq dataset: {database_file_name}\n'

    if el_peptides_file_name != None:
        notification_content += f'Elution peptides list: {el_peptides_file_name}\nFlow-through peptides list: {ft_peptides_file_name}'
    else:
        notification_content += f'Elution raw dataset: {elution_file_name}\nFlow-through raw dataset: {flowthrough_file_name}\n'

    notification_content += f'Digestion enzyme: {digestion_enzyme}\nMin enrichment ratio: {enrichment_threshold}\n\n'

    notification_content += f'Once the analysis will be ready, we will let you know! Meanwhile, you can track the ' \
        f'progress of your job at:\n{CONSTS.WEBSERVER_URL}/results/{run_number}/{CONSTS.RESULT_WEBPAGE_NAME}\n\n'

    send_email(
        smtp_server=CONSTS.SMTP_SERVER,
        sender=CONSTS.ADMIN_EMAIL,
        receiver=f'{email}',
        subject=
        f'{CONSTS.WEBSERVER_NAME.upper()} - your job has been submitted! (Run number: {run_number})',
        content=notification_content)
Ejemplo n.º 31
0
from webapp import create_app
from async.email_sender import send_email

if __name__ == '__main__':
    app = create_app('dummy')
    app.app_context().push()
    send_email(recipients=['*****@*****.**'],
               template='email/new_user.html',
               template_ctx={"subject": "New user",
                             "user_password": "******"},
               subject="Welcome to Opinew")
Ejemplo n.º 32
0
 def send(self, reason):
     send_email(self.username, self.password, reason=reason)
Ejemplo n.º 33
0
def send_email(*args, **kwargs):
    from async.email_sender import send_email

    send_email(*args, **kwargs)