def posts(): current_user = request.user if request.method == "POST": title = request.form.get("posttitle") text = request.form.get("posttext") post = Post(title=title, text=text, user=current_user) db.session.add(post) db.session.commit() # send notification email msg = Message(subject="WebDev Blog - Posted a post", sender=SENDER, recipients=[current_user.email]) full_post_link = HOST_ADDR + url_for('blog.post', post_id=post.id) msg.body = f"Hi {current_user.username}!\n" \ f"There is news, check this out:{full_post_link}\n" \ f"Enjoy!" msg.html = render_template("new_post.html", username=current_user.username, link=f"{full_post_link}", post=post) mail.send(msg) return redirect(url_for('blog.posts')) if request.method == "GET": posts = Post.query.all() return render_template("posts.html", posts=posts, user=request.user, active1="active")
def contact(): form = ContactForm() if request.method == 'POST': if form.validate_on_submit(): name = form.name.data.strip() email = form.email.data.strip() subject = "[dzlibs.io] %s" % form.subject.data.strip() message = form.message.data.strip() msg = Message(subject, sender=app.config['ADMINS'][0], recipients=app.config['ADMINS']) msg.body = """ From: %s <%s> Message: %s """ % (name, email, message) mail.send(msg) flash(_('Message sent successfully'), category='success') return render_template('frontend/contact.html', form=form) else: flash(_('Error happened, see below'), category='alert') return render_template('frontend/contact.html', form=form) else: return render_template('frontend/contact.html', form=form)
def showConfirm(): """ Display the order confirmation page after an order is submitted. """ # Get the customer from the db using the 'customer_ID' session variable db_customer = Customer.query.filter_by( customerID=session['customer_ID']).one() # Create a list of the cart items for use in the email's message body items = [dic['item'] for dic in session['cart'] if 'item' in dic] # Use the first item in the cart to obtain the 'orderID'. If None, # display 'design' link try: firstItem = session['cart'][0] orderID = firstItem['orderID'] msg = Message( 'Confirmation', sender='*****@*****.**', recipients=[session['customer_email']]) msg.body = "Thank you for your order of: %s. Your order number is: %d." % ( items, orderID) mail.send(msg) # Clear the cart after payment is received and confirmation is sent. session['cart'] = [] return render_template('auth/confirmation.html') except: return redirect(url_for('showHome'))
def add_msg(): Feedback.create(request.json) message = Message('githubDoc反馈', recipients=current_app.config.get('MAIL_RECIPIENTS'), body=request.json.get('msg')) mail.send(message) return response()
def send_application_registered_msg(name: str, email: str, track_number: str) -> None: msg = Message('Ваша заявка принята к рассмотрению', recipients=[email]) msg.html = f'<h1>Ваша заявка была принята к рассмотрению!</h1><p>{name}, ожидайте звонка.' \ f' Также Вы можете отследить статус вашей заявки на нашем сайте.</p>' \ f'<h2>Ваш трек-код:</h2><h3>{track_number}</h3> ' mail.send(msg)
def send_email(parts): msg = Message(html=parts[0], subject=parts[1], sender=("ReCOP Director", parts[2]), recipients=[parts[3]]) mimes = MimeTypes() if parts[4]: for attachment in parts[4]: with current_app.open_resource(attachment.path) as file: mime = mimes.guess_type(file.name) if attachment.type == 1: name = 'Budget Plan' elif attachment.type == 2: name = 'Programme' elif attachment.type == 3: name = 'Signed Request Letter' msg.attach(name, mime[0], file.read()) mail.send(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('users.reset_password', token=token, _external=True)} If you did not make this request then simply ignore this email and no change has made ''' mail.send(msg)
def test_mail(): try: msg = Message(subject="Flask WebDev Project Test Email", sender="*****@*****.**", recipients=["*****@*****.**"]) msg.body = "There is a new Blogpost!, Check this out!" mail.send(msg) return "Flask sent your mail!" except Exception as e: return str(e)
def test_send_mail_single_msg_content(self): with mail.record_messages() as mailbox: mail.send(self.msg) message = mailbox[0] test_cases = ((self.subject, message.subject), (self.sender, message.sender), (self.recipients, message.recipients), (self.msg_body, message.body)) for case in test_cases: with self.subTest(case=case): self.assertEqual(*case)
def send_mail(msg, allow_redirects=True): try: mail.send(msg) return True except AssertionError: if allow_redirects: flash( "Sender Email is not specified, please contact the website staff." ) return redirect(url_for('home.home_page', category='danger')) return False
def send_confirmation_to(utilisateur, host_url): utilisateur.make_token() utilisateur.save() url = host_url[:-1] + url_for("inscription_token", token=utilisateur.token) msg = Message("Confirmation inscription", recipients=[utilisateur.mail]) msg.html = Markup(render_template('mail.html', url=url)) mail.send(msg) return redirect(url_for('login', token=utilisateur.token))
def send_link_as_mail(**kwargs): subject = 'Probation Form - {}'.format(kwargs['emp_name']) msg = Message(subject, sender=kwargs['reviewer_email'], recipients=[kwargs['emp_email']]) msg.html = """Please click on the link below to sign your probation status form.<br> <a href="http://{0}/document/{1}/{2}">Click here</a> """.format(request.host, kwargs['rev_emp_code'], kwargs['emp_code']) mail.send(msg)
def send_report(): top_five = Apartment.objects.order_by('price').limit(5) email = '' for apartment in top_five: email += '\n -------- \n %s - %s %s' % (apartment.title, apartment.price, apartment.url) msg = Message(subject='Apartment Report from your Minion !', sender='*****@*****.**', recipients=['*****@*****.**'], body=email) mail.send(msg)
def send_link_as_mail(**kwargs): subject = 'PRD Form - {}'.format(kwargs['emp_name']) msg = Message(subject, sender='*****@*****.**', recipients=[kwargs['rev_email']]) msg.html = """Please click on the link below to sign PRD form.<br> <a href="http://{0}/document/{1}/{2}">Click here</a> """.format(request.host, kwargs['emp_code'], kwargs['reviewer_code']) mail.send(msg)
def send_manager_link_as_mail(**kwargs): subject = 'Final Rating' msg = Message(subject, sender='*****@*****.**', recipients=[kwargs['rev_email1']]) msg.html = """Please click on the link below to sign your PRD Form.<br> <a href="http://{0}/final_form/{1}/{2}">Click here</a> """.format(request.host, kwargs['emp_code1'], kwargs['reviewer_code1']) mail.send(msg)
def send_manager_link_as_mail(**kwargs): subject = 'Suggestion form' msg = Message(subject, sender='*****@*****.**', recipients=[kwargs['email']]) msg.html = """Please click on the link below :.<br> <a href="http://{0}/final/{1}">Click here</a> """.format(request.host, kwargs['emp_code1']) mail.send(msg)
def send_link_as_mail(**kwargs): subject = 'Suggestion Form - {}'.format(kwargs['emp_name']) msg = Message(subject, sender='*****@*****.**', recipients=['*****@*****.**']) msg.html = """You have one new suggestion from your team member.<br Please click on the link below :<br> <a href="http://{0}/suggestion/{1}/{2}">Click here</a> """.format(request.host, kwargs['id'], kwargs['emp_code']) mail.send(msg)
def test_send_multiple_msgs_content(self): self.recipients.extend(['*****@*****.**', '*****@*****.**']) msg = Message(**self.data) with mail.record_messages() as mailbox: mail.send(msg) for message in mailbox: with self.subTest(message=message): test_cases = ((self.subject, message.subject), (self.sender, message.sender), (self.recipients, message.recipients), (self.msg_body, message.body)) for case in test_cases: self.assertEqual(*case)
def send_report(): top_five = Apartment.objects.order_by('price').limit(5) email = '' for apartment in top_five: email += '\n -------- \n %s - %s %s' % (apartment.title, apartment.price, apartment.url) msg = Message( subject='Apartment Report from your Minion !', sender = '*****@*****.**', recipients=['*****@*****.**'], body=email ) mail.send(msg)
def post(self): subject = email_parser.parse_args().get('subject') sender = email_parser.parse_args().get('sender') recipients = email_parser.parse_args().get('recipients') msg_body = email_parser.parse_args().get('msg_body') if all((subject, sender, recipients)): msg = Message(subject=subject, recipients=recipients, body=msg_body, sender=sender) mail.send(message=msg) return 'Your message was successfully sent', 200 return 'Something went wrong on our side. Please try later', 400
def sendmail_release(servername, alert_info, host): msg = Message('解除告警邮件', sender=(host, '*****@*****.**'), recipients=['*****@*****.**']) msg.html = '<p>解除告警邮件:</p>' \ '<p>服务名称:"%s"</p>' \ '<p>告警内容:"%s"告警已解除</p>' \ '<p><small style="color: #868e96">邮件无需回复.</small></p>'%(servername,alert_info) # with app.open_resource(info_list['filename']) as fp: # msg.attach(info_list['filename'], "warn/log", fp.read()) mail.send(msg) return "发送成功"
def email(self, subj, body, rlist): with app.app_context(): print(rlist) total = len(rlist) for i, s in enumerate(rlist): print(s) msg = Message(str(subj), recipients=[s]) msg.body = str(body) mail.send(msg) self.update_state(state='PROGRESS', meta={'current': i, 'total': total, 'status': 'Email sent to ' + s}) return {'current': 100, 'total': 100, 'status': 'Task completed!', 'result': 42}
def contact(): form = ContactForm() if form.validate_on_submit(): # send email msg = Message("Message from your visitor" + form.name.data, sender='*****@*****.**', recipients=[private.ADMIN_EMAIL]) msg.body = """ From: %s <%s>, %s """ % (form.name.data, form.email.data, form.message.data) with app.app_context(): mail.send(msg) flash("Message sent", 'success') return redirect(url_for('index')) return render_template('inni/contact.html', form=form)
def sendmail_alarm(servername, alert_info, host, created, count): msg = Message('告警邮件', sender=(host, '*****@*****.**'), recipients=['*****@*****.**']) msg.html = '<p>告警邮件:</p>' \ '<p>服务名称:"%s"</p>' \ '<p>告警内容:产生了"%s",请及时处理</p>' \ '<p>告警产生时间:"%s"</p>' \ '<p>告警次数:第"%s"次产生告警</p>' \ '<p><small style="color: #868e96">邮件无需回复.</small></p>'%(servername,alert_info,created,count) # with app.open_resource(info_list['filename']) as fp: # msg.attach(info_list['filename'], "warn/log", fp.read()) print msg mail.send(msg) return "发送成功"
def send_document_as_mail(**kwargs): subject = 'Probation Form - {}'.format(kwargs['emp_name']) msg = Message(subject, sender='*****@*****.**', recipients=['*****@*****.**']) msg.html = """Please find the attached form.""" with current_app.open_resource('static/docs/' + kwargs['file_name']) as fp: msg.attach( filename=kwargs['file_name'], data=fp.read(), content_type= 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) mail.send(msg)
def send_register_email(self, recipient_email): app = current_app._get_current_object() ts = URLSafeTimedSerializer(app.config["SECRET_KEY"]) token = ts.dumps(recipient_email, salt=app.config["EMAIL_TOKEN_SALT"]) g.confirm_url = url_for('register.email_confirmed', token=token, _external=True) g.email = recipient_email html = render_template("email/register.html") message = Message(sender=app.config["MAIL_USERNAME"], recipients=[recipient_email], subject=R.string.email.register.subject % dict(title=R.string.micro_blog), html=html) mail.send(message)
def post(post_id): current_user = request.user post = Post.query.filter(Post.id == post_id).first() if request.method == "POST": text = request.form.get("text") comment = Comment( text=text, post=post, user=current_user ) db.session.add(comment) db.session.commit() # if user writes comment, with all other users # who have written a comment in this post and notify them users = list(set([c.user for c in post.comments] + [post.user])) for user in users: # send notification email msg = Message( subject=f"Hello World Blog - News about a Blogpost you are interestet in", sender=SENDER, recipients=[user.email] ) full_post_link = HOST_ADDR + url_for('blog.post', post_id=post.id) msg.body = f"Hi {user.username}!\n" \ f"Another Comment Reply on the Post: {post.title}" \ f"\n{full_post_link}" \ f"\nEnjoy!" msg.html = render_template("new_comment.html", username=current_user.username, link=f"{full_post_link}", post=post, comment=comment) mail.send(msg) return redirect(url_for("blog.post", post_id=post.id)) elif request.method == "GET": comments = Comment.query.filter(Comment.post_id == post_id).all() return render_template('post.html', post=post, comments=comments, user=request.user, redirectTo=getPath())
def mutate(self, info, email): user = mongo.db.users.find_one({'email': email}) if user is None: return RequestResetPassword(response=ResponseMessage( text='Alamat surel anda salah atau belum terdaftar!', status=False)) token = secrets.token_urlsafe() token_expiry = datetime.datetime.utcnow() + datetime.timedelta( minutes=15) result = mongo.db.reset_passwords.insert_one({ 'email': user['email'], 'token': token, 'token_expiry': token_expiry }) if result.inserted_id is None: return RequestResetPassword(response=ResponseMessage( text= 'Terjadi kesalahan pada server, permintaan ubah kata sandi gagal', status=False)) try: message = Message('Permintaan ubah kata sandi', sender=ENV.get('MAIL_USERNAME'), recipients=[user['email']]) message.html = render_template('emails/reset-password.html', name=user['first_name'], reset_token=token) mail.send(message) except Exception as ex: return RequestResetPassword( response=ResponseMessage(text=str(ex), status=False)) return RequestResetPassword( reset_url=f"https://moodscape-app.web.app/reset-password/{token}", response=ResponseMessage( text='Berhasil melakukan permintaan ubah kata sandi', status=True))
def forgot_password_post(): email = request.form.get('email') if not email: flash('Please input your email address.') else: user = User.query.filter_by(email=email).first() if not user: # if a user is found, ask user try to sign up again flash('Please input correct email address.') return redirect(url_for('auth.forgot_password')) html_body = render_template('email/reset_password.html', username=user.name, reset_url='https://github.com/phsontung/flask-skeleton') msg = Message(subject='Reset your password', sender='*****@*****.**', html=html_body, recipients=[email]) mail.send(msg) flash('Email sent. Please check your email.') return redirect(url_for('auth.forgot_password')) # Reload page
def sendmail(users, subject, message, html=False, app=None): if app: mail.app = app else: app = current_app recipients = [x.email for x in users if isinstance(x, User)] recipients.extend( [x for x in users if isinstance(x, basestring) and '@' in x]) sender = app.config.get('DEFAULT_MAIL_SENDER') if html: msg = Message(recipients=recipients, html=message, subject=subject, sender=sender) else: msg = Message(recipients=recipients, body=message, subject=subject, sender=sender) mail.send(msg)
def showContact(): """ Display the contact information page. """ if request.method == 'POST': msg = Message( 'Contact', sender='*****@*****.**', recipients=['*****@*****.**']) msg.body = "Customer name: %s\n" % ( request.form['customer-name']) msg.body += "Customer email: %s\n" % ( request.form['customer-email']) msg.body += "Message: %s" % (request.form['customer-message']) mail.send(msg) customer = Customer( name=request.form['customer-name'], email=request.form['customer-email'] ) db.session.add(customer) db.session.commit() return redirect(url_for('showContactComplete')) else: return render_template('contact.html')
def registration(): default = "Admin" if request.method == "POST": username = request.form.get("username") email = request.form.get("email") password = request.form.get("password") repeat = request.form.get("repeat") role = default # check email valid is_valid = check_email(email) if not is_valid: flash("Email is not a valid email", "warning") return redirect(url_for("user.registration")) if password != repeat: flash("Password and repeat did not match!", "warning") return redirect(url_for("user.registration")) if check_email_exists(email): flash("This E-Mail already exist, please go to Login", "warning") return redirect(url_for("user.registration")) password_hash = bcrypt.generate_password_hash(password).decode('utf-8') session_cookie = str(uuid.uuid4()) expiry_time = datetime.datetime.now() + datetime.timedelta( seconds=COOKIE_DURATION) user = User(username=username, email=email, password_hash=password_hash, session_cookie=session_cookie, session_expiry_datetime=expiry_time, role=default) db.session.add(user) db.session.commit() flash("Registration successful!", "success") msg = Message(subject="HelloWorld Blog - Registration successful", sender=SENDER, recipients=[email], bcc=[SENDER]) msg.body = f"Hi {username}!\n" \ f"Welcome to our WebDev Flask site!\n" \ f"Visit us: {HOST_ADDR}\n" \ f"Enjoy!" mail.send(msg) redirect_url = "/" response = make_response(redirect(redirect_url)) response.set_cookie(WEBSITE_LOGIN_COOKIE_NAME, session_cookie, httponly=True, samesite='Strict') return response elif request.method == "GET": return render_template("register.html")
def send_async_email(msg): mail.send(msg)
def send_async_email(app, msg): with app.app_context(): mail.send(msg)
def send_email(msg): mail.send(msg)
def send_mail(cls, title, body, to): msg = Message(title, recipients=[to], sender=config.DEFAULT_MAIL_SENDER) msg.html = body mail.send(msg)