def send_email(path_to_file, recipient): app.logger.info("Preparing email...") # prepare email attachment # NOTE: when using the app context you automatically go into the app # folder and thus you need to remove the first part of the path with app.open_resource(str(Path(*path_to_file.parts[1:]))) as file: attachment = Attachment( filename=path_to_file.name, data=file.read(), content_type="application/vnd.ms-excel", ) # send email app.logger.info("Start sending email") with app.app_context(): mail.send_message( subject="Wordified file", sender=app.config["ADMINS"][0], recipients=[recipient], body= ("Dear user,\r\n\nPlease find attached your Wordified file. " "It contains two sheets: one with the positive indicators for " "each label and one with the negative indicators (note that if " "you have only two labels, the positive indicators of one label " "are the negative ones of the other, and vice versa).\r\nIf you " "do not see any indicators, you might have provided too few texts " "per label.\r\n\nYour Wordify Team"), attachments=[attachment], ) app.logger.info("Email sent") # delete file from memory path_to_file.unlink()
def registration_notice(sender, user, **extra): # site_url = 'https://%s' % app.config['NOI_DEPLOY'] # sender = app.config['MAIL_USERNAME'] sender = '*****@*****.**' mail.send_message( subject=gettext( "%(user)s registered on Network of " "Innovators!", user=user.full_name ), body=gettext( "%(user)s Created a new profile: " "\n\n" "\nName: %(user)s" "\nEmail: %(email)s" "\nPosition: %(position)s" "\nOrganization: %(organization)s" "\nOrganization Type: %(organization_type)s" "\nCountry: %(country)s" "\nCity: %(city)s" "\n\n", user=user.full_name, email=user.email, position=user.position, organization=user.organization, organization_type=user.organization_type, country=user.country, city=user.city ), sender=sender, recipients=["*****@*****.**", "*****@*****.**", "*****@*****.**"] )
def test_send_mail(self): with mail.record_messages() as outbox: mail.send_message(subject='testing', body='test', recipients=['*****@*****.**']) assert len(outbox) == 1 assert outbox[0].subject == "testing"
def post(self): """ purpose: Send email to inbox for contact purposes Send email to user thanking them for their feedback parameters: Name Email Subject Message return: HTTP 400 - Error occured HTTP 200 - Successful """ # Get JSON data json_data = req.get_json(force=False) print(json_data) if not json_data: return HTTPHandler.no_data() # Load contact data if possible try: data = contactSchema.load(json_data) except ValidationError as e: return HTTPHandler.improper_data(e) contact_failed = False # Send message confirming contact try: mail.send_message(subject='SafeWalk - Message Received', sender='*****@*****.**', recipients=[data['email']], body=create_user_message(data['name'], data['email'], data['subject'], data['message'])) except Exception as e: contact_failed = True print(e) # If contact to user did not fail, forward message to safewalks account if not contact_failed: try: mail.send_message(subject='SafeWalk - New Message', sender='*****@*****.**', recipients=['*****@*****.**'], body=create_account_message( data['name'], data['email'], data['subject'], data['message'])) except Exception as e: print(e) #[email protected] #walksafe1119! return HTTPHandler.valid()
def login(): login_form = LoginForm() register_form = RegisterForm() if login_form.validate_on_submit(): username = login_form.username.data password = login_form.password.data remember_me = login_form.remember_me.data user = User.query.filter( func.lower(User.username) == func.lower(username)).first() if login_user(user, remember_me): flash("You were logged in.", "success") if user.invitations.count(): flash( Markup( 'You have %s team invitations - click <a href="%s">here</a> to view them.' % (user.invitations.count(), url_for("invitations"))), "info") return redirect(request.args.get("next") or url_for('index')) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) else: flash("Login failed, user not validated", "error") return redirect(url_for("verify_status", username=username)) elif register_form.validate_on_submit(): username = register_form.username.data.strip() password = register_form.password.data email = register_form.email.data new_user = User(username, password, email) body = render_template("verification.txt", recipient=new_user, email_changed=False) mail.send_message(subject="Welcome to " + app.config["LONG_NAME"] + ", " + username, recipients=[new_user.email], body=body) db.session.add(new_user) db.session.commit() flash("Your account has been created, confirm your email to verify.", "success") return redirect(url_for('verify_status', username=username)) return render_template('login.html', login_form=login_form, register_form=register_form)
def send_signup_message(user, token): url = url_for('users.confirm_registeration', email=user.email, token=token, _external=True) sender = '*****@*****.**' recipients = [user.email] subject = 'Flask Blog - Registeration Confirm' body = f'Hello,<br>Open this URL: {url}.' mail.send_message(sender=sender, recipients=recipients, subject=subject, html=body)
def contact_us(): if(request.method=='POST'): name = request.form.get('name') email = request.form.get('email') phone = request.form.get('phone') message = request.form.get('message') entry = Contacts(name=name, phone_num = phone, msg = message, date= datetime.now(),email = email ) db.session.add(entry) db.session.commit() flash('Data Saved Successfully') mail.send_message('New message from ' + name, sender=email, recipients = [params['gmail-user']], body = message + "\n" + phone ) return render_template('contactUs.html', params=params)
def verify_send(): if request.method == 'GET': return redirect(url_for('index')) username = request.form.get('username', "") user = User.query.filter_by(username = username).first_or_404() if user.is_verified: flash("%s's account is already validated." % user.username.capitalize(), "info") return redirect(url_for('index')) body=render_template("emails/account/verification.txt", recipient=user) mail.send_message(subject="Welcome to " + app.config["LONG_NAME"] + ", " + username, recipients=[user.new_email], body=body) flash("Verification has been resent, check your email", "success") return redirect(url_for('verify_status', username=username))
def reset_request(): if current_user.is_authenticated(): flash("You are already logged in.", "info") return redirect(url_for("index")) error = None form = RecoveryForm() if form.validate_on_submit(): # thanks to the UsernameValidator we cam assume the username exists user = User.query.filter_by(username=form.username.data).first() user.token = randint(0, sys.maxint) db.session.commit() body = render_template("emails/account/reset_password.txt", recipient=user) mail.send_message(subject=app.config["LONG_NAME"] + ": Reset your password", recipients=[user.email], body=body) flash("Your password has been reset, check your email.", "success") return render_template('account/reset_request.html', form=form, error=error)
def add_comment(post_id, parent_id=None): post = Post.query.get_or_404(post_id) post.permissions.view.test(403) parent = Comment.query.get_or_404(parent_id) if parent_id else None #user = User.query.first() form = CommentForm() if form.validate_on_submit(): comment = Comment(post=post, parent=parent, author=current_user) form.populate_obj(comment) comment.save() post.num_comments += 1 post.save() save_action(u"评论了条目 " + u'"' + post.title + u'"' ) #comment_added.send() flash(u"谢谢你的评论", "successfully") author = parent.author if parent else post.author if author.email_alerts and author.id != current_user.id: if setting.MAIL_ENABLE: subject = u"有人回复了你的评论" if parent else \ u"有人给你的提交添加了评论" template = "emails/comment_replied.html" if parent else \ "emails/post_commented.html" body = render_template(template, author=author, post=post, parent=parent, comment=comment) mail.send_message(subject=subject, body=body, recipients=[post.author.email]) flash(u"谢谢,你的邮件已发出", "successfully") else: flash(u"邮件服务器未开启,请联系管理员", "error") return redirect(comment.url) return render_template("post/add_comment.html", parent=parent, post=post, form=form)
def send_error_email(error, recipient): with app.app_context(): mail.send_message( subject="Wordify: Sorry, something went wrong", sender=app.config["ADMINS"][0], recipients=[recipient], body= ("Sorry, something went wrong while wordifying your file. The " "administrators have been notified and the problem will be solved " "as soon as possible."), ) mail.send_message( subject="Wordify: Exception", sender=app.config["ADMINS"][0], recipients=[app.config["ADMINS"][0], app.config["ADMINS"][1]], body="{}\n{}".format(error.__doc__, error), )
def add_comment(post_id, parent_id=None): post = Post.query.get_or_404(post_id) post.permissions.view.test(403) parent = Comment.query.get_or_404(parent_id) if parent_id else None #user = User.query.first() form = CommentForm() if form.validate_on_submit(): comment = Comment(post=post, parent=parent, author=current_user) form.populate_obj(comment) comment.save() post.num_comments += 1 post.save() save_action(u"评论了条目 " + u'"' + post.title + u'"') #comment_added.send() flash(u"谢谢你的评论", "successfully") author = parent.author if parent else post.author if author.email_alerts and author.id != current_user.id: if setting.MAIL_ENABLE: subject = u"有人回复了你的评论" if parent else \ u"有人给你的提交添加了评论" template = "emails/comment_replied.html" if parent else \ "emails/post_commented.html" body = render_template(template, author=author, post=post, parent=parent, comment=comment) mail.send_message(subject=subject, body=body, recipients=[post.author.email]) flash(u"谢谢,你的邮件已发出", "successfully") else: flash(u"邮件服务器未开启,请联系管理员", "error") return redirect(comment.url) return render_template("post/add_comment.html", parent=parent, post=post, form=form)
def test_sendMail(self): with mail.record_messages() as outbox: mail_event = self.initial_emailEvent() # add email_addresses nums = random.randint(1, 10) self.add_emailAddress(email_group_id=mail_event.email_group_id, nums=nums) email_subject = mail_event.email_subject email_content = mail_event.email_content recipients = self.get_address_from_emailEvent(mail_event) mail.send_message(subject=email_subject, recipients=recipients, body=email_content, sender="*****@*****.**") self.assertEqual(len(outbox[0].recipients), len(recipients)) self.assertEqual(outbox[0].subject, email_subject) self.assertEqual(outbox[0].body, email_content)
def verify_send(): if request.method == 'GET': return redirect(url_for('index')) username = request.form.get('username', "") user = User.query.filter_by(username=username).first_or_404() if user.is_verified: flash( "%s's account is already validated." % user.username.capitalize(), "info") return redirect(url_for('index')) body = render_template("emails/account/verification.txt", recipient=user) mail.send_message(subject="Welcome to " + app.config["LONG_NAME"] + ", " + username, recipients=[user.new_email], body=body) flash("Verification has been resent, check your email", "success") return redirect(url_for('verify_status', username=username))
def login(): login_form = LoginForm() register_form = RegisterForm() if login_form.validate_on_submit(): username = login_form.username.data password = login_form.password.data remember_me = login_form.remember_me.data user = User.query.filter(func.lower(User.username) == func.lower(username)).first() if login_user(user, remember_me): flash("You were logged in.", "success") if user.invitations.count(): flash(Markup('You have %s team invitations - click <a href="%s">here</a> to view them.' % (user.invitations.count(), url_for("invitations"))), "info") return redirect(request.args.get("next") or url_for('index')) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) else: flash("Login failed, user not validated", "error") return redirect(url_for("verify_status", username=username)) elif register_form.validate_on_submit(): username = register_form.username.data.strip() password = register_form.password.data email = register_form.email.data new_user = User(username, password, email) body = render_template("verification.txt", recipient = new_user, email_changed = False) mail.send_message(subject="Welcome to " + app.config["LONG_NAME"] + ", " + username, recipients=[new_user.email], body=body) db.session.add(new_user) db.session.commit() flash("Your account has been created, confirm your email to verify.", "success") return redirect(url_for('verify_status', username = username)) return render_template('login.html', login_form = login_form, register_form = register_form)
def invite(): """ Invite another human to join the site. """ form = InviteForm() if request.method == "POST": if form.validate(): site_url = "https://%s" % current_app.config["NOI_DEPLOY"] sender = current_app.config["MAIL_USERNAME"] mail.send_message( subject=gettext("%(user)s would like you to join the network!", user=current_user.full_name), body=gettext("Just visit %(url)s.", url=site_url), sender=sender, recipients=[form.email.data], ) flash(gettext("Invitation sent!")) return redirect(url_for("views.invite")) else: flash(gettext("Your form submission was invalid."), "error") return render_template("invite.html", form=form)
def invite(): ''' Invite another human to join the site. ''' form = InviteForm() if request.method == 'POST': if form.validate(): site_url = 'https://%s' % current_app.config['NOI_DEPLOY'] sender = current_app.config['MAIL_USERNAME'] mail.send_message( subject=gettext( "%(user)s would like you to join the Network of " "Innovators!", user=current_user.full_name, ), body=gettext( "%(user)s has invited you to join the " "Network of Innovators -- a new skill-sharing network " "for government and civic innovators worldwide.\n\n" "Join today. It's FREE. And in just a few minutes, " "you can get matched with innovators from around the " "world.\n\n" "Build your network now at %(url)s.", user=current_user.full_name, url=site_url, ), sender=sender, recipients=[form.email.data] ) flash(gettext("Invitation sent!")) return redirect(url_for('views.invite')) else: flash(gettext("Your form submission was invalid."), "error") return render_template('invite.html', form=form)
def test_send_message(): with app.app_context(): success, mes = mail.send_message( [("Bill Leddy", '*****@*****.**')], body="This is a test", subject="Simple Test") assert success == True assert "sent successfully" in mes # try sending with the name and addres in the wrong order success, mes = mail.send_message( [('*****@*****.**', "Bill Leddy")], body="This is a test with name and address params reversed", subject="Reversed address Test") assert success == True assert "sent successfully" in mes # try address only success, mes = mail.send_message(["*****@*****.**"], body="Address only test test", subject="Address Test") assert success == True assert "sent successfully" in mes #try sending to a group success, mes = mail.send_message( [("bill Leddy", '*****@*****.**'), ('*****@*****.**')], body="This is a group email", subject="Group Email") assert success == True assert "sent successfully" in mes success, mes = mail.send_message() assert success == False assert mes == "No message body was specified"
def run_async(self): """Send the mail asynchronously.""" try: with self.app_obj.app_context(): # algo = Mace( # inputfile=self.inputs.inputfile, # priors=self.inputs.priors, # controls=self.inputs.controls, # alpha=self.inputs.alpha, # beta=self.inputs.beta, # em=self.inputs.em, # iterations=self.inputs.iterations, # restarts=self.inputs.restarts, # threshold=self.inputs.threshold, # smoothing=self.inputs.smoothing, # ) # algo.fit() algo = self.logger.info("Mace finished") report = MaceReporter(algo) attachment = self.prepare_attachment(report) email = self.prepare_email(attachment) self.logger.info("Email prepared") mail.send(email) self.logger.info("Email sent") # delete file from memory os.remove(path) self.logger.info("Attachement removed from disk") except Exception as e: with self.app_obj.app_context(): mail.send_message( subject='Mace: Sorry, something went wrong', sender=app.config['ADMINS'][0], recipients=[self.inputs['email']], body=( """ Dear user, Sorry, something went wrong while wordifying your file. The administrators have been notified and the problem will be solved as soon as possible. Your MilaNLP Team """ ) ) mail.send_message( subject='Wordify: Exception', sender=app.config['ADMINS'][0], recipients=[app.config['ADMINS'] [0], app.config['ADMINS'][1]], body='{}\n{}'.format(e.__doc__, e) )
def get(self): mail.send_message('Send Mail tutorial!', sender='*****@*****.**', recipients=['*****@*****.**'], body="Congratulations you've succeeded!") return 'Mail sent'