def send_database(): msg = Message('Database Change', sender = '*****@*****.**', recipients = ['*****@*****.**']) msg.body = "Find the updated database below" fp = app.open_resource("site.db") msg.attach('site.db','database/db',fp.read()) fp.close() mail.send(msg)
def send_record(): msg = Message('Record of the month', sender = '*****@*****.**', recipients = ['*****@*****.**']) msg.body = "Find the updated record below" fp = app.open_resource("record.csv") msg.attach('record.csv','record/csv',fp.read()) fp.close() mail.send(msg)
def subscribe(): """ Subscribes an user and sends an email. Request Example: POST { email : 'email address' } """ data = request.get_json(force=True) email = data.get('email', None) criterion = [email, len(data) == 1] if not all(criterion): return make_response('Bad Request', 400) found = User.query.filter_by(email=email).first() if found is None: # Create email and send it msg = Message('Welcome to ChartBulls!', recipients=[email]) msg.html = render_template('email_templates/subscribed.html') mail.send(msg) # Add new user user = User(email) db.session.add(user) db.session.commit() return make_response(str(user.id), 201) else: return make_response('Duplicate', 400)
def post(self): url = "http://optical.cs.ucdavis.edu/" # url = "http://*****:*****@gmail.com', recipients=[email]) msg.body = ( "Hey Fort Nitta user,\n\n" + " To verify your account, please visit the following link:\n " + url + "#home/verifyemail?" + "user="******"&tok=" + hash_token + "\n\nAll the best,\n" + "Fort Nitta Team,\n" + url) mail.send(msg) return jsonify(**{'success': True}) return jsonify(**{'success': False}), 401 return jsonify(**{'success': False}), 401
def sendEmail(PK, intervalID, intervalInSecs): with app.app_context(): queryObject = User.query.join( Settings, User.id == Settings.user_id).join( ChatMessages, Settings.user_id == ChatMessages.to_user).filter( and_(Settings.n_hour == intervalID, ChatMessages.id > PK)).all() maxPK = db.session.query(db.func.max(ChatMessages.id)).scalar() url = "http://optical.cs.ucdavis.edu" # url = "http://*****:*****@gmail.com', recipients=emailArray) msg.body = ("Hey Fort Nitta user,\n\n" + " You have new unread messages waiting!\n " + " Visit Fort Nitta now to check!\n " + "\n\nAll the best,\n" + "Fort Nitta Team,\n" + url) mail.send(msg) threading.Timer( intervalInSecs, lambda: sendEmail(maxPK, intervalID, intervalInSecs)).start()
def send_reset_email(user): token = user.get_reset_token() msg = Message('Password Reset Request', sender=os.environ['MAIL_USERNAME'], recipients=[user.email]) msg.body = f'''To reset your password, kindly visit: {url_for('users.reset', token=token, _external=True)} Kindly ignore this email if you did not make this request''' mail.send(msg)
def send_mail(data): template, body = get_mail_template(data) msg = Message(body, sender=settings.MAIL_USERNAME, recipients=[data[0].get('email', {})]) msg.body = render_template(template, data=data) msg.html = msg.body mail.send(msg) return True
def sendMessage(msg): SEND_EMAIL = os.environ.get('SEND_EMAIL') if SEND_EMAIL=='no': print("no email sent") else: try: mail.send(msg) except: print("message could not be sent") print(msg)
def send_reset_email(user): token = user.get_reset_token() msg = Message("Password Reset Request", sender="*****@*****.**", recipients=[user.email]) msg.body = f"""To reset your password, visit the following link: {url_for('reset_token', token=token, _external=True)} If you did not make this request then simply ignore this email and no changes will be made. """ mail.send(msg)
def send_credential(user,form): msg = Message('Account Creation Success', sender='*****@*****.**', recipients=[user.email]) msg.body = f''' Your Credentials: Email ID: {user.email} Username: {user.username} Password: {form.password.data} ''' mail.send(msg)
def add_company_user(): request_json = request.get_json() auth_token = request_json['auth_token'] user = User.verify_auth_token(auth_token) if user is None: return json.dumps({ 'status': 0, 'error': "Session expired. Please login again." }) elif not user.isMaster: return json.dumps({'status': 0, 'error': "Access Denied"}) company_id = request_json['company_id'] company = Company.query.filter_by(id=company_id).first() name = request_json['name'] designation = request_json['designation'] email = request_json['email'] random_password = ''.join( random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation, k=8)) msg = Message("Welcome to Helpify Corporate", sender="*****@*****.**", recipients=[email], body=f""" Hi {name}, Thanks for your interest in working with us over the upcoming event! We have created a user account for you under the company {company.name}. You may log in by going to {current_app.config['CURRENT_URL']}. Your username is the email address on which you received this email, and your password is: {random_password} Please feel free to contact us in case of any queries. We look forward towards meeting you at the event! Regards, Helpify Corporate Team (on behalf of the event organizers) """) mail.send(msg) hashed_pwd = bcrypt.generate_password_hash(random_password).decode('utf-8') new_user = User(name=name, email=email, password=hashed_pwd, isAdmin=True, company_id=company.id, designation=designation) db.session.add(new_user) db.session.commit() return json.dumps({'status': 1})
def send_request_email(req_id): token = req_id.get_request_token() msg = Message('Account Creation Request', sender='*****@*****.**', recipients=['*****@*****.**']) msg.body = f''' A person with email id {req_id.email} has requested an account. To create an account, visit the following link: {url_for('register', token=token, _external=True)} If you do not want this request to complete then simply ignore this email and no changes will be made. ''' mail.send(msg)
def contact(): form= ContactForm() if form.validate_on_submit(): msg = Message('Contact Request', sender='*****@*****.**', recipients=['*****@*****.**']) msg.body = f''' {form.name.data} (email id: {form.email.data}) has contacted you with message: __MESSAGE START__ {form.content.data} __MESSAGE END__ ''' mail.send(msg) return render_template('contact.html',title='Contact Us', form=form)
def stream(): all_ss = SearchStream.query.filter_by(status=True) num_adds = 0 num_stream_sends = 0 for ss in all_ss: map_received = { 'q': ss.q, 'center': ss.center, 'location': ss.location, 'media_type': ss.media_type, 'photographer': ss.photographer, 'keywords': ",".join([Keyword.query.filter_by(id=x.kw_id).first().name for x in SearchKeywordRel.query.filter_by(ss_id=ss.id)]) } if not ss.first_time: ss.first_time = False else: curr_user = ss.user_id map_to_send = {} for each in map_received: if map_received[each] != '': map_to_send[each] = map_received[each] query = requests.get(current_app.config['BASE_URL'] + current_app.config['SEARCH_URL'], params=map_to_send) result = query.json() received_res = result['collection']['items'] ##storing search results until all are accumulated num_p_extra = result['collection']['metadata'][ 'total_hits'] // 100 ##number of more pages to load data from for i in range(2, num_p_extra + 2): map_to_send['page'] = i query = requests.get(current_app.config['BASE_URL'] + current_app.config['SEARCH_URL'], params=map_to_send) result = query.json() received_res += result['collection']['items'] new_adds = [] for each in received_res: if (StreamResult.query.filter_by(nasa_id=each['data'][0]['nasa_id'])).first() is None: new_res = StreamResult( name=each['data'][0]['title'], center=each['data'][0]['center'] if each['data'][0].get('center') is not None else "No Center Information Provided", last_updated=datetime.strptime(each['data'][0]['date_created'], "%Y-%m-%dT%H:%M:%SZ"), thumb_img=([x['href'] for x in each['links'] if x.get('render') is not None and x['render'] == "image"][0]) if each.get('links') is not None else "", description=((each['data'][0]['description']) if len(each['data'][0]['description']) <= 16383 else each['data'][0]['description'][:16379] + "...") if each['data'][0].get('description') is not None else "", nasa_id=each['data'][0]['nasa_id'] ) new_adds.append(new_res) new_add_str = "\n".join( [(current_app.config['CURRENT_URL'] + current_app.config['IMG_URL'] + str(x.id)) for x in new_adds] ) num_adds += len(new_adds) if len(new_adds) != 0: num_stream_sends += 1 msg = Message('Investoreal Login Credentials', sender='*****@*****.**', recipients=[curr_user.email]) msg.body = f'''Hi {curr_user.name}, New images matching your query were recently added by NASA. Below-mentioned are links to the images that were added. {new_add_str} Cheers, Spindler Team''' mail.send(msg) for ss in all_ss: map_received = { 'q': ss.q, 'center': ss.center, 'location': ss.location, 'media_type': ss.media_type, 'photographer': ss.photographer, 'keywords': ",".join([Keyword.query.filter_by(id=x.kw_id).first().name for x in SearchKeywordRel.query.filter_by(ss_id=ss.id)]) } map_to_send = {} for each in map_received: if map_received[each] != '': map_to_send[each] = map_received[each] query = requests.get(current_app.config['BASE_URL'] + current_app.config['SEARCH_URL'], params=map_to_send) result = query.json() received_res = result['collection']['items'] ##storing search results until all are accumulated num_p_extra = result['collection']['metadata'][ 'total_hits'] // 100 ##number of more pages to load data from for i in range(2, num_p_extra + 2): map_to_send['page'] = i query = requests.get(current_app.config['BASE_URL'] + current_app.config['SEARCH_URL'], params=map_to_send) result = query.json() received_res += result['collection']['items'] num_res = 0 for each in received_res: if (StreamResult.query.filter_by(nasa_id=each['data'][0]['nasa_id'])).first() is None: new_res = StreamResult( name=each['data'][0]['title'], center=each['data'][0]['center'] if each['data'][0].get('center') is not None else "No Center Information Provided", last_updated=datetime.strptime(each['data'][0]['date_created'], "%Y-%m-%dT%H:%M:%SZ"), thumb_img=([x['href'] for x in each['links'] if x.get('render') is not None and x['render'] == "image"][0]) if each.get('links') is not None else "", description=((each['data'][0]['description']) if len(each['data'][0]['description']) <= 16383 else each['data'][0]['description'][:16379] + "...") if each['data'][0].get('description') is not None else "", nasa_id=each['data'][0]['nasa_id'] ) db.session.add(new_res) num_res += 1 db.session.commit() return json.dumps({'status': 1, 'num_adds': num_adds, 'num_stream_sends': num_stream_sends})
def add_new_kid(): """Adds a new kid account, links it to the database, and sends them their login credentials Method Type: POST Special Restrictions -------------------- User must be logged in User must be parent JSON Parameters --------------- auth_token : str Token to authorize the request - released when logging in kid_name : str Name of the kid being added kid_email : str Email of the kid being added init_amount : int Amount that needs to be transferred to the kid Returns ------- JSON status : int Tells whether or not did the function work - 1 for success, 0 for failure """ request_json = request.get_json() auth_token = request_json['auth_token'] user = User.verify_auth_token(auth_token) if user is None: return json.dumps({'status': 0, 'error': "User Not Authenticated"}) if not user.isParent: return json.dumps({'status': 0, 'error': "Access Denied"}) kid_name = request_json['kid_name'] kid_email = request_json['kid_email'] init_amount = request_json['init_amount'] # Create a Kid account using Nessie new_account_number = ''.join(random.choices(string.digits, k=16)) new_account_id = add_account(user.customerId, f"Kid Card - {kid_name}", 0, new_account_number) # Initiate a transfer between the parent account and the kid account using Nessie init_money_transfer_status = transfer_money(user.accountId, new_account_id, init_amount) if not init_money_transfer_status: return json.dumps({ 'status': 0, 'error': "The parent account does not have enough money." }) random_password = ''.join( random.choices(string.digits + string.ascii_uppercase, k=8)) hashed_pwd = bcrypt.generate_password_hash(random_password).decode('utf-8') kid_user = User(name=kid_name, email=kid_email, password=hashed_pwd, isParent=False, accountId=new_account_id, parent_id=user.id) db.session.add(kid_user) db.session.commit() msg = Message('KidFin Login Credentials', sender='*****@*****.**', recipients=[kid_user.email]) msg.body = f'''Hi {kid_name}, You have been added by your parent to their account. You may now log in using the credentials listed below: Username: {kid_email} Password: {random_password} Please be sure to keep this email secure. Cheers, KidFin Team''' mail.send(msg) return json.dumps({ 'status': 1, 'message': "Account Created Successfully!" })
def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body mail.send(msg)