def register_model(form): user = User(username=form.username.data, email=form.email.data) lib = Libraries(name=form.username.data + '\'s Library', owner=form.username.data) user.set_password(form.password.data) msg = Message('Registration conformation', sender='*****@*****.**', recipients=[form.email.data]) msg.body = "Please click link below to finish registration:" token = ''.join(random.choice('0123456789ABCDEF') for i in range(16)) registration = Registrations(username=form.username.data, token=token, date=str(datetime.now())) db.session.add(registration) msg = Message('Registration confirmation', sender=app.config['ADMINS'][0], recipients=['*****@*****.**']) msg.body = 'Click following link to finish registration: http://127.0.0.1:5000/activate?token=' + token msg.html = '<h1>Registration</h1>' \ '<p>Click following link to finish registration: <a href=http://127.0.0.1:5000/activate?token=' + token + '>Activation link</a></p>' mail.connect() mail.send(msg) mail.send(msg) db.session.add(lib) db.session.add(user) db.session.commit() user.libraries.append(lib) db.session.commit() flash('Congratulations, you are now a registered user!')
def send_async_email(msg): '''send an email in another thread, see decorators.py arg: msg - the Message object to send ''' with app.app_context(): mail.connect() mail.send(msg)
def send_mail(self): """ send an email to receiver """ message = Message(recipients=[self.receiver], subject=self.subject, body=self.body) with apps.app_context(): mail.connect() mail.send(message)
def daily_email_sends(): # query all with subscribed=True subs = Subscribers.query.filter_by(subscribed=True) song, date = phishnet_api.get_random_jamchart() jam_url = phishin_api.get_song_url(song=song, date=date) relisten_formatted_date = datetime.datetime.strptime( date, "%Y-%m-%d").strftime("%Y/%m/%d") phishnet_url = phishnet_api.get_show_url(date) with app.app_context(): with mail.connect() as conn: for subscriber in subs: msg = Message( subject="Daily Phish Jam", sender=os.getenv("SENDGRID_MAIL_SENDER"), recipients=[subscriber.email], ) msg.html = render_template( "random_jam_email.html", song=song, date=date, jam_url=jam_url, relisten_formatted_date=relisten_formatted_date, phishnet_url=phishnet_url, web_url=os.getenv("WEB_URL"), ) conn.send(msg) return "Mail sent"
def send_email(subscribed, rapper_name, post_url): with mail.connect() as conn: for user in subscribed: subject = generate_subject(rapper_name) html = generate_html(rapper_name, post_url) msg = Message(recipients=[user.email], html=html, subject=subject) conn.send(msg)
def send_email_to_user(user, subject, message): with mail.connect() as conn: message = message subject = subject msg = Message(recipients=[user.email], sender="*****@*****.**", html = message, subject = subject) conn.send(msg) return "Sent"
def sendTomorrow(): workers = Worker.query.all() boss = Worker.query.filter_by(role='Manager').first() hour_start = 2 #time for 06:00-08:59 with mail.connect() as conn: for worker in workers: tomorrow_forecast = forecaster(worker.city, worker.state, worker.country, hour_start) if tomorrow_forecast[1] == 'Rain': #forecast for tomorrow if worker.role == "IT": message = "Do not go on the road tomorrow\n\n\n\nRegards,\n {} {}".format( boss.fname, boss.lname) else: message = "You are going to work for 4 hours tomorrow instead of 8 hours\n\n\n\nRegards,\n {} {}".format( boss.fname, boss.lname) else: if worker.role == "IT": message = "Have fun at work tomorrow!\n\n\n\nRegards,\n {} {}".format( boss.fname, boss.lname) else: message = "You will be working for 8 hours tomorrow\n\n\n\nRegards,\n {} {}".format( boss.fname, boss.lname) subject = "Work for tomorrow, Mr.%s" % worker.lname msg = Message(recipients=[worker.email], sender=app.config.get("MAIL_USERNAME"), body=message, subject=subject) conn.send(msg) flash('Email notification sent to all workers!', 'success') return redirect(url_for('home'))
def send_mails(message, recipients): subject = 'Notification from postman' with mail.connect() as conn: for user in recipients: msg = Message(recipients=[user.email], body=message, subject=subject) conn.send(msg)
def sendbulk(message, subject, users): with mail.connect() as conn: for user in users: msg = Message(recipients=[user.email], body=message, subject=subject, sender=app.config['MAIL_USERNAME']) conn.send(msg)
def send_mail_to_staff(cls, _subject, _body): staffs = cls.query.all() with mail.connect() as conn: for staff in staffs: msg = Message( rsubject=_subject, body=_body, ecipients=[staff.email] ) conn.send(msg)
def send_routing_message(from_email, to_email, company_name, routes, company): with mail.connect() as conn: msg = Message("New pickup route!", sender=from_email, recipients=[to_email]) Mailer.inject_garbage_routing_html(msg, company_name, routes, company) conn.send(msg)
def send_bulk_email(subject, sender, recipients, text_body, html_body): with mail.connect() as conn: for i,r in enumerate(recipients): msg = Message(subject, sender=sender, recipients=[recipients[i]]) msg.body = text_body[i] msg.html = html_body[i] Thread(target=send_async_email, args=(current_app._get_current_object(), msg)).start()
def send_mail(subject, sender, recipients, message): with mail.connect() as conn: for user in recipients: msg = Message(recipients=[user], html=message, sender=sender, subject=subject) conn.send(msg) return True
def orders(): orderByUser = cart.query.filter( cart.user_id == session['user']['id']).all() user_order = Orders(user_id=session['user']['id']) db.session.add(user_order) db.session.commit() ord = Orders.query.all() for newOrder in orderByUser: amounts = newOrder.qty * newOrder.priceItem delete = cart.query.filter( cart.user_id == session['user']['id']).first() db.session.delete(delete) for i in ord: k = orderItems(product=newOrder.product_id, qty=newOrder.qty, price=newOrder.priceItem, amount=amounts, order_id=i.id) db.session.add(k) db.session.commit() mail_user = users.query.filter(users.id == session['user']['id']).all() with mail.connect() as conn: for us in mail_user: order_id = orderItems.query.filter( Orders.id == orderItems.order_id).order_by( Orders.id.desc()).first() orderByus = Orders.query.filter( db.and_(Orders.id == orderItems.order_id, Orders.user_id == session['user']['id'])).all() prodName = Product.query.filter( Product.id == orderItems.product).first() for byUs in orderByus: orderItemsByUser = orderItems.query.filter( db.and_(Orders.id == orderItems.order_id, Orders.user_id == session['user']['id'])).all() for itemsByuser in orderItemsByUser: message = 'This is your purchase' + '<br>' + 'name: ' + str(byUs.id) + '<br>' \ 'qty:' + str( itemsByuser.qty) + '<br>' \ 'price:' + str(itemsByuser.price) + '$' + '<br>' \ 'Amount:' + str( itemsByuser.amount) + '$' + '<br>' subject = "Your Purchase %s" % us.username msg = Message(recipients=[us.email], html=message, subject=subject) conn.send(msg) return redirect(url_for('shopping_cart'))
def mailinglist_email(subject, body): users = User.query.filter_by(is_subscribed=True).all() with mail.connect() as conn: for user in users: msg = Message(recipients=[user.email], sender="*****@*****.**", html=body, subject=subject) conn.send(msg) return "Sent"
def send_email(subject, sender, recipients, text_body, html_body, attachments=None, sync=False): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body if attachments: for attachment in attachments: msg.attach(*attachment) if sync: mail.connect() mail.send(msg) else: Thread(target=send_async_mail, args=(current_app._get_current_object(), msg)).start()
def send_mail(messages): with app.app_context(): with mail.connect() as conn: for msg in messages: m = Message(recipients=msg['recipient'], subject=msg['subject'], body=msg['body']) conn.send(m)
def send_results(session): # for each email, send session data with mail.connect() as conn: for email in session['emails']: print(f"Sending results to {email}") html = render_template('results.html', session=session) text = f'Your brainstorm results are in.\n' text += f"{session['title']}\n {session['description']}" text += '----\n'.join([post for post in session['posts']]) text += 'Thanks for using Timed Brainstorm!' subject = "Your brainstorm results" msg = build_message(subject, sender, [email], text, html) conn.send(msg)
def send_emails(emails): with mail.connect() as conn: for e in emails: try: msg = Message(recipients=e['recipients'], html=e['html'], body=e['body'], subject=e['subject']) conn.send(msg) except SMTPRecipientsRefused: error = 'Kon niet de mail "{}" versturen naar {}'.format( e['subject'], e['recipients']) app.logger.info(error) flash(error)
def addpost(): if not g.admin: return redirect(url_for('login')) posts = Post.query.all() if request.method == 'POST': title = request.form['title'] article = request.form['article'] for check_title in posts: if title == check_title.title: flash('Title already present chose a different title!', "danger") return redirect(url_for('addpost')) image = request.files['image'] if image.filename == '': flash('File must have name!', "warning") return redirect(url_for('addpost')) if allowed_image(image.filename): image_name = secure_filename(image.filename) new_post = Post(title=title.lower(), image=image.read(), image_name=image_name, article=article) db.session.add(new_post) db.session.commit() post = Post.query.filter_by(title=title).first() subscribers = Subscriber.query.all() if subscribers: html_body = render_template('owner/send_mail.html', post=post) with mail.connect() as conn: for sub in subscribers: msg = Message(subject='Hi There', recipients=[sub.email]) msg.html = html_body conn.send(msg) flash('Post successfully added!', "success") return redirect(url_for('addpost')) query = request.args.get('query') if query: search_post = Post.query.filter(Post.title.contains(query)).all() return render_template('owner/owner_search_post.html', title='Search Result', search_post=search_post, query=query) return render_template('owner/owner_addpost.html', title='Add Post', post=None)
def send_garbage_request(from_email, company_name, latitude, longitude, company_id, req_id, location_details): with mail.connect() as conn: msg = Message("New Garbage can request", sender=from_email, recipients=[ "*****@*****.**", "*****@*****.**" ]) Mailer.inject_garbage_request_html(msg, company_name, latitude, longitude, company_id, req_id, location_details) conn.send(msg)
def send_updates(item): from app import mail followers = item.followers if len(followers) > 0: # used to send mail in bulk # keeps the mail object connected until all messages are sent with mail.connect() as conn: for follower in followers: message = Message("Nontrivial Item Listing Alert", sender=os.environ.get('FLASKEMAIL'), recipients=[follower.email]) # open a file and attach to message with current_app.open_resource("templates/mail/new_listing.html") as fp: message.attach("new_listing.html","text/html", fp.read()) message.html = render_template('mail/new_listing.html', user=follower, item=item, link=url_for('listings.view_item', item_id=item.id)) conn.send(message) # not mail.send(message)
def send_email(subject, sender, recipients, text_body, html_body, attachment=False, mimetype=None, bulk=False): if bulk: with mail.connect() as conn: for recipient in recipients: msg = Message(subject, sender=sender, recipients=[recipient]) msg.body = text_body msg.html = html_body conn.send(msg) else: msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body if attachment: with app.open_resource(attachment) as fp: msg.attach(attachment[(attachment.rindex('/')+1):], mimetype, fp.read()) mail.send(msg)
def flush_pending(app): while True: time.sleep(app.config['MAIL_FLUSH_INTERVAL']) now = datetime.utcnow() with app.app_context(): emails = PendingEmail.query.filter(PendingEmail.timestamp < now) if emails.count() > 0: with mail.connect() as conn: for email in emails.all(): conn.send( get_notification_email(email.name, email.email, email.subject, email.body_text, email.body_html)) db.session.delete(email) db.session.commit()
def send_reminder_email(): flights = get_booked_flights() if not flights: logging.info("There are no bookings for tommorrow flights yet") else: logging.info("creating the mailing lists ...") messages = create_message_list(flights) logging.info("connecting to the mail server ...") with mail.connect() as conn: for message in messages: try: conn.send(message) "sending success: " + message.recipients except Exception as e: logging.exception("sending failed: " + message.recipients)
def post(self): args = password_recovery_parser.parse_args() user = User.query.filter_by(email=args.email).first() if not user: return abort(400, message='This user does does not exist.') user.recovery_code = uuid.uuid4().hex user.recovery_code_expiration = (datetime.datetime.now() + datetime.timedelta(hours=3)) db.session.commit() with mail.connect() as conn: # Send Email msg = MailMessage("Cambiar contraseña", sender=("mail", "*****@*****.**")) msg.add_recipient(user.email) msg.html = render_template("email/pass_recovery.html", user=user) conn.send(msg) return {'success': 1}
def mailall(): """Sends an email to all users""" form = MailAllForm() if form.validate_on_submit(): subject = request.values["subject"] message = request.values["message"] from_address = setting.ADMIN_MAIL with mail.connect() as conn: if setting.MAIL_ENABLE: for user in User.query: message = Message(subject=subject, body=message, sender=from_address, recipients=[user.email]) conn.send(message) flash(u"邮件已发出", "successfully") else: flash(u"邮件服务器未开启,请联系管理员", "error") return render_template("admin/mailall.html", form = form)
def forgot_password(): token = request.args.get('token') form = ResetPassword() if form.validate_on_submit(): email = form.email.data user = User.query.filter_by(email=email).first() if user: token = user.get_token() print("HERE'S THE OUL TOKEN LOVE", token) link_for_token = "<a href=\"http://*****:*****@gmail.com", html=message, subject=subject) conn.send(msg) flash("Email has been sent!") else: flash("No such user in the database") token = request.args.get('token') verified_result = User.verify_token(token) if token and verified_result: is_verified_token = True form = ResetPasswordSubmit() if form.validate_on_submit(): verified_result.password = form.password.data verified_result.is_subscribed = verified_result.is_subscribed db.session.commit() flash("Password updated successfully") return redirect(url_for('auth.login')) return render_template('auth/reset.html', form=form, title='Reset')
def sendAll(): workers = Worker.query.all() boss = Worker.query.filter_by(role='Manager').first() hour_start = 2 #time for 06:00-08:59 with mail.connect() as conn: for worker in workers: loadDays = getDays() loadDays.pop(0) forecasts = forecaster(worker.city, worker.state, worker.country, hour_start) forecasts.pop(0) outputs = zip(forecasts, loadDays) for output in outputs: if output[0] == 'Rain': #forecast for tomorrow if worker.role == "IT": message = "Do not go on the road {}\n\n\n\nRegards,\n {} {}".format( output[1], boss.fname, boss.lname) else: message = "You are going to work for 4 hours on {} instead of 8 hours\n\n\n\nRegards,\n {} {}".format( output[1], boss.fname, boss.lname) else: if worker.role == "IT": message = "Have fun at work {}!\n\n\n\nRegards,\n {} {}".format( output[1], boss.fname, boss.lname) else: message = "You will be working for 8 hours {}\n\n\n\nRegards,\n {} {}".format( output[1], boss.fname, boss.lname) subject = "Work for {}, Mr.{}".format(output[1], worker.lname) msg = Message(recipients=[worker.email], sender=app.config.get("MAIL_USERNAME"), body=message, subject=subject) conn.send(msg) flash('Email notification for the 4 days sent to all workers!', 'success') return redirect(url_for('home'))
def send_email(subject, sender, recipients, text_body, html_body, attachment=False, mimetype=None, bulk=False): if bulk: with mail.connect() as conn: for recipient in recipients: msg = Message(subject, sender=sender, recipients=[recipient]) msg.body = text_body msg.html = html_body conn.send(msg) else: msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body if attachment: with app.open_resource(attachment) as fp: msg.attach(attachment[(attachment.rindex('/') + 1):], mimetype, fp.read()) mail.send(msg)
def send_async_email(app, msg): with app.app_context(): mail.connect() mail.send(msg)
def send_async_email(message): with mail.connect() as conn: with app.app_context(): conn.send(message)
def send_async_emails(msg_dicts): with mail.connect() as conn: for msg_dict in msg_dicts: msg = Message() msg.__dict__.update(msg_dict) conn.send(msg)