def notify(snipe, index): """ Notify this snipe that their course is open""" course = '%s:%s:%s' % (snipe.subject, snipe.course_number, snipe.section) if snipe.user.email: attributes = { 'email': snipe.user.email, 'subject': snipe.subject, 'course_number': snipe.course_number, 'section': snipe.section, } # build the url for prepopulated form url = 'http://sniper.rutgers.io/?%s' % (urllib.urlencode(attributes)) register_url = 'https://sims.rutgers.edu/webreg/editSchedule.htm?login=cas&semesterSelection=92015&indexList=%s' % (index) email_text = 'A course (%s) that you were watching looks open. Its index number is %s. Click the link below to register for it!\n\n %s \n\n If you don\'t get in, visit this URL: \n\n %s \n\n to continue watching it.\n\n Send any feedback to [email protected]' % (course, index, register_url, url) # send out the email message = Message('[Course Sniper](%s) is open' %(course), sender=EMAIL_SENDER) message.body = email_text message.add_recipient(snipe.user.email) message.add_recipient(snipe.user.email) mail.send(message) db.session.delete(snipe) db.session.commit() app.logger.warning('Notified user: %s about snipe %s' % (snipe.user, snipe))
def send_email(to,subject,template,**kwargs): msg = Message(subject,sender='Hatch Intranet <*****@*****.**>',recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) mail.send(msg)
def sendmail(subject, content): msg = Message(sender=current_app.config['CONFIG']['admin']['email_from'], recipients=current_app.config['CONFIG']['admin']['email_to'], subject=subject, body=content ) mail.send(msg)
def endContest(shoe_id): all_tix = [] tickets = Tickets.query.filter_by(kicks_id = shoe_id).all() if tickets: for t in tickets: for k in range(t.num_tickets): all_tix.append(t.user_id) winner_id = random.choice(all_tix) print winner_id kick = Kicks.query.filter_by(id = shoe_id).first() kick.winner_id = winner_id db.session.add(kick) db.session.commit() winner = User.query.filter_by(id = winner_id).first() msg = Message('test subject', sender = ADMINS[0], recipients = ADMINS) msg.body = 'text body' msg.html = '<b>HTML</b> body' mail.send(msg) flash("Contest has ended, winner is " +str(winner_id)) return redirect(url_for('index')) else: flash('No one has bought tickets') return redirect(url_for('index'))
def post(self): """ Send email """ form = ContactForm() if form.validate(): msg = Message( form.subject.data, sender=MAIL_USERNAME, recipients=[MAIL_USERNAME]) msg.body = """ De: %s <%s> Mensaje: %s """ % (form.name.data, form.email.data, form.message.data) mail.send(msg) message = "" message += "Se envió correctamente la consulta. " message += "Su mensaje sera respondido a la brevedad. ¡Gracias!" flash(message) return redirect(url_for("index", _anchor='contacto')) else: return render_template(self.template_name, form=form, set_tab=3)
def send_activate(user): message = Message(subject='MyLink Activation.', sender='*****@*****.**', recipients=[user.get_email()]) activate_url = url_for('activate_account', uid=user.get_id(), _external=True) message.html = activate_url mail.send(message)
def verify_user(uid): if current_user.is_authenticated: return redirect(url_for('index')) else: form = ResendVerifyFrom() vid = Users.query.filter_by(uid=uid).first() if uid is not 'nouser': if vid: if vid.active is True: flash('User already verified') return redirect(url_for('login')) elif vid.uid == uid: vid.active = True db.session.commit() flash('User Verified!') return redirect(url_for('login')) else: flash('Did not verify user') return render_template('verify.html', verify_form=form) elif form.validate_on_submit(): suid = Users.query.filter_by(email=form.email.data).first() msg = Message(subject='Activate CHS Ride Share Account', sender=('Ride Share', '*****@*****.**')) msg.html = render_template('verify_email.html', suid=suid) msg.recipients = [form.email.data] mail.send(msg) flash('Check your email to activate your account.') return redirect(url_for('login')) else: return render_template('verify.html', verify_form=form)
def send_async_email(app, msg): '''Because it is a separate thread, the application context required by Flask-Mail will not be automatically set for us, so the app instance is passed to the thread, and the application context is set up manually, like we did above when we sent an email from the Python console.''' with app.app_context(): mail.send(msg)
def send_email(to, subject, template, **kwargs): msg = Message( subject, sender=app.config['MAIL_DEFAULT_SENDER'], recipients=[to]) msg.html = template mail.send(msg)
def register(): login_form = LoginForm() if current_user.is_authenticated: return redirect(url_for('index')) else: form = RegisterForm() if request.method == 'POST': if form.validate_on_submit(): password = bcrypt.generate_password_hash(form.password.data) uid = binascii.hexlify(os.urandom(32)).decode() user = Users(form.email.data, password, form.firstname.data, form.lastname.data, form.type.data, uid, active=False) db.session.add(user) db.session.commit() user = Users.query.filter_by(email=form.email.data).first() msg = Message(subject='Activate CHS Ride Share Account', sender=('Ride Share', '*****@*****.**')) msg.html = render_template('verify_email.html', suid=user) msg.recipients = [form.email.data] mail.send(msg) flash('Registered the user ' + form.firstname.data + ' ' + form.lastname.data + '! Check your email to activate your account.') return render_template('index.html', register_form=form, login_form=login_form) else: flash('did not validate') return render_template('index.html', register_form=form, login_form=login_form) return render_template('index.html', register_form=form, login_form=login_form)
def contact(): form = ContactForm( name=request.form['name'], email=request.form['email'], phone=request.form['phone'], zip=request.form['zip'], message=request.form['message'] ) print(request.form['name'], "sending a message\n", request.form['message']) msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + 'Consultation', sender=app.config['MAIL_SENDER'], recipients=app.config['MAIL_RECIPIENTS']) msg.html = render_template('inquiry.html', form=form) try: mail.send(msg) except Exception as e: print("EXCEPTION:", e) response = jsonify(code=e.args[0], message=str(e.args[1])) response.status_code = e.args[0] return response return jsonify(status='OK', name=request.form['message'])
def upload(): f = request.files['file'] upload_dir = os.path.join(basedir, 'app/static/uploads') abs_file_path = os.path.join(upload_dir, f.filename) print("INFO: Uploading " + f.filename + " to " + upload_dir) if not os.path.exists(upload_dir): os.mkdir(upload_dir) # TODO check for file size and maybe extension # Save to filesystem f.save(os.path.join(upload_dir, f.filename)) file_size = os.path.getsize(os.path.join(upload_dir, f.filename)) form = ContactForm( message="See attached resume." ) msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + 'Applicant', sender=app.config['MAIL_SENDER'], recipients=app.config['MAIL_RECIPIENTS']) # msg.html = render_template('', form=form) # print(f.filename) # print(f.content_type) with app.open_resource(abs_file_path) as fp: msg.attach(f.filename, f.content_type, fp.read()) try: mail.send(msg) except Exception: return jsonify(status='FAIL') return jsonify(status='OK', name=f.filename, size=file_size)
def send_newsletter(): form = QuestionForm() if request.method == 'POST': recievers = Newsletter.query.order_by(Newsletter.id.desc()).all() if form.validate() == False: flash('Wymagane wszystkie pola.') return render_template('admin/send_newsletter.html', form=form) else: msg = Message(sender=("*****@*****.**")) for reciever in recievers: msg.add_recipient(reciever.email) msg.subject = " %s " % (form.subject.data) msg.body = """ %s Aby wypisac sie z tego newslettera wejdz w zakladke pomoc na naszej stronie. """ % (form.message.data) mail.send(msg) print 'Newsletter do %s zostal wyslany' % (msg.recipients) flash('Newsletter zostal wyslany.') return redirect('/admin/newsletter') elif request.method == 'GET': print 'ok' return render_template('admin/send_newsletter.html', form=form, title='Wysylanie newslettera')
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 email synchronously mail.send(msg)
def transaction(postid): post = Listing.query.filter_by(id = postid).first() poster = User.query.filter_by(id=post.user_id).first() form = TransactionForm() if(form.validate_on_submit()): post.active = False post.datetime = datetime.now() db.session.add(post) db.session.commit() recipients = [poster.email, g.user.email] recipients = filter (lambda x: ('@' in x) and ('.' in x), recipients) if len(recipients) != 0: msg = Message('Dining Exchange Match',sender='*****@*****.**',recipients=recipients) msg.body = "Hello users,\n\n" + "You have recently been matched on CMU Dining Exchange. The user " msg.body += str(g.user.nickname) + " will" # has accepted your offer. The terms of the agreement are: \n\n" if post.buysell: msg.body += " buy " else: msg.body += " sell " msg.body += "one " + post.blockOrDinex msg.body += " per $" + str(post.price) msg.body += " from " + poster.nickname + ". The meeting location is " + post.location + "." msg.body += "\n\nAfter the exchange, please rate each other on http://127.0.0.1:5000" msg.body += url_for('rate', rateduser = poster.nickname) + " and http://127.0.0.1:5000" msg.body += url_for('rate', rateduser = g.user.nickname) msg.body += "\n\nThank you for using CMU Dining Exchange!" mail.send(msg) return redirect(url_for('success')) return render_template("transaction.html", title = "Transaction", form = form, post = post, poster = poster)
def signup(): if request.method == 'GET': return render_template('signup.html', form=RegistrationForm()) form = RegistrationForm(request.form) if form.validate_on_submit(): user = User(form.username.data, form.email.data) form.populate_obj(user) user.set_password(form.password.data) db.session.add(user) db.session.commit() msg = Message( 'Successful registration!', sender=('Blog Tceh Cource', '*****@*****.**'), recipients=[form.email.data] ) msg.body = 'Welcome to our blog!' mail.send(msg) flash('Successful registration! Please login.') return redirect(url_for('auth.login')) else: return render_template('signup.html', form=form)
def create_account(): form = NewUser() if form.validate_on_submit(): if User.query.filter_by(email=form.email.data).order_by(User.member_since.desc()).first(): flash('Email already registered!') else: # CREATE USER user = User(email=form.email.data, password=form.email.data, username=form.email.data, name=form.first_name.data + " " + form.last_name.data) db.session.add(user) db.session.commit() # GET SECURITY TOKEN token = ts.dumps(form.email.data, salt='email-confirm-key') confirm_url = url_for('auth.confirm_email', token=token, _external=True) # WRITE CONFIRMATION EMAIL AND SEND msg = Message(subject='Registration Confirmation for carminati.io!', sender='*****@*****.**', recipients=[form.email.data]) msg.body = """ Hey {first_name}, Thanks for registering for my site! Please confirm your email with the link below: {confirm} -Anthony """.format(first_name=form.first_name.data, confirm=confirm_url) mail.send(msg) flash('Confirmation email sent!') return redirect(url_for('site.index')) return render_template('auth/register.html', form=form)
def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): S=BotCheck(request.form.get('g-recaptcha-response')) user = User.query.get(form.email.data.lower()) if user: flash('Entered Email ID is already registered with us.') return render_template('register.html', form=form) if S==False: flash('Entered Email ID is already registered with us or Invalid Bot Captcha') return render_template('register.html', form=form) user=User(form.username.data,form.email.data.lower(),form.password.data,form.age.data) db.session.add(user) db.session.commit() try: mail.send(GetWelcomeMessage(user.name,user.email)) except: print("Error while Sending Mail") flash('Thanks for registering,you can login Now and start chating') return redirect(url_for('login')) return render_template('register.html', form=form)
def contact_me(): message = request.get_json() subject = "[blogify-notification]: " + message.get('subject') sender = message.get('sender') content = sender + ": " + message.get('content') captcha = message.get('captcha') print captcha email = Message(subject, sender=sender) email.add_recipient("*****@*****.**") email.body = content try: # change this os we use the app.config vars instead of leaving it public SITE_KEY = "6LcKAB8TAAAAAO2twN-zfqEQZ0bUz4KkRgk0p8e1" SECRET_KEY = "6LcKAB8TAAAAALBGRpDf1SAYHgMtoDRmX4MnGhFl" r = requests.post('https://www.google.com/recaptcha/api/siteverify', data = { "secret": SECRET_KEY, "response" : captcha } ) if r.json().get('success'): mail.send(email) return jsonify({ "response":"message sent" }) else: return jsonify({ "response":"wrong captcha" }) except Exception: return jsonify({ "response":"error" })
def send_reset_email(user, template, **kwargs): msg = Message(subject=app.config['RESET_MAIL_SUBJECT'], sender=app.config['MAIL_SENDER'], recipients=[user.email]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) mail.send(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 print 'Enviando mensaje a ' + str(recipients) mail.send(msg) print 'Mensaje enviado'
def forgotpass(): form = RecoverPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: # generate activation_key and save it in database user.activation_key = str(uuid.uuid4()) user.save() # send recover email if setting.MAIL_ENABLE: body = render_template("emails/forgotpass.html", user=user) message = Message(subject=u"找回密码", body=body, sender=setting.ADMIN_MAIL, recipients=[user.email]) mail.send(message) flash(u"邮件已发出", "successfully") else: flash(u"邮件服务器未开启,请联系管理员", "error") return redirect(url_for("account.forgotpass")) else: flash(u"对不起,没找到你的邮件", "error") return render_template("account/forgotpass.html", form=form)
def contact(self): form = ContactForm() if form.validate_on_submit(): try: template = """ This is a contact form submission from Guildbit.com/contact \n Email: %s \n Comment/Question: %s \n """ % (form.email.data, form.message.data) msg = Message( form.subject.data, sender=settings.DEFAULT_MAIL_SENDER, recipients=settings.EMAIL_RECIPIENTS) msg.body = template mail.send(msg) except: import traceback traceback.print_exc() flash("Something went wrong!") return redirect('/contact') return render_template('contact_thankyou.html') return render_template('contact.html', form=form)
def volunteer(volunteerId): # query the volunteer table for a volunteer with the given id volunteer = Volunteer.query.filter_by(id = volunteerId).first() # check if either one of the submit buttons have been clicked if request.method == 'POST': # if the accept button is clicked activate the account if request.form.get('accept') == 'accept': volunteer.isActive = True # send accepted email email msgTitle = "Fair Frome Application Accepted" msg = Message(msgTitle,html=render_template('accounts/volunteer_application_success.html', volunteer=volunteer), sender=app.config['ADMIN_EMAIL'],recipients=[volunteer.email]) mail.send(msg) # if the decline button is clicked then delete the volunteer record and email the applying volunteer if request.form.get('decline') == 'decline': # send failed application email msgTitle = "Fair Frome Application Declined" msg = Message(msgTitle,html=render_template('accounts/volunteer_application_fail.html', volunteer=volunteer), sender=app.config['ADMIN_EMAIL'],recipients=[volunteer.email]) mail.send(msg) # delete the record for the applying volunteer Volunteer.query.filter_by(id=volunteer.id).delete() db.session.commit() # after redirect the admin to the applying volunteers page return redirect(url_for('dashboard.applyingVolunteers')) # render the profile template return render_template("accounts/profile.html" , volunteer=volunteer)
def create(): form = CreateForm() if form.validate_on_submit(): newuser = form.username.data password = crypt.crypt(form.password.data,salt()) user = User(nickname=newuser, password=sha256_crypt.encrypt(form.password.data), email=form.email.data, role=ROLE_USER) db.session.add(user) db.session.commit() os.system("sudo mkdir " + settings.WORKING_DIR + newuser) os.system("sudo mkdir " + settings.REMOTE_DIR + newuser) os.system("sudo mkdir " + settings.WORKING_DIR + newuser + "/myRepo") os.system("sudo chmod 777 " + settings.REMOTE_DIR + newuser) os.system("sudo chmod 777 " + settings.WORKING_DIR + newuser) repo = Repo.init_bare(settings.REMOTE_DIR + newuser + "/") newrepo = Rpstry(repourl="/myRepo/", owner=user) db.session.add(newrepo) db.session.commit() working_repo = repo.clone(settings.WORKING_DIR + newuser + newrepo.repourl, False, False, "origin") p = subprocess.Popen(["sudo", "git", "remote", "add", "origin", "file:///" + settings.REMOTE_DIR + newuser + "/"], cwd=settings.WORKING_DIR + newuser + "/myRepo/") p.wait() open(settings.REMOTE_DIR + newuser + "/.htpasswd", 'a').writelines(newuser + ":" + password + "\n") s = get_serializer() payload = s.dumps(user.id) url = url_for('activate_user', payload=payload, _external=True) msg = Message('Confirm Email Address', sender = ADMINS[0], recipients = [user.email]) msg.body = "Follow this link to activate account: " + url mail.send(msg) flash("User created and activation email sent") return redirect(url_for('login')) return render_template('createAccount.html', title = 'Create New Account', form = form)
def post(self): form = SignupForm(request.form) print("form validate", form.validate()) print("form errors", form.errors) if form.validate() == False: print("form errors", form.errors) return render_template("signup.html", form=form) else: # import pdb;pdb.set_trace(); user = User( username=form.username.data, password=form.password.data, firstname=form.firstname.data, lastname=form.lastname.data, email=form.email.data, ) db.session.add(user) db.session.commit() msg = Message( "Hello" + " " + form.firstname.data + " " + form.lastname.data, sender="*****@*****.**", recipients=[form.email.data], ) msg.body = "Thanks for signup , we will get in touch with you soon!!!" mail.send(msg) user = User.query.all() print("users are :: ", user) print("@@@@@@@@@@@ redirected to showSignIn part") return redirect(url_for("index"))
def send_confirmation(): """docstring for send_confirmation""" token = generate_confirmation_token(str(g.user.get_email())) lnk = url_for('users.confirm', token=token, _external=True) conflnk_html = '<a href="%s">%s</a>' % (lnk, lnk) msg = Message( gettext(u"Please confirm your account at vision website"), sender=current_app.config['NOREPLY_EMAIL'], recipients=[g.user.get_email()] ) msg.body = "\nWelcome\n\n" msg.body += "\nPlease confirm your account by clicking this link:\n" msg.body += "\n%s" % lnk msg.body += "\nFuture notifications will be sent to this email address." msg.body += "\nThank you," msg.body += "\n\nTeam." msg.html = "Hi, Welcome" msg.html += "<br><br>Please confirm your account by clicking this link:" msg.html += "\n%s" % conflnk_html msg.html += "<br>Future notifications will be sent to this email address." msg.html += "<br>Thank you," msg.html += "<br><br>Team." mail.send(msg)
def sendmail(mail_id): msg = Message("Your Attendance QR-Code.", recipients=[mail_id], sender='*****@*****.**') with app.open_resource("../qr.png") as fp: msg.attach("qr.png", "image/png", fp.read()) mail.send(msg)
def login_or_signup_user(email, name): # 0. Convert email and name normal non unicode characters. email = unicodedata.normalize('NFKD', email).encode('ascii','ignore') name = unicodedata.normalize('NFKD', name ).encode('ascii','ignore') # 1. if str(email) == None or str(email) == "": return redirect(url_for('login')) # 2. user_exists = False if c.count('users', { 'email' : str(email) }) == 1L: user_exists = True # 4.1 if user_exists: session['openid'] = str(email) else: c.put('users', str(email), {'name' : str(name), 'funds' : 0.0, 'Bitcoin' : 0.0, 'Dogecoin' : 0.0 }) # Send email about new user signup msg = Message("New User", sender=EMAIL, recipients=[EMAIL]) msg.body = "New User %s:" % email mail.send(msg) session['openid'] = str(email) g.user_email = str(email) g.username = str(name) return redirect(request.args.get('next') or url_for('index'))
def register(): form = RegistrationForm() if request.method == 'POST': if form.validate() is False: flash("All fields are required for registration.") return render_template('register.html', form=form) else: newuser = User(form.username.data, form.email.data, form.passwd.data) db.session.add(newuser) db.session.commit() # obtuser = User.query.filter_by(email=form.email.data.lower()).first() email = newuser.email.encode('ascii', 'ignore') reg_key = newuser.reg_key.encode('ascii', 'ignore') subject = "Your confirmation email from microBLOG" mail_to_be_sent = Message(subject=subject, recipients=[newuser.email]) conf_url = url_for('confirm', reg_key=reg_key, _external=True) mail_to_be_sent.body = "Please click the link to confirm registration at microBLOG: %s" % conf_url mail.send(mail_to_be_sent) flash('Please check your email to confirm registration. Then you can start using the site.') # session['email'] = newuser.email return redirect(url_for('homepage')) elif request.method == 'GET': return render_template('register.html', form=form)
from flask_mail import Message from app import app, mail from config import ADMINS sender = '*****@*****.**' receivers = ['*****@*****.**'] message = """From: From Person <*****@*****.**> To: To Person <*****@*****.**> Subject: SMTP e-mail test This is a test e-mail message. """ # email server MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = os.environ.get('MAIL_USERNAME') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') # administrator list ADMINS = ['*****@*****.**'] msg = Message('test subject', sender=ADMINS[0], recipients=ADMINS) msg.body = 'text body' msg.html = '<b>HTML</b> body' with app.app_context(): ... mail.send(msg) ....
def send_async_email(app, msg): with app.app_context(): mail.send(msg)
def send_message(to_address_list=None, **kwargs): """Send an email with the parameters as: to_address_list=[list of tuples (recipient name,recipient address)]=None If the to_address_list is not provided, mail will be sent to the admin -- all templates must use 'context' as their only context variable **kwargs: context = {a dictionary like object with data for rendering all emails} = {} body = <text for body of email> = None body_text_is_html = <True | False> = False text_template=<template to render as plain text message> = None html_template=<template to render as html message> = None subject=<subject text (will be rendered with the current context>)>= a default subject subject_prefix=<some text to prepend to the subject: = '' from_address=<from address> = app.config['MAIL_DEFAULT_ADDR'] from_sender=<name of sender> = app.config['MAIL_DEFAULT_SENDER'] reply_to_address=<replyto address> = from_address reply_to_name=<name of reply to account> = from_sender On completion returns a tuple of: success [True or False] message "some message" """ #import pdb;pdb.set_trace() app_config = get_app_config( ) #update the settings. this also recreates the mail var in app with new settings context = kwargs.get('context', {}) body = kwargs.get('body', None) body_is_html = kwargs.get('body_is_html', None) text_template = kwargs.get('text_template', None) html_template = kwargs.get('html_template', None) subject_prefix = kwargs.get('subject_prefix', '') try: admin_addr = app_config['MAIL_DEFAULT_ADDR'] admin_name = app_config['MAIL_DEFAULT_SENDER'] except KeyError as e: mes = "MAIL Settings not found" mes = printException(mes, 'error', e) return (False, mes) from_address = kwargs.get('from_address', admin_addr) from_sender = kwargs.get('from_sender', admin_name) reply_to = kwargs.get('reply_to', from_address) subject = subject_prefix + ' ' + kwargs.get( 'subject', 'A message from {}'.format(from_sender)) if not text_template and not html_template and not body: mes = "No message body was specified" printException(mes, "error") return (False, mes) if not to_address_list or len(to_address_list) == 0: #no valid address, so send it to the admin to_address_list = [ (admin_name, admin_addr), ] with mail.record_messages() as outbox: sent_cnt = 0 err_cnt = 0 err_list = [] result = True for who in to_address_list: #import pdb;pdb.set_trace() name = "" address = "" body_err_head = "" if type(who) is tuple: if len(who) == 1: # extend whp who = who[0] + (who[0], ) name = who[0] address = who[1] else: address = who #assume its a str name = who if not looksLikeEmailAddress(address) and looksLikeEmailAddress( name): # swap values temp = address address = name name = temp if not looksLikeEmailAddress(address): # still not a good address... address = admin_addr name = admin_name if not body: body = "" body_err_head = "Bad Addres: {}\r\r".format(who, ) subject = render_template_string(subject.strip(), context=context) #Start a message msg = Message(subject, sender=(from_sender, from_address), recipients=[(name, address)]) #Get the text body verson if body: if body_is_html: msg.html = render_template_string("{}{}".format( body_err_head, body, ), context=context) else: msg.body = render_template_string("{}{}".format( body_err_head, body, ), context=context) if html_template: msg.html = render_template(html_template, context=context) if text_template: msg.body = render_template(text_template, context=context) msg.reply_to = reply_to try: mail.send(msg) sent_cnt += 1 except Exception as e: mes = "Error Sending email" printException(mes, "error", e) err_cnt += 1 err_list.append("Error sending message to {} err: {}".format( who, str(e))) # End Loop if sent_cnt == 0: mes = "No messages were sent." result = False else: mes = "{} messages sent successfully.".format(sent_cnt) if err_cnt > 0: mes = mes + " {} messages had errors.\r\r{}".format( err_cnt, err_list) return (result, mes)
def _async(app, msg): with app.app_context(): try: mail.send(msg) except SMTPDataError as e: logger.warning(str(e))
def send_email(subject, recipients, template, html_data): # send the message msg = Message(subject, recipients) msg.html = render_template(template, html_data) mail.send(msg)
def semail(name, email, subject, message): msg = Message("request.form.subject", sender="request.form.name", recipients=["request.form.email"]) msg.body = "This is the body" mail.send(msg)
def send_async(app, message): ''' Send the mail asynchronously. ''' with app.app_context(): mail.send(message)
def send_async_email(app, msg): with app.app_context(): try: mail.send(msg) except Exception as e: pass
def send_response_email(email, template): msg = Message('Response to Your Request', sender=app.config['ADMINS'][0], recipients=[email], html=template) mail.send(msg)
def send_email(order): msg = Message('Новий запит', recipients=Config.ADMINS) msg.body = order mail.send(msg)
def send_async_email(msg): mail.send(msg)
def send_async_email(application, msg): with application.application_context(): mail.send(msg)
def send_async_email(app, msg): with app.app_context(): # identify the application instance mail.send(msg) # thread automatically closes
def send_confirmation(email, template): msg = Message('SAAC Email Confirmation', sender=app.config['ADMINS'][0], recipients=[email], html=template) mail.send(msg)
def send_mail(email, url): msg = Message("Recupera tu Contrasenia", sender="*****@*****.**", recipients=[email]) msg.body = "Este mensaje te llego porque solicitaste recuperar tu contrasenia, utiliza esta direccion de correo " + url mail.send(msg)
def send_async_email(app, msg): """ Target function run in thread to send email. Used by send_email. """ with app.app_context(): mail.send(msg)
def send_feedback(id): # Проверка отправляемых слоёв - нужно спросить у пользователя, что отправлять msg = Message("Test message", sender="*****@*****.**", recipients=["*****@*****.**"]) msg.body = get_db().execute( 'SELECT body' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0] #Неплохо бы завернуть этот код в метод image_data = { 'original': get_db().execute( 'SELECT original_picture' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0], 'salinity': get_db().execute( 'SELECT edit_salinity' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0], 'corrosion': get_db().execute( 'SELECT edit_corrosion' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0], 'pitting': get_db().execute( 'SELECT edit_pitting' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0], 'oil': get_db().execute( 'SELECT edit_oil' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0], 'recess': get_db().execute( 'SELECT edit_recess' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0], 'elongated_recess': get_db().execute( 'SELECT edit_ext_recess' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0] } #Вместо отправки всего выбирать нужные слои или отправлять все и писать нужные слои текстом error = "" attach_imgs('original', image_data, msg) empty_layers = 0 #Заменить на цикл try: attach_imgs('salinity', image_data, msg) except: error += "Salinity " empty_layers += 1 try: attach_imgs('corrosion', image_data, msg) except: error += "Corrosion " empty_layers += 1 try: attach_imgs('pitting', image_data, msg) except: error += "Pitting " empty_layers += 1 try: attach_imgs('oil', image_data, msg) except: error += "Oil " empty_layers += 1 try: attach_imgs('recess', image_data, msg) except: error += "Recess " empty_layers += 1 try: attach_imgs('elongated_recess', image_data, msg) except: error += "Elongated recess" empty_layers += 1 if (empty_layers == 6): flash("There are no edited layers for this post") else: if (error == ""): flash("Message sent with all the layers!") mail.send(msg) else: flash("Post " + get_db().execute( 'SELECT title' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id, )).fetchone()[0] + " (ID: " + str(id) + "): The following layers weren't saved to be sent: " + error) mail.send(msg) return redirect(url_for('blog.index'))
def send_async_email(msg): """ Takes `msg` and emails it using `mail.send(msg)` as a background process. """ mail.send(msg)
def send_async_email(app, msg): """异步电子邮件""" with app.app_context(): mail.send(msg)
def password(): data = request.form.to_dict() # Fetch Data k6_encrypted_kum = data.get('k6_encrypted_kum') k6_encrypted_kupg = data.get('k6_encrypted_kupg') iv6 = data.get('iv6') authdata_and_hashed_k6encrypted = data.get('authdata_and_hashed_k6encrypted') pwd_kuisencrypted_and_hashed_k6encrypted = data.get('pwd_kuisencrypted_and_hashed_k6encrypted') bank_name = data.get('bank_name', None) # Decrypt K6 krm = RSA.importKey(get_key(CertificateOwner.MERCHANT, CertificateType.MERCHANT)['private_key']) k6 = merchant_decrypt_k1(k6_encrypted_kum) # Decrypt Authdata authdata_and_hashed = decrypt_aes(k6, iv6, authdata_and_hashed_k6encrypted) authdata = authdata_and_hashed[:-32] hashed = authdata_and_hashed[len(authdata):] # Hash authdata authdata_hashed = SHA256.new(authdata).hexdigest() authdata_hashed = bytes.fromhex(authdata_hashed) if not authdata_hashed == hashed: msg = ErrorMessages.MISMATCH_DIGEST return make_response(json({'status': 'NO', 'message': msg})) # Encrypt AuthData with k7 k7 = Random.get_random_bytes(16) authdata_encrypted_k7 = encrypt_aes(k7, authdata.decode()) # Encrypt K7 with Kupg kupg = RSA.importKey(get_key(CertificateOwner.GATEWAY, CertificateType.GATEWAY)['public_key']) k7_encrypted_kupg = encrypt_rsa(kupg, k7) # Sign authdata_encrypted_k7 with Krm authdata_signature = sign_message(krm, authdata) # Base64 Encode b64_pwd_kuisencrypted_and_hashed_k6encrypted = base64.b64encode(pwd_kuisencrypted_and_hashed_k6encrypted.encode()) b64_k7_encrypted_kupg = base64.b64encode(k7_encrypted_kupg) b64_authdata_signature = base64.b64encode(authdata_signature) b64_authdata_encrypted_k7 = base64.b64encode(authdata_encrypted_k7) b64_k6_encrypted_kupg = base64.b64encode(k6_encrypted_kupg.encode()) b64_iv6 = base64.b64encode(iv6.encode()) gateway_response = requests.post(Api.SEND_GATEWAY_PASSWORD, data={ 'b64_pwd_kuisencrypted_and_hashed_k6encrypted': b64_pwd_kuisencrypted_and_hashed_k6encrypted.decode(), 'b64_k7_encrypted_kupg': b64_k7_encrypted_kupg, 'b64_authdata_signature': b64_authdata_signature, 'b64_authdata_encrypted_k7': b64_authdata_encrypted_k7, 'b64_k6_encrypted_kupg': b64_k6_encrypted_kupg, 'b64_iv6': b64_iv6, 'session_id': request.cookies.get(SESSION_KEY), 'bank_name': bank_name}) if gateway_response.status_code != 200: msg = ErrorMessages.FAILED_CONNECT_GATEWAY return make_response(json({'status': 'NO', 'message': msg})) gateway_response = gateway_response.json()['data'] if gateway_response.get('status') != 'YES': msg = ErrorMessages.TRANSACTION_FAILED return make_response(json({'status': 'NO', 'message': msg})) # Fetch Data b64_payment_response_encrypted = gateway_response.get('b64_payment_response_encrypted') b64_k8_encrypted_kum = gateway_response.get('b64_k8_encrypted_kum') b64_payment_response_signature = gateway_response.get('b64_payment_response_signature') # Decode base64 payment_response_encrypted = base64.b64decode(b64_payment_response_encrypted) k8_encrypted_kum = base64.b64decode(b64_k8_encrypted_kum) payment_response_signature = base64.b64decode(b64_payment_response_signature) # Decrypt K8_KUM k8 = decrypt_rsa(krm, k8_encrypted_kum) # Decrypt payment_response_encrypted payment_response = AESCipher(k8).decrypt(payment_response_encrypted) if verify_rsa(kupg, payment_response, payment_response_signature): if payment_response.decode() == Messages.TRANSACTION_VERIFIED: cart = Cart.get_current() products = cart.products msg = render_template('mail_order.html', products=products, cart=cart) user = request.session.user from app import mail message = Message(subject="Mua Hàng Thành Công", html=msg, sender=("Anh Thu Shop", "*****@*****.**"), recipients=[user.email]) mail.send(message) cart = Cart.get_current() cart.data = {} response = make_response(json( {'status': 'YES', 'payment_response': payment_response.decode(), 'url': url_for('home.index')})) response.set_cookie('cart', cart.jsonified_data) return response elif payment_response.decode() == ErrorMessages.NOT_ENOUGH_MONEY: msg = ErrorMessages.NOT_ENOUGH_MONEY else: msg = ErrorMessages.FAILED_VERIFY_TRANSACTION return make_response(json({'status': 'NO', 'message': msg}))
def send_async_email(current_app, msg): with current_app.app_context(): mail.send(msg)
def send_async_email(app, msg): with app.app_context(): try: mail.send(msg) except ConnectionRefusedError: raise InternalServerError("[MAIL SERVER] not working")
def send_mail_async(microblogapp, msg): with microblogapp.app_context(): mail.send(msg)
def send_async_email(app, msg): with app.app_context(): #确认程序上下文被激活 mail.send(msg)
def sendVerifyEmail(newEmail, token): print("Sending verify email!") msg = Message("Verify email address", recipients=[newEmail]) msg.body = "This is a verification email!" msg.html = render_template("emails/verify.html", token=token) mail.send(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 mail.send(msg) Thread(target=send_async_email, args=(app, msg)).start()
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)
def send_conf_mail(recp,conf_link): msg=Message(recipients=[recp]) msg.body="welcome to our website, please follow the link bellow to finish registering :) (love) "+conf_link with app.app_context(): mail.send(msg)
def _send_async_email(app, msg): with app.app_context(): try: mail.send(msg) except SMTPException: logger.exception("Ocurrió un error al enviar el email")
def send_mail(to, subject, **kwargs): msg = Message(Config.FLASKY_MAIL_SUBJECT_PREFIX + subject, sender=Config.FLASKY_MAIL_SENDER, recipients=[to]) msg.html = auth.format(kwargs["user"], kwargs["code"]) mail.send(msg)