def send_mail_with_template(recipients: list, subject, content_text, logo_src=None, logo_text=None, logo_href=None, title_text=None, greeting=None, greeting_name=None, button_href=None, button_text=None, content_end_text=None, footer_text=None, template=None, attachments=None, cc=None, bcc=None, body=None, sender=None): """ :param recipients: recipient mail addresses. List of strings :param subject: subject of the mail. Passed to Message instance :param logo_src: url of logo passed to template, default : logo located in SiteAyarlari or Zopsedu logo :param logo_text: logo text located under the logo, passed to template. :param logo_href: href value passed to both logo_text and logo_url :param title_text: title text passed to template :param greeting: greeting for the greeting name, passed to template :param greeting_name: greeting name, passed to the template :param content_text: content text, passed to the template :param button_href: href value of button, passed to the template :param button_text: text value of button, passed to the template :param content_end_text: content end text, passed to the template :param footer_text: footer text passed to template :param template: template name for the send mail. Gets used for rendering the mail. :param attachments: A list of Attachment instances, gets added to the Message instance :param cc: CC mail addresses. List of strings :param bcc: BCC mail addresses. List of strings :param body: Plain text value for body of mail. Passed to Message instance :param sender: Sender mail address of mail. default: default sender mail address set while initiating mail instance :return: returns rendered template html """ ayarlar = DB.session.query(SiteAyarlari).filter_by( universite_id=SessionHandler.universite_id()).first() genel_ayarlar = None if ayarlar and ayarlar.params and ayarlar.params[ "site_ayarlari"] and ayarlar.params["site_ayarlari"]["genel"]: genel_ayarlar = ayarlar.params["site_ayarlari"]["genel"] if not logo_src: if ayarlar and ayarlar.logo and genel_ayarlar: logo_src = "{}{}".format(genel_ayarlar["site_adi"], ayarlar.logo.url) logo_href = genel_ayarlar["site_adi"] else: logo_src = 'http://v2.zopsedu.net/static/assets/img/brand-logo2-white.png' if template is None: # sablon tipi 52 email sablonunu isaret eder. degistirilmemelidir. guncel_email_sablonu = DB.session.query(Sablon).filter( Sablon.kullanilabilir_mi == True, Sablon.sablon_tipi_id == 52).order_by(desc( Sablon.updated_at)).first() template = guncel_email_sablonu.sablon_text if not footer_text and genel_ayarlar: footer_text = """ <strong>Telefon: {}</strong><br> <strong>Faks: {}</strong><br> <strong>Adres: {}</strong><br> """.format(genel_ayarlar.get("telefon", "-"), genel_ayarlar.get("faks", "-"), genel_ayarlar.get("adres", "-")) html = render_template_string( template, logo_src=logo_src, logo_text=logo_text, logo_href=logo_href, title_text=title_text if title_text else subject, greeting=greeting, greeting_name=greeting_name, content_text=content_text, button_href=button_href, button_text=button_text, content_end_text=content_end_text, footer_text=footer_text, ) msg = Message(recipients=recipients, attachments=attachments, cc=cc, bcc=bcc, body=body, sender=sender, subject=subject) msg.html = html current_app.extensions['mail'].send(msg) return html
def tickets_reserve(user_id=None): pts = PriceTier.query.join(Product, ProductGroup) \ .order_by(ProductGroup.name, Product.display_name, Product.id).all() if user_id is None: form = TicketsNewUserForm() user = None new_user = True else: form = TicketsForm() user = User.query.get_or_404(user_id) new_user = False if request.method != 'POST': for pt in pts: form.price_tiers.append_entry() form.price_tiers[-1].tier_id.data = pt.id pts = {pt.id: pt for pt in pts} for f in form.price_tiers: f._tier = pts[f.tier_id.data] # TODO: apply per-user limits values = range(f._tier.personal_limit + 1) f.amount.values = values f._any = any(values) if form.validate_on_submit(): if new_user: email, name = form.email.data, form.name.data if not name: name = email app.logger.info('Creating new user with email %s and name %s', email, name) user = User(email, name) flash('Created account for %s' % name) db.session.add(user) currency = form.currency.data if currency: basket = Basket(user, currency) else: basket = Basket(user, 'GBP') for f in form.price_tiers: if f.amount.data: basket[f._tier] = f.amount.data app.logger.info('Admin basket for %s %s', user.email, basket) try: basket.create_purchases() basket.ensure_purchase_capacity() db.session.commit() except CapacityException as e: db.session.rollback() app.logger.warn('Limit exceeded creating admin tickets: %s', e) return redirect(url_for('.tickets_reserve', user_id=user_id)) code = user.login_code(app.config['SECRET_KEY']) msg = Message('Your reserved tickets to EMF', sender=app.config['TICKETS_EMAIL'], recipients=[user.email]) msg.body = render_template('emails/tickets-reserved.txt', user=user, code=code, tickets=basket.purchases, new_user=new_user, currency=currency) mail.send(msg) db.session.commit() flash('Reserved tickets and emailed {}'.format(user.email)) return redirect(url_for('.tickets_reserve')) if new_user: users = User.query.order_by(User.id).all() else: users = None return render_template('admin/tickets/tickets-reserve.html', form=form, pts=pts, user=user, users=users)
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 Thread(target=send_async_email, args=(app, msg)).start()
def mail_message(subject, template, to, **kwargs): sender_email = '*****@*****.**' email = Message(subject, sender=sender_email, recipients=[to]) email.body = render_template(template + ".txt", **kwargs) email.html = render_template(template + ".html", **kwargs) mail.send(email)
container = Container(container_path) # 初始化算法容器 algofunc = container.algorithm_contained(modelname='reshape', algoname='reshape') # 根据算法函数名获取函数对象,这里使用的测试算法函数是reshape模块的reshape算法函数 algofunc(filedir, resultdir) # 调用算法函数 # 2.3. 将处理结果的路径转换为url形式,保存在数据库Post表的resultdir字段中,并标记该任务已经处理完成 resulturl = 'img'+'/'+str(post.id)+'/'+'result.jpg' # 附注: 视频处理结果统一命名为result.mp4 post.resultdir = resulturl post.state = 1 # 更改任务状态标记,表示任务已经处理完成 db.session.commit() # 2.5. 向用户发送邮件,表示任务已经完成 with app.app_context(): # 需要特别注意flask_email扩展中,发送邮件需要使用flask应用程序上下文 message = Message("任务处理完成通知", sender="*****@*****.**", recipients=[post.author.email]) message.body = "您好,您提交的任务(任务描述:"+post.body+")已经处理完成,处理结果请参见附件,也可以到网站主页上下载" # 邮件正文 with app.open_resource(resultdir) as fp: message.attach("image.jpg", "image/jpg", fp.read()) # 处理结果作为附件加入邮件中 mail.send(message) # 发送邮件
def send_mail(): msg = Message("Hello, zhangw",recipients=['*****@*****.**']) msg.body = "哈哈哈" msg.html = render_template("mail.html") # 可以自己选人模板 发送 mail.send(msg) return "邮件发送成功"
def register(): con=sqlite3.connect("user_database.db") conn=con.cursor() res=conn.execute('''SELECT * FROM COUPLES WHERE LOG=1 ''') k=res.fetchone() if k!=None: conn.execute('''UPDATE COUPLES SET LOG=0''') con.commit() form=RegisterForm(request.form) if request.method=='POST' and form.validate(): name1=form.name1.data screen1=form.screen1.data email1=form.email1.data age1=form.age1.data interest1=form.interest1.data name2=form.name2.data screen2=form.screen2.data email2=form.email2.data age2=form.age2.data interest2=form.interest2.data password=sha256_crypt.encrypt(str(form.password.data)) validated1=0 validated2=0 image='images/default.jpeg' if email1==email2: flash('Emails Cannot Be Same') return render_template('register.html',form=form) con=sqlite3.connect("user_database.db") conn=con.cursor() res=conn.execute('''SELECT * FROM COUPLES WHERE EMAIL1=?;''',(email1,)) k=res.fetchone() if k != None: flash('Email Already Exists') return render_template('register.html',form=form) res=conn.execute('''SELECT * FROM COUPLES WHERE EMAIL2=?;''',(email2,)) k=res.fetchone() if k != None: flash('Email Already Exists') return render_template('register.html',form=form) res=conn.execute('''SELECT * FROM COUPLES WHERE EMAIL1=?;''',(email2,)) k=res.fetchone() if k != None: flash('Email Already Exists') return render_template('register.html',form=form) res=conn.execute('''SELECT * FROM COUPLES WHERE EMAIL2=?;''',(email1,)) k=res.fetchone() if k != None: flash('Email Already Exists') return render_template('register.html',form=form) conn.execute("INSERT INTO COUPLES (NAME1, SCREEN1, EMAIL1, AGE1, INTEREST1, NAME2, SCREEN2, EMAIL2, AGE2, INTEREST2, PASSWORD, VALIDATED1,VALIDATED2,LOG,IMAGE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (name1,screen1,email1,age1,interest1,name2,screen2,email2,age2,interest2,password,validated1,validated2,validated2,image)) con.commit() msg = Message("Couple Dal confirmation mail", sender="*****@*****.**", recipients=[email1]) link=url_for('confirmation1',email=email1,w=1,_external=True) msg.body="Click on the given link to confirm your account {}".format(link) mail.send(msg) msg = Message("Couple Dal confirmation mail", sender="*****@*****.**", recipients=[email2]) link=url_for('confirmation1',email=email2,w=2,_external=True) msg.body="Click on the given link to confirm your account {}".format(link) mail.send(msg) return redirect(url_for('succesFullRegister')) return render_template('register.html',form=form)
def notify(agency, login, checksum, type, TIMESTAMP): errorLog("final_email routine:") timestamp_date = datetime.datetime.fromtimestamp( int(TIMESTAMP)).strftime('%Y-%m-%d %H:%M:%S') errorLog(TIMESTAMP) required_tables_dict = { 'algae': ['tbl_algae'], 'channelengineering': ['tbl_channelengineering'], 'hydromod': ['tbl_hydromod'], 'siteevaluation': ['tbl_siteeval'], 'taxonomy': ['tbl_taxonomysampleinfo', 'tbl_taxonomyresults'], 'chemistry': ['tbl_chemistrybatch', 'tbl_chemistryresults'], 'toxicity': ['tbl_toxicitybatch', 'tbl_toxicityresults', 'tbl_toxicitysummary'], 'hydromod': ['tbl_hydromod'] } message_body = "SCCWRP has received a successful %s submission from %s for %s. For future - the user submitted [row count] and [row count] were successfully entered into the database." % ( str(type), str(login), str(agency)) # use report to build message body of email if type in required_tables_dict: errorLog(required_tables_dict[type]) eng = create_engine( 'postgresql://*****:*****@192.168.1.17:5432/smc') message_body = "SCCWRP has received a successful %s submission from %s for %s: SubmissionID - %s\r\n" % ( str(type), str(login), str(agency), str(TIMESTAMP)) for v in required_tables_dict[type]: errorLog(v) table_name = str(v) table = "\r\n ---- %s ----\r\n" % table_name total = "" group_list = "" # checksum on submitted data vs received sql_total = "select count(*) from %s where created_date = '%s'" % ( table_name, str(timestamp_date)) errorLog(sql_total) sql_total_results = eng.execute(sql_total) for s in sql_total_results: errorLog(s.count) total = total + "\t checksum - total submitted: " + str( checksum[table_name]) + ", total received: " + str(s.count) sql_group = "select created_date,count(*) from %s where login_agency = '%s' group by created_date" % ( table_name, str(agency)) errorLog(sql_group) sql_group_results = eng.execute(sql_group) for s in sql_group_results: errorLog(s) group_list = group_list + "\r\n\t submisssions - \r\n\t\t date -- records \r\n\t\t " + str( s.created_date) + " -- " + str(s.count) + "\r\n" errorLog(group_list) message_body = message_body + str(table) + str( total) + " - " + str(group_list) + "\r\n" # report code location - not used yet in smc #if report_link: # report_url = '\r\n ---- Click here for a link to your report: %s ----' % report_link #else: report_url = "" message_body = message_body + str(report_url) errorLog(message_body) eng.dispose() mail = Mail(current_app) if type == "algae": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) if type == "channelengineering": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) elif type == "chemistry": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) elif type == "hydromod": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) elif type == "siteevaluation": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) elif type == "taxonomy": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) elif type == "toxicity": msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) else: msg = Message("%s smc - successful data load" % (str(type)), sender="*****@*****.**", recipients=["*****@*****.**", "%s" % str(login)]) msg.body = message_body mail.send(msg) return "success"
def send_email(subject, sender, recipients, text_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body # msg.html = html_body mail.send(msg)
def send_async_email(subject, recipient, text_body, html_body): """Sends an Email""" msg = Message(subject=subject, recipients=[recipient]) msg.body = text_body msg.html = html_body
def addpayment(): if 'loggedin' in session: if session['is_retailer'] == 1: if request.method == 'POST': purchase_id = request.form['purchase_id'] amountpaid = request.form['amount_paid'] payment_date = request.form['payment_date'] cursor = mysql.connection.cursor() cursor.execute( "INSERT INTO Payments(purchase_id, amount_paid, payment_date) VALUES(% s,% s,% s)", [purchase_id, amountpaid, payment_date]) cursor.execute( "UPDATE Purchase SET amount_paid=amount_paid + % s WHERE purchase_id = % s", [amountpaid, purchase_id]) mysql.connection.commit() cursor.execute( "SELECT item_name, price, amount_paid, user_id, purchase_date FROM Purchase WHERE purchase_id = %s", [purchase_id]) details = cursor.fetchone() print(details) item = details[0] price = details[1] tot_amount_paid = details[2] userid = details[3] purchase_date = details[4] cursor.execute( "SELECT email, username FROM Users WHERE user_id = %s", [userid]) user = cursor.fetchone() print(user) recipient = user[0] username = user[1] pending_amount = price - tot_amount_paid msg = Message('Payment Detail', sender=config.email, recipients=[recipient]) msg.body = f''' Hey {username}, we hope you are doing well. You made a payment on {payment_date} for the purchase item - {item} purchased on {purchase_date}. Please pay the balance pending payments as soon as possible. If you paid all the payments, then leave it. Payment Details: Item : {item} Amount Paid : {amountpaid} Payment Date : {payment_date} Pending Payment Details : Item : {item} Price : {price} Purchase Date : {purchase_date} Amount Paid : {tot_amount_paid} Pending Amount : {pending_amount} Thankyou. ''' mail.send(msg) return redirect(url_for('home')) return render_template('addpayment.html') else: return redirect(url_for('intro'))
def send(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body Thread(target=_send_async, args=(current_app._get_current_object(), msg)).start()
def variant_verification( store, institute_id, case_name, variant_id, sender, variant_url, order, comment, url_builder=None, mail=None, user_obj=None, ): """Sand a verification email and register the verification in the database Args: store(scout.adapter.MongoAdapter) institute_obj(dict): an institute object case_obj(dict): a case object user_obj(dict): a user object variant_obj(dict): a variant object (snv or sv) sender(str): current_app.config['MAIL_USERNAME'] variant_url(str): the complete url to the variant (snv or sv), a link that works from outside scout domain. order(str): False == cancel order, True==order verification comment(str): sender's entered comment from form url_builder(flask.url_for): for testing purposes, otherwise test verification email fails because out of context """ url_builder = url_builder or url_for mail = mail or ex_mail user_obj = user_obj or store.user(current_user.email) data = variant_controller( store, institute_id, case_name, variant_id=variant_id, add_case=True, add_other=False, get_overlapping=False, add_compounds=False, ) variant_obj = data["variant"] case_obj = data["case"] institute_obj = data["institute"] pp(variant_obj) recipients = institute_obj["sanger_recipients"] if len(recipients) == 0: raise MissingVerificationRecipientError() view_type = None email_subject = None category = variant_obj.get("category", "snv") display_name = variant_obj.get("display_name") chromosome = variant_obj["chromosome"] end_chrom = variant_obj.get("end_chrom", chromosome) breakpoint_1 = ( ":".join([chromosome, str(variant_obj["position"])]) if category in ["sv", "cancer_sv"] else "-" ) breakpoint_2 = ( ":".join([end_chrom, str(variant_obj.get("end"))]) if category in ["sv", "cancer_sv"] else "-" ) variant_size = variant_obj.get("length") panels = ", ".join(variant_obj.get("panels", [])) gene_identifiers = [ str(ident) for ident in variant_obj.get("hgnc_symbols", variant_obj.get("hgnc_ids", [])) ] hgnc_symbol = ", ".join(gene_identifiers) email_subj_gene_symbol = None if len(gene_identifiers) > 3: email_subj_gene_symbol = " ".join([str(len(gene_identifiers)) + "genes"]) else: email_subj_gene_symbol = hgnc_symbol gtcalls = [ "<li>{}: {}</li>".format(sample_obj["display_name"], sample_obj["genotype_call"]) for sample_obj in variant_obj["samples"] ] tx_changes = [] if category == "snv": # SNV view_type = "variant.variant" tx_changes = [] for gene_obj in variant_obj.get("genes", []): for tx_obj in gene_obj["transcripts"]: # select refseq transcripts as "primary" if not tx_obj.get("refseq_id"): continue for refseq_id in tx_obj.get("refseq_identifiers"): transcript_line = [] transcript_line.append(gene_obj.get("hgnc_symbol", gene_obj["hgnc_id"])) transcript_line.append("-".join([refseq_id, tx_obj["transcript_id"]])) if "exon" in tx_obj: transcript_line.append("".join(["exon", tx_obj["exon"]])) elif "intron" in tx_obj: transcript_line.append("".join(["intron", tx_obj["intron"]])) else: transcript_line.append("intergenic") if "coding_sequence_name" in tx_obj: transcript_line.append(urllib.parse.unquote(tx_obj["coding_sequence_name"])) else: transcript_line.append("") if "protein_sequence_name" in tx_obj: transcript_line.append( urllib.parse.unquote(tx_obj["protein_sequence_name"]) ) else: transcript_line.append("") tx_changes.append("<li>{}</li>".format(":".join(transcript_line))) else: # SV view_type = "variant.sv_variant" display_name = "_".join([breakpoint_1, variant_obj.get("sub_category").upper()]) # body of the email html = verification_email_body( case_name=case_obj["display_name"], url=variant_url, # this is the complete url to the variant, accessible when clicking on the email link display_name=display_name, category=category.upper(), subcategory=variant_obj.get("sub_category").upper(), breakpoint_1=breakpoint_1, breakpoint_2=breakpoint_2, hgnc_symbol=hgnc_symbol, panels=panels, gtcalls="".join(gtcalls), tx_changes="".join(tx_changes) or "Not available", name=user_obj["name"].encode("utf-8"), comment=comment, ) # build a local the link to the variant to be included in the events objects (variant and case) created in the event collection. local_link = url_builder( view_type, institute_id=institute_obj["_id"], case_name=case_obj["display_name"], variant_id=variant_obj["_id"], ) if order == "True": # variant verification should be ordered # pin variant if it's not already pinned if case_obj.get("suspects") is None or variant_obj["_id"] not in case_obj["suspects"]: store.pin_variant(institute_obj, case_obj, user_obj, local_link, variant_obj) email_subject = "SCOUT: validation of {} variant {}, ({})".format( category.upper(), display_name, email_subj_gene_symbol ) store.order_verification( institute=institute_obj, case=case_obj, user=user_obj, link=local_link, variant=variant_obj, ) else: # variant verification should be cancelled email_subject = "SCOUT: validation of {} variant {}, ({}), was CANCELLED!".format( category.upper(), display_name, email_subj_gene_symbol ) store.cancel_verification( institute=institute_obj, case=case_obj, user=user_obj, link=local_link, variant=variant_obj, ) kwargs = dict( subject=email_subject, html=html, sender=sender, recipients=recipients, # cc the sender of the email for confirmation cc=[user_obj["email"]], ) message = Message(**kwargs) # send email using flask_mail mail.send(message)
def send_mail(to, fro, subject, template_name=None, bcc=None, files=None, msg_body=None, **template_params): bcc = [] if bcc is None else bcc files = [] if files is None else files # ensure that email isn't sent if it is disabled if not app.config.get("ENABLE_EMAIL", False): app.logger.info("Email template {0} called to send, but email has been disabled.\nto:{1}\tsubject:{2}".format(template_name, to, subject)) return assert type(to) == list assert type(files) == list if bcc and not isinstance(bcc, list): bcc = [bcc] to_is_invalid = True for t in to: if t: to_is_invalid = False # a list of None, None, None or even just a [None] is no good! if to_is_invalid: magic = str(uuid.uuid1()) app.logger.error('Bad To list while trying to send email with subject \"{0}\". Magic num for log grep {1}'.format(subject, magic)) flash("Invalid email address - no email specified at all. Trying to send email with subject \"{0}\". Magic number to help identify error: {1}".format(subject, magic), 'error') return if app.config.get('CC_ALL_EMAILS_TO', None) is not None: bcc.append(app.config.get('CC_ALL_EMAILS_TO')) # Get the body text from the msg_body parameter (for a contact form), # or render from a template. # TODO: This could also find and render an HTML template if present if msg_body: plaintext_body = msg_body else: try: plaintext_body = render_template(template_name, **template_params) except: with app.test_request_context(): plaintext_body = render_template(template_name, **template_params) # create a message msg = Message(subject=subject, recipients=to, body=plaintext_body, html=None, sender=fro, cc=None, bcc=bcc, attachments=files, reply_to=None, date=None, charset=None, extra_headers=None ) try: mail = Mail(app) with app.app_context(): mail.send(msg) app.logger.info("Email template {0} sent.\nto:{1}\tsubject:{2}".format(template_name, to, subject)) except Exception as e: raise EmailException(e)
def place_order(customer_username, customer_id, restaurant_id): if request.method == "POST": #if customer not logged in, can't place order if not customer_id: flash("You must be logged in to place an order", "danger") return redirect(url_for('index')) #get various tables needed oiTable = dynamodb.Table('order_item') # pylint: disable=no-member menuTable = dynamodb.Table('menu_item') # pylint: disable=no-member orderTable = dynamodb.Table('order') # pylint: disable=no-member restTable = dynamodb.Table('restaurant') # pylint: disable=no-member custTable = dynamodb.Table('customer') # pylint: disable=no-member # generate order_id order_id = str(uuid.uuid4()) #get order details from front end menu_items = list(request.form.getlist("menu_item_id")) quantites = request.form.getlist('item_quantity') subtotals = request.form.getlist("item_subtotal") #create dict to hold info on order details for each menu item sub_order = {} for i in range(len(menu_items)): sub_order[menu_items[i]] = {'Quantity': int(quantites[i]), "subtotal": float(subtotals[i])} orderSubtotal = 0 orderIdList = [] #check to make sure enough menu items exist for order for key in sub_order: response = menuTable.get_item( Key={'menu_item_id': key} ) #if not enough items for order, displays error message quantAvailable = int(response['Item']['item_quantity_available']) quantRemaining = quantAvailable - sub_order[key]['Quantity'] if quantRemaining < 0: unavailableItem = "We are so sorry, the " + response['Item']['item_name'] + " is unavailable!" flash(unavailableItem, "danger") redirectUrl = 'restaurant.get_restaurant' return redirect(url_for(redirectUrl, restaurant_id = restaurant_id)) #create an order item for each menu item, linking to order for key in sub_order: orderItemId = str(uuid.uuid4()) item = { 'order_id': order_id, 'order_item_id': orderItemId, 'oi_quantity': sub_order[key]['Quantity'], 'oi_unit_price': str(sub_order[key]['subtotal']), 'item_id': key } response = menuTable.get_item( Key={'menu_item_id': key} ) quantAvailable = response['Item']['item_quantity_available'] quantRemaining = str(int(quantAvailable) - int(item['oi_quantity'])) #update quantites of items ordered in database, subtracting items from database that were ordered response = menuTable.update_item( Key={'menu_item_id': key}, UpdateExpression='set item_quantity_available = :val', ExpressionAttributeValues = { ':val': quantRemaining }, ReturnValues = 'UPDATED_NEW' ) #create new order_item with menu item and price newOrderItem = oiTable.put_item( Item=item ) #keep track of order subtotal orderSubtotal = orderSubtotal + sub_order[key]['subtotal'] orderIdList.append(orderItemId) #get the current time and convert it into a string named_tuple = time.localtime() # get struct_time time_string = time.strftime("%Y-%m-%d, %H:%M:%S", named_tuple) #create confirmation number for order confirmation = "".join([random.choice(string.ascii_uppercase + string.digits) for n in range(8)]) order = dict() #restrieve restaurant name, phone number, and zip code response = restTable.get_item( Key={'restaurant_id': restaurant_id} ) restName = response['Item']['restaurant_name'] restPhone = response['Item']['restaurant_phone_num'] restZip = response['Item']['restaurant_postal_code'] #retrieve customer email response = custTable.get_item( Key={'customer_id': customer_id} ) #if somehow user has no email listed, sends error message if 'customer_email' not in response['Item']: flash('Your profile has no email address. Please update your information and try again', 'danger') return redirect(url_for('index')) #get customer email address custEmail = response['Item']['customer_email'] ''' #calculate sales tax for restaurant using zip-tax.com api tax_url = 'https://api.zip-tax.com/request/v40?key=' + tax_api_key + '&postalcode=' + str(restZip) tax_request = requests.get(tax_url) tax_request_content = json.loads(tax_request.content) salesTax = tax_request_content['results'][0]['taxSales'] ''' salesTax = 0.08 #calculate tax for the order orderTax = round((salesTax * orderSubtotal), 2) #calculate order total (subtotal + order tax) orderTotal = str(round(orderTax + orderSubtotal, 2)) #create order object to be stored in database order['order_time'] = time_string order['order_id'] = order_id order['confirmation'] = confirmation order['order_type'] = request.form['order_type'] order['order_fulfilled_time'] = None order['order_status'] = "Submitted" order['customer_id'] = customer_id order['oi_id'] = orderIdList order['restaurant_id'] = restaurant_id order['table_id'] = None order['subtotal'] = str(orderSubtotal) order['tax'] = str(orderTax) order['order_total'] = orderTotal #place order object in database createOrder = orderTable.put_item(Item = order) #create dict with order details to send back to front end to display to user orderDetails = dict( username = customer_username, restName = restName, order_time = order['order_time'], subtotal = orderSubtotal, tax = orderTax, total=orderTotal, confirmation=order['confirmation'], restPhone=restPhone) #create a confirmation url for user to check status of their order confirmation_url = request.url_root + 'order/?confirmation=' + confirmation #using flask_mail, send email to user with order details and a link they can check to see the status of their order from application import mail as mail try: msg = Message("Order Confirmation Email", sender = "*****@*****.**", recipients= [custEmail]) msg.body = 'Hello ' + str(customer_username) + '\nBelow are the details of your recent order from ' + str(restName) + '\n' + 'Order Placed: ' + str(order['order_time']) + '\n' + 'Order Confirmation: ' + str(order['confirmation']) + '\n' + 'Order Subtotal: ' + str(order['order_total']) + '\n' + 'Please call ' + str(restName) + ' at ' + str(restPhone) + ' with any questions or concerns for your order.\n' msg.html = render_template('order_confirmation_email.html', order=orderDetails, confirmation_url=confirmation_url) mail.send(msg) confirmationMessage = "Order was successful. Confirmation email sent to " + custEmail flash(confirmationMessage, "success") except Exception as e: return str(e) return render_template('order.html', customer_username=customer_username, customer_id=customer_id, restaurant_id=restaurant_id, order=orderDetails, confirmation_url=confirmation_url)
def send_email(subject, recipients, text_body, html_body, sender=None): msg = Message(subject, recipients=recipients, sender=sender) msg.body = text_body msg.html = html_body mail.send(msg)
import flask import os from flask_mail import Mail from flask_mail import Message mail = Mail() app = flask.Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.googlemail.com' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = '******'#os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = '******'#os.environ.get('MAIL_PASSWORD') mail.init_app(app) msg = Message('test subject', sender='*****@*****.**', recipients=['*****@*****.**','*****@*****.**']) msg.body = 'text body' msg.html = '<b>HTML</b> body' with app.app_context(): mail.send(msg)
def send_email(subject, email, html): msg = Message(subject, sender=app.config['MAIL_USERNAME'], recipients=[email]) msg.body = html mail.send(msg)
def send_mail(rec, u_name, msg_type): email_cont = [] # Logs alerts and emails to cont_log table def contact_log(recip, message_type): try: c, conn = connection() c.execute("INSERT INTO cont_log (recipient, date_sent, message_type) VALUES (%s, %s, %s)", (thwart(recip), time.strftime("%H:%M:%S %m-%d-%Y"), message_type),) conn.commit() print(f"Message sent to {recip} as {message_type} and logged to db") except Exception as e: if netpop_logging_to_console: app.logger.error(e) c.close() conn.close() gc.collect() def message_type(): if msg_type.lower() == "new_user": msg_subject = "Welcome to Netpops!" msg_html = f'<p>Hey {u_name.capitalize()}!\ <br>\ Welcome to NetPops {u_name.capitalize()}!\ <br>\ Thanks!\ <br>\ NetPop</p>' msg_body = f"Welcome to Netpops and Thanks for registering {u_name.capitalize()}!" msg = [msg_subject, msg_body, msg_html] print("Welcome Email Sent.") return msg elif msg_type.lower() == "reset_password": c, conn = connection() data = c.execute("SELECT * FROM users WHERE username = %s", u_name, ) result = c.fetchone() token = result[11] full_url = f"{netpop_hostname}/reset_password/{token}" msg_subject = "NetPops Password Reset" msg_html = f'<p>Hey {u_name.capitalize()}!\ <br>\ We got a request to reset your password.\ <br>\ <p>Click <a href="{full_url}">HERE</a> to it.\ <br>\ <p>Or open this <strong>{full_url}</strong> in your browser.\ <br>\ <p>If you did not request this password reset, then just ignore this email.\ <br>\ Thanks!\ <br>\ NetPops</p>' msg_body = f"Looks like you're trying to reset your password for {u_name}. \ Go to {full_url} to reset you password. If you did not request \ this password change you can ignore this message." msg = [msg_subject, msg_body, msg_html] return msg elif msg_type.lower() == "password_update_confirm": c, conn = connection() data = c.execute("SELECT * FROM users WHERE username = %s", u_name, ) msg_subject = "NetPops Password Changed" msg_html = f'<p>Hey {u_name.capitalize()}!\ <br>\ Your password was successfully changed!\ <br>\ Thanks!\ <br>\ NetPop</p>' msg_body = "Your password was successfully changed! Thanks!" msg = [msg_subject, msg_body, msg_html] return msg else: if netpop_logging_to_console: app.logger.error(e) email_cont = message_type() try: msg = Message(email_cont[0], sender="*****@*****.**", recipients=[rec,]) msg.body = email_cont[1] msg.html = email_cont[2] mail.send(msg) print("calling contact_log function") contact_log(rec, message_type) print("contact_log function has completed.") except Exception as e: if netpop_logging_to_console: app.logger.error(e)
def email_message(subject, template, to, **kwargs): sender_email = '*****@*****.**' email = Message(subject, sender=sender_email, recipients=[to]) email.body = render_template(template + ".txt", **kwargs) email.html = render_template(template + ".html", **kwargs) mail.send(email)
def send_email(to, subject, template): msg = Message(subject, recipients=[to], html=template, sender=app.config['MAIL_DEFAULT_SENDER']) mail.send(msg)
def create_courier(): empty_fields = [] user_name = request.form['user_name'] arrival_time = request.form['arrivalTime'] contents = request.form['contents'] user_id = request.form['user_id'] hostel = request.form['hostel'] roomNo = request.form['roomNo'] sender_address = request.form['sender_address'] types = request.form['types'] if phone_regex.match(user_id) is None: # return jsonify(success=False, field="user_id") empty_fields.append('user_id') if user_name is "": # return jsonify(success=False, field="user_name") empty_fields.append('user_name') if contents is "": empty_fields.append('contents') if hostel is "": empty_fields.append('hostel') if roomNo is "": empty_fields.append('roomNo') if sender_address is "": empty_fields.append('sender_address') if types is "": empty_fields.append('types') if len(empty_fields) > 0: print(empty_fields) return jsonify(success=False, fields=empty_fields) # user = User.query.filter(User.id == user_id).first() # if user is None: # return jsonify(success=False) courier = Courier(user_id, arrival_time, contents, hostel, roomNo, types, sender_address, user_name) db.session.add(courier) db.session.commit() print(courier.user) try: # courierslist=Courier.query.all() # print(courierslist) msg = Message( "Hello!", sender="*****@*****.**", # recipients=[courierslist[len(courierslist)-1].user.email]) recipients=[courier.user.email]) msg.body = "This mail is to inform you that a courier has arrived for you from " + sender_address + " of type " + types + " having contents as " + contents + "." mail.send(msg) # return redirect('/courier/list') except: pass finally: return jsonify(success=True, courier=courier.to_dict())
def mail_message(subject,template,to,**kwargs): sender_email= "*****@*****.**" email = Message(subject, sender=sender_email, recipients=[to]) email.body = render_template(template + ".txt", **kwargs) email.html = render_template(template + ".html",**kwargs) mail.send(email)
def send_admin_email(subject, template): msg = Message(subject, recipients=['*****@*****.**'] + ['*****@*****.**'], html=template, sender=app.config['MAIL_DEFAULT_SENDER']) mail.send(msg)
def send_email(email: str, subject: str, message: str): config = app.config['PUBLIC_CONFIG'] msg = Message(subject, recipients=[config['support']['contact_email']]) msg.body = 'From: {0} <{0}> {1}'.format(email, message) mail.send(msg)
def doregister(self): ret = {} try: req = request.form url = secrets.token_urlsafe(16) pes = Participant() pes.name = req.get('name') pes.email = req.get('email') pes.affiliation = req.get('affiliation') pes.country_id = req.get('nationality') pes.uniqueURL = url print("ALL GOO1") mariadb.session.add(pes) mariadb.session.flush() print("ALL GOO2") # updateURL upes = Participant.query.get(pes.id) print("ALL GOO3", upes.uniqueURL, pes.id) upes.uniqueURL = upes.uniqueURL + "_" + str(pes.id) print("ALL GOO4") ret['status'] = True print("ALL GOO5") # print('peserta',pes.id, pes.uniqueURL) # traceback.print_exc() # except exc.IntegrityError as err: # print("ERROR 1",err) # mariadb.session.rollback() # ret['status']=False # do send mail print("SENDDING EMAIL") msg = Message(subject='REGISTRATION CONFRIMATION', sender='*****@*****.**', recipients=[upes.email]) data = {} data['name'] = upes.name data['affiliation'] = upes.affiliation country = Countrydb.query.get(upes.country_id) data['country'] = country.nicename msg.body = render_template('register.txt', **data) mail.send(msg) print("COMMITING DB") mariadb.session.commit() except exc.IntegrityError as err: print('integrityError') # print(err.args) if re.match("(.*)Duplicate entry(.*)for key 'email'(.*)", err.args[0]): ret['errors'] = {'email': 'Email Already Registered'} mariadb.session.rollback() ret['status'] = False except Exception as e: ret['status'] = False print("ERROR 3") traceback.print_exc() finally: return jsonify(ret)
def tickets_choose_free(user_id=None): free_pts = PriceTier.query.join(Product).filter( ~PriceTier.prices.any(Price.price_int > 0), ).order_by( Product.name).all() if user_id is None: form = TicketsNewUserForm() user = None new_user = True else: form = TicketsForm() user = User.query.get_or_404(user_id) new_user = False if request.method != 'POST': for pt in free_pts: form.price_tiers.append_entry() form.price_tiers[-1].tier_id.data = pt.id pts = {pt.id: pt for pt in free_pts} for f in form.price_tiers: f._tier = pts[f.tier_id.data] values = range(f._tier.personal_limit + 1) f.amount.values = values f._any = any(values) if form.validate_on_submit(): if not any(f.amount.data for f in form.price_tiers): flash('Please choose some tickets to allocate') return redirect(url_for('.tickets_choose_free', user_id=user_id)) if new_user: app.logger.info('Creating new user with email %s and name %s', form.email.data, form.name.data) user = User(form.email.data, form.name.data) db.session.add(user) flash('Created account for %s' % form.email.data) basket = Basket(user, 'GBP') for f in form.price_tiers: if f.amount.data: basket[f._tier] = f.amount.data app.logger.info('Admin basket for %s %s', user.email, basket) try: basket.create_purchases() basket.ensure_purchase_capacity() assert basket.total == 0 except CapacityException as e: db.session.rollback() app.logger.warn('Limit exceeded creating admin tickets: %s', e) return redirect(url_for('.tickets_choose_free', user_id=user_id)) for p in basket.purchases: p.set_state('paid') app.logger.info('Allocated %s tickets to user', len(basket.purchases)) db.session.commit() code = user.login_code(app.config['SECRET_KEY']) msg = Message('Your complimentary tickets to EMF', sender=app.config['TICKETS_EMAIL'], recipients=[user.email]) msg.body = render_template('emails/tickets-free.txt', user=user, code=code, tickets=basket.purchases, new_user=new_user) if feature_enabled('ISSUE_TICKETS'): attach_tickets(msg, user) mail.send(msg) db.session.commit() flash('Allocated %s ticket(s)' % len(basket.purchases)) return redirect(url_for('.tickets_choose_free')) if new_user: users = User.query.order_by(User.id).all() else: users = None return render_template('admin/tickets/tickets-choose-free.html', form=form, user=user, users=users)
def register(): msg = '' # Check if "username" and "password" POST requests exist (user submitted form) if register.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form: username = request.form['username'] password = request.form['password'] email = request.form['email'] # Check if account exists using MySQL cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute('SELECT * FROM accounts WHERE username = %s', (username)) account = cursor.fetchone() # If account exists show error and validation checks if account: msg = '이미 등록한 회원입니다!' elif not re.match(r'[^@]+@[^@]+\.[^@]+', email): msg = '유효하지 않은 이메일 주소입니다!' elif not re.match(r'[A-Za-z0-9]+', username): msg = '아이디는 숫자와 문자로만 이루어져야합니다!' elif not username or not password or not email: msg = '입력 칸을 채워주세요!' elif account_activation_required: # Account activation enabled # Generate a random unique id for activation code activation_code = uuid.uuid4() # Scrypt password hashing and random salt generation salt = generate_random_salt() password_hash = generate_password_hash(password, salt) cursor.execute( 'INSERT INTO accounts VALUES (NULL, %s, %s, %s, %s, %s,"")', (username, password_hash, salt, email, activation_code)) mysql.connection.commit() email = Message('Account Activation Required', sender='*****@*****.**', recipients=[email]) activate_link = 'http://localhost:5000/pythonlogin/activate/' + str( email) + '/' + str(activation_code) email.body = '<p>아래 링크를 클릭하여 이메일을 인증하세요: <a hredf="' + str( activate_link) + '">' + str(activate_link) + '</a></p>' mail.send(email) return '이메일이 발송되었습니다. 계정을 활성화하려면 이메일을 인증하세요!' else: # Account doesn't exist and the form data is valid. Insert new Account cursor.execute('INSERT INTO accounts VALUES (NULL, %s, %s, %s)', (username, password, email)) mysql.connection.commit() msg = '회원 등록 성공!' cursor.close() mysql.connection.close() elif request.method == 'POST': # Form is empty msg = '회원 등록 정보를 입력해주세요' return render_template('register.html', msg=msg)
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 send_async_email(app,msg)
def predict(): print("I was here 1") if request.method == 'POST': print(request.form.get('age')) try: age = float(request.form['age']) income = float(request.form['income']) Gender = float(request.form['Gender']) MaritalStatus = float(request.form['MaritalStatus']) HaveKids = float(request.form['HaveKids']) isVeg = float(request.form['isVeg']) IsStudent = float(request.form['IsStudent']) email= request.form['email'] offer_received = 0 pred_args = [age, income, Gender,MaritalStatus,HaveKids,isVeg,IsStudent] pred_args_arr = np.array(pred_args) pred_args_arr = pred_args_arr.reshape(1, -1) # mul_reg = open("multiple_regression_model.pkl", "rb") # ml_model = joblib.load(mul_reg) model_prediction = ml_model.predict(pred_args_arr) model_prediction = round(float(model_prediction), 2) cred = service_account.Credentials.from_service_account_file( 'subway_cred.json') # Setting up the Configuration Variables: project_id = "subwayoffers" bucket_name = "bucket_subway" topic_name = "subwaytopic" subscription_name = "subwayoffers" dataset_name = "data" table_name = "Profile" publisher = pubsub_v1.PublisherClient(credentials=cred) client = pubsub_v1.PublisherClient(credentials=cred) topic_path = publisher.topic_path(project_id, topic_name) print(topic_path) subscriber = pubsub_v1.SubscriberClient(credentials=cred) topic_path = subscriber.topic_path(project_id, topic_name) subscription_path = subscriber.subscription_path(project_id, subscription_name) model_prediction_dict='dict' if isVeg==0: model_prediction_dict = "Free Subway Chicken Sandwich" elif HaveKids==1: model_prediction_dict = "40% on Happy Meal" else: model_prediction_dict = "30 % of on any Subway Sandwich" if model_prediction==1 : offer_received='1' model_prediction = 0 msg = Message(subject="Subway offers", sender=app.config.get("MAIL_USERNAME"), recipients=[email], # replace with your email for testing body="Thank you for taking this survey. Your offer is "+str(model_prediction_dict)) print(str(model_prediction)) mail.send(msg) else: msg = Message(subject="Subway offers", sender=app.config.get("MAIL_USERNAME"), recipients=[email], # replace with your email for testing body="Thank you for taking this survey. You have earned a cookie") mail.send(msg) #print(str(model_prediction)) model_prediction=0 data_row = {"age": age, "income": income, "Gender": Gender, "MaritalStatus": MaritalStatus, "HaveKids": HaveKids, "isVeg": isVeg, "IsStudent": IsStudent, "offer_received": offer_received, "offer_completed": model_prediction, "email": email} # print(data_row) message_data = json.dumps(data_row) message_data = message_data.encode('utf-8') print(message_data) # Publishing a message on the PubSub Topic Created: response = publisher.publish(topic_path, message_data, origin='python-sample') print(response) except ValueError: return "Please check if the values are entered correctly" return render_template('predict.html', prediction = model_prediction)