def __init__(self, app): self.app = app self.setupConfiguration() self.mail = Mail(app) self.lookup = TemplateLookup(directories=['mail'], output_encoding='utf-8', encoding_errors='replace')
def _send_mail_to_admin(meeting, events, form, person_id): app = flask.current_app mail = Mail(app) recipients = [meeting.data['info_admin_email']] subject = u"%s registration for %s.%s %s" % ( meeting.data['info_description_E'], form.data['personal_name_title'], form.data['personal_first_name'], form.data['personal_last_name'], ) template = app.jinja_env.get_template('participant/form_for_admin.html') body = template.render({ 'meeting': meeting, 'events': events, 'person': form, 'categories': dict(form.personal_category.choices), 'countries': dict(form.personal_country.choices), 'languages': dict(form.personal_language.choices), 'person_id': person_id, 'config': app.config, }) msg = Message(subject, sender=meeting.data['info_admin_email'], recipients=recipients, html=body) mail.send(msg)
def test_participant_reg_mail_to_admin_category(self): """Certify 'Participation category' is shown as string not as dict key""" mail = Mail(self.app) with mail.record_messages() as outbox: data = dict(self.PERSON_DATA) data.pop('personal_fee', None) self.client.post('/meeting/1/participant/form', data=data) import xml.dom.minidom from xml.parsers.expat import ExpatError for message in outbox: try: dom = xml.dom.minidom.parseString(message.html) matching_rows = [item.parentNode for item in dom.getElementsByTagName('th') if item.firstChild.data == 'Participation category'] if matching_rows: category_value = matching_rows[0].childNodes[3].firstChild.nodeValue.strip() if str(category_value) == 'Member': break except ExpatError: continue else: self.fail('Participant category is not displayed correctly!')
def send_test_email(recipient): mail = Mail(app) msg = Message("Test Message -- Candidates Emailer app", [recipient], sender="*****@*****.**") msg.body = "This is a test message from the Candidates Emailer App" mail.send(msg)
def send_mail_to_admin(meeting, form, person_id): app = flask.current_app mail = Mail(app) sender = app.config["CITES_ADMIN"] recipients = [meeting.data['info_media_admin_email']] subject = u"%s Media accreditation for %s.%s %s" % ( meeting.data['info_description_E'], form.data['personal_name_title'], form.data['personal_first_name'], form.data['personal_last_name'], ) template = app.jinja_env.get_template('media_participants/form_for_admin.html') body = template.render({ 'meeting': meeting, 'person': form, 'categories': dict(form.personal_category.choices), 'countries': dict(form.personal_country.choices), 'attending_dates': dict(form.attending_dates.choices), 'person_id': person_id, 'config': app.config, }) msg = Message(subject, sender=sender, recipients=recipients, html=body) mail.send(msg)
def _send_mail_to_self_registering_participant(meeting, events, form, lang='en'): app = flask.current_app mail = Mail(app) lang = {"en": "E", "es": "S", "fr": "F"}.get(lang, "E") template = app.jinja_env.get_template('participant/self_registration_mail.html') recipients = [ email for email in form.data['personal_email'].split() if len(email)>3 ] phrases = {p.data['name']: p for p in meeting.get_phrases} body_html = template.render({ 'meeting': meeting, 'events': events, 'phrases': phrases, 'lang': lang, 'config': app.config, 'categories': dict(form.personal_category.choices), 'countries': dict(form.personal_country.choices), 'languages': dict(form.personal_language.choices), 'person': form, }) msg = Message(_(u'Registration for %(meeting)s', meeting=meeting.decoded_data['info_description_%s' % lang]), sender=meeting.decoded_data['info_admin_email'], recipients=recipients, html=body_html) mail.send(msg)
def test_send_mail(self): from flaskext.mail import Mail from flaskext.mail.signals import email_dispatched self._create_participant(u"10") # 10: "Member" mail = Mail(self.app) with mail.record_messages() as outbox: resp = self.client.post("/meeting/1/participant/1/send_mail", data=dict( to="*****@*****.**", subject="SC61 registration -- Acknowledgment", message="Hello world" )) self.assertEqual(len(outbox), 1) self.assertEqual(outbox[0].subject, "SC61 registration -- Acknowledgment") self.assertEqual(outbox[0].recipients, ["*****@*****.**"]) self.assertEqual(outbox[0].body, u"Hello world") self.assertEqual(outbox[0].sender, "*****@*****.**") self.assertEqual(outbox[0].attachments[0].content_type, "application/pdf") self.assertEqual(outbox[0].attachments[0].filename, "credentials.pdf")
def test_staff_new_admin_mail(self): mail = Mail(self.app) with mail.record_messages() as outbox: self.create_staff() self.assertEqual(1, len(outbox)) with mail.record_messages() as outbox: self.create_staff({'is_admin': '1'}) self.assertEqual(len(outbox), 1)
def reset_password(): email_to_reset_password = flask.request.form.get("email", "") if flask.request.method == "POST": try: staff_member = [i for i in database.find("staff", email=email_to_reset_password)] assert len(staff_member) == 1 staff_member = staff_member[0] except AssertionError: flask.flash(u"Your email does not exist in our database.", "error") else: auth_token = sugar.generate_token(email_to_reset_password) session = database.get_session() staff_row = database.get_or_404("staff", id=staff_member.id) staff_schema = StaffSchema.from_flat(staff_row) staff_schema["token"].set(auth_token) if staff_schema.validate(): staff_row.update(staff_schema.flatten()) session.save(staff_row) session.commit() app = flask.current_app mail = Mail(app) settings_url = app.config.get("HOSTNAME") mail_msg_link = "%s/%s/change-password" % (settings_url, auth_token) msg_subject = "Reset your Cites password" msg_sender = app.config.get("DEFAULT_MAIL_SENDER") msg_recipients = [email_to_reset_password] msg_body = str( "Forgot your password?\n\nCites received a request " "to reset the password for your account.\n" "If you want to reset your " "password, click on the link below (or copy and " "paste the URL into your browser):\n\n%s\n\nThis " "link takes you to a secure page where you can " "change your password.\nIf you don't want to " "reset your password, please ignore this " "message. Your password will not be reset." "\n\nThe Cites Team" % (mail_msg_link) ) msg = Message(msg_subject, sender=msg_sender, recipients=msg_recipients, body=msg_body) mail.send(msg) flash_message = str( "We've sent password reset instructions to your " "email address. Please also check your email's " "spam filter." ) flask.flash(flash_message, "success")
def _send_mail_to_user(staff_schema, password): app = flask.current_app mail = Mail(app) admin_email = app.config["CITES_ADMIN"] body = "You are now admin on Cites Meetings. Your password is %s" % password msg = Message("Cites Meetings Admin ", sender=admin_email, recipients=[staff_schema["email"].value], body=body) mail.send(msg)
def _send_mail_to_user(staff_schema, password): app = flask.current_app mail = Mail(app) admin_email = app.config["CITES_ADMIN"] body = "You have admin rights on %s. Your password is %s" % ( app.config["HOSTNAME"], password) msg = Message("Administration rights ", sender=admin_email, recipients=[staff_schema["email"].value], body=body) mail.send(msg)
def __init__(self, *args, **kwargs): kwargs['static_folder'] = config['TEMPLATES']['STATIC_DIR'] kwargs['static_url_path'] = '' super(RentMyBike, self).__init__(config['APPLICATION_NAME'], *args, **kwargs) self.debug = self.config['DEBUG'] self._register_error_handler(None, Exception, self.error_handler) self._register_error_handler(None, 500, self.error_handler) self.before_request(self.inject_csrf_token) self.teardown_request(self.session_cleanup) self.emailer = Mail() self.emailer.init_app(self) balanced.configure(self.config['BALANCED_SECRET']) self.marketplace_href = balanced.Marketplace.mine.href
def test_participant_registration_form_confirmation_mail(self): mail = Mail(self.app) with mail.record_messages() as outbox: data = dict(self.PERSON_DATA) data.pop('personal_fee', None) resp = self.client.post('/meeting/1/participant/form', data=data) for message in outbox: if message.recipients == [data['personal_email']]: break else: self.fail("No message was sent to participant.") self.assertEqual('*****@*****.**', message.sender) self.assertIn(self.MEETING_FORM_DATA['info_description_E'], message.subject) self.assertIn('Thank you for registering on line', message.html)
def run(self, testing): mail = Mail(app) for user, csv_reports in generate_reports(app.config["REPORTS_DIR"]): context = {"user": user} template = Template(app.config["EMAIL_TEXT_TEMPLATE"]) msg = Message(app.config["EMAIL_SUBJECT_LINE"], recipients=[user.alternate_email] if user.use_alternate_email else [user.email], sender=app.config["DEFAULT_MAIL_SENDER"]) msg.body = template.render(context) for csv_filename, csv_data in csv_reports: msg.attach(csv_filename, "text/csv", csv_data) if not testing: mail.send(msg) else: print msg.get_response().to_message().as_string()
class MailService(): def __init__(self, app): self.app = app self.setupConfiguration() self.mail = Mail(app) self.lookup = TemplateLookup(directories=['mail'], output_encoding='utf-8', encoding_errors='replace') def setupConfiguration(self): self.app.config['MAIL_USERNAME'] = "******" self.app.config['MAIL_PASSWORD'] = "******" self.app.config['DEFAULT_MAIL_SENDER'] = "enjoy-events" self.app.config['MAIL_SERVER'] = "smtp.gmail.com" self.app.config['MAIL_PORT'] = "465" self.app.config['MAIL_USE_SSL'] = True def createUser(self, user): msg = Message("Bienvenido a Enjoy-events", recipients=[user.email]) msg.html = self.lookup.get_template("registration.html").render( user=user) self.sendMail(msg) def assistance(self, assistance, user): msg = Message("Vas a asistir al evento %s" % assistance.event.name, recipients=[user.email]) msg.html = self.lookup.get_template("assistance.html").render( assistance=assistance) self.sendMail(msg) def sendMail(self, msg): try: @copy_current_request_context def sendMessage(self, msg): self.mail.send(msg) if self.app.config['SEND_EMAILS']: sender = threading.Thread(name='mailService', target=sendMessage, args=(self, msg)) sender.start() except Exception as err: print err
def resend_mail(mail_id): app = flask.current_app sent_mail = database.get_or_404('mail_log', mail_id) sent_mail_schema = schema.MailSchema.from_flat(sent_mail) if flask.request.method == 'POST': mail = Mail(app) meeting = schema.Meeting.get_or_404(sent_mail['meeting_id']) msg = Message(sent_mail['mail_subject'], sender=meeting['info']['admin_email'], recipients=[m.value for m in sent_mail_schema['to']], cc=[m.value for m in sent_mail_schema['cc']], body=sent_mail['mail_message']) mail.send(msg) if app.config['MAIL_SUPPRESS_SEND']: flask.flash(u'This is a demo, no real email was sent', 'info') else: flask.flash('Email resent.', 'success') return flask.redirect(flask.url_for('meeting.view_mail_log', meeting_id=sent_mail['meeting_id'], mail_log_id=mail_id))
def test_participant_registration_form_mail_to_admin(self): mail = Mail(self.app) with mail.record_messages() as outbox: data = dict(self.PERSON_DATA) data.pop('personal_fee', None) resp = self.client.post('/meeting/1/participant/form', data=data) for message in outbox: if message.recipients == ['*****@*****.**']: break else: self.fail('No message was sent to meeting admin.') ok_subject = '%s registration for %s.%s %s' % ( 'Some meeting For the Test', self.PERSON_DATA['personal_name_title'], self.PERSON_DATA['personal_first_name'], self.PERSON_DATA['personal_last_name']) self.assertEqual(message.subject, ok_subject) self.assertEqual(message.sender, '*****@*****.**')
def send_mail_to_media_participant(meeting, form, lang='en'): app = flask.current_app mail = Mail(app) lang = {"en": "E", "es": "S", "fr": "F"}.get(lang, "E") template = app.jinja_env.get_template('media_participants/form_for_participant.html') body_html = template.render({ 'meeting': meeting, 'lang': lang, 'config': app.config, 'categories': dict(form.personal_category.choices), 'countries': dict(form.personal_country.choices), 'attending_dates': dict(form.attending_dates.choices), 'person': form, }) msg = Message(_(u'Registration for %(meeting)s', meeting=meeting.decoded_data['info_description_%s' % lang]), sender=meeting.decoded_data['info_media_admin_email'], recipients=[form.data['personal_email']], html=body_html) mail.send(msg)
class MailService(): def __init__(self, app): self.app = app self.setupConfiguration() self.mail = Mail(app) self.lookup = TemplateLookup(directories=['mail'], output_encoding='utf-8', encoding_errors='replace') def setupConfiguration(self): self.app.config['MAIL_USERNAME'] = "******" self.app.config['MAIL_PASSWORD'] = "******" self.app.config['DEFAULT_MAIL_SENDER'] = "enjoy-events" self.app.config['MAIL_SERVER'] = "smtp.gmail.com" self.app.config['MAIL_PORT'] = "465" self.app.config['MAIL_USE_SSL'] = True def createUser(self, user): msg = Message("Bienvenido a Enjoy-events", recipients=[user.email]) msg.html = self.lookup.get_template("registration.html").render(user=user) self.sendMail(msg) def assistance(self, assistance, user): msg = Message("Vas a asistir al evento %s" % assistance.event.name, recipients=[user.email]) msg.html = self.lookup.get_template("assistance.html").render(assistance=assistance) self.sendMail(msg) def sendMail(self, msg): try: @copy_current_request_context def sendMessage(self, msg): self.mail.send(msg) if self.app.config['SEND_EMAILS']: sender = threading.Thread(name='mailService', target=sendMessage, args=(self, msg)) sender.start() except Exception as err: print err
def __init__(self, *args, **kwargs): kwargs['static_folder'] = config['TEMPLATES']['STATIC_DIR'] kwargs['static_url_path'] = '' super(RentMyBike, self).__init__(config['APPLICATION_NAME'], *args, **kwargs) self.debug = self.config['DEBUG'] self._register_error_handler(None, Exception, self.error_handler) self._register_error_handler(None, 500, self.error_handler) self.before_request(self.inject_csrf_token) self.teardown_request(self.session_cleanup) self.emailer = Mail() self.emailer.init_app(self) balanced.configure(self.config['BALANCED_SECRET']) self.marketplace_uri = balanced.Marketplace.mine.uri
#!/usr/bin/env python #coding=utf-8 from flaskext.mail import Mail from flaskext.sqlalchemy import SQLAlchemy from flaskext.cache import Cache from flaskext.uploads import UploadSet, IMAGES __all__ = ['mail', 'db', 'cache', 'photos'] mail = Mail() db = SQLAlchemy() cache = Cache() photos = UploadSet('photos', IMAGES)
from flask import Flask from flaskext.mail import Mail app = Flask(__name__) mail = Mail(app) mail = Mail() msg = mail("Hello", sender="*****@*****.**", recipients=["*****@*****.**"]) mail.send(msg)
from werkzeug import generate_password_hash, check_password_hash, UserAgent from flaskext.sqlalchemy import SQLAlchemy from flaskext.mail import Mail, Message from flaskext.wtf import Form, TextField, TextAreaField, PasswordField from flaskext.wtf import SelectField, Required, Email, ValidationError from pytz import utc, timezone from markdown import markdown import pygooglechart try: from greatape import MailChimp, MailChimpError except ImportError: MailChimp = None app = Flask(__name__) db = SQLAlchemy(app) mail = Mail() # --------------------------------------------------------------------------- # Static data USER_CATEGORIES = [ ('0', u'Unclassified'), ('1', u'Student or Trainee'), ('2', u'Developer'), ('3', u'Designer'), ('4', u'Manager, Senior Developer/Designer'), ('5', u'CTO, CIO, CEO'), ('6', u'Entrepreneur'), ] USER_CITIES = [
def environment(self): try: root = os.getcwd() environment = os.environ['ENVIRONMENT'] if environment == 'development': path = os.path.join(root, "config/development.cfg") self.app.config.from_pyfile(path) elif environment == 'production': path = os.path.join(root, "config/production.cfg") self.app.config.from_pyfile(path) elif environment == 'testing': path = os.path.join(root, "config/testing.cfg") self.app.config.from_pyfile(path) except KeyError: pass def App(self): return self.app def config(self): return self.app.config def db(self): db = MongoEngine(self.app) return db settings = Settings() db = settings.db() config = settings.config() mail = Mail(settings.App())
class RentMyBike(Flask): request_class = Request strict_slashes = False def __init__(self, *args, **kwargs): kwargs['static_folder'] = config['TEMPLATES']['STATIC_DIR'] kwargs['static_url_path'] = '' super(RentMyBike, self).__init__(config['APPLICATION_NAME'], *args, **kwargs) self.debug = self.config['DEBUG'] self._register_error_handler(None, Exception, self.error_handler) self._register_error_handler(None, 500, self.error_handler) self.before_request(self.inject_csrf_token) self.teardown_request(self.session_cleanup) self.emailer = Mail() self.emailer.init_app(self) balanced.configure(self.config['BALANCED_SECRET']) self.marketplace_href = balanced.Marketplace.mine.href def request_context(self, environ): ctx = super(RentMyBike, self).request_context(environ) ctx.g.url_adapter = ctx.url_adapter return ctx def make_config(self, instance_relative=False): return config def make_response(self, rv): if not rv: rv = Response('') elif not isinstance(rv, (BaseResponse, Exception)): template_name, payload = rv payload['marketplace_href'] = self.marketplace_href rv = render(template_name, request, **payload) return super(RentMyBike, self).make_response(rv) def dummy_email_generator( self, size=6, chars=string.ascii_letters + string.digits): return ''.join(random.choice(chars) for _ in range(size)) + \ '@gmail.com' def dummy_bank_account_generator(self, owner): bank_account = balanced.BankAccount( routing_number='121000358', account_type='checking', account_number='9900000001', name='Johann Bernoulli' ).save() bank_account.associate_to_customer(owner.balanced_customer.href) def add_dummy_data(self): user = User( name='Dummy User', email=self.dummy_email_generator(), password='******') Session.add(user) user.create_balanced_customer() for i in range(4): owner = User.fetch_one_at_random() if not user.balanced_customer.bank_accounts.count(): self.dummy_bank_account_generator(owner) listing = Listing.query.filter(Listing.id == i + 1).count() if not listing: listing = Listing(id=i + 1, owner_guid=owner.guid) Session.add(listing) Session.commit() def generate_csrf_token(self): return self.jinja_env.globals['csrf_token']() def inject_csrf_token(self): if request.method != 'POST' and '_csrf_token' not in session: session['_csrf_token'] = self.generate_csrf_token() def error_handler(self, ex): try: Session.rollback() except InterfaceError as ex: if not ex.connection_invalidated: logger.exception(ex) raise logger.exception(ex) ex_type = sys.exc_info()[0] ex_tb = sys.exc_info()[2] fmt_tb = traceback.format_exception(ex_type, ex, ex_tb) encoded_tb = [unicode(l, 'utf-8') for l in fmt_tb] tb = ''.join(encoded_tb) ex.traceback = tb response = render('error.mako', request, exception=ex, status_code=500) return response def session_cleanup(self, ex): try: Session.rollback() Session.expunge_all() Session.remove() except InterfaceError as ex: if not ex.connection_invalidated: logger.exception(ex) raise Session.close()
from flask import request from flask_sqlalchemy import SQLAlchemy from flaskext.babel import Babel from flaskext.cache import Cache from flaskext.mail import Mail from flaskext.script import Manager from flask_collect import Collect from .app import create_app babel = Babel() cache = Cache() db = SQLAlchemy() main = Mail() manager = Manager(create_app) manager.add_option("-c", "--config", dest="config", required=False) collect = Collect() collect.init_script(manager) def config_extensions(app): " Init application with extensions. " cache.init_app(app) db.init_app(app) main.init_app(app) collect.init_app(app)
def send_mail(meeting_id, person_id): app = flask.current_app meeting = sugar.get_object_or_404(models.Meeting, id=meeting_id) session = database.get_session() person = sugar.get_person_or_404(meeting_id, person_id) lang_code = person.decoded_data['personal_language'] or 'en' labeled = schema.labels_for_values(person.data, meeting_id, in_participant_language=True) category = person.category_model(meeting_id) cc_addresses = [] phrases = {p.data['name']: p for p in meeting.get_phrases} event_form = EventCitesForm(meeting_model=meeting, person=person) if flask.request.method == "POST": mail = Mail(app) form_data = flask.request.form.to_dict() if form_data['mail_to'].find(',') != -1: to_addresses = form_data['mail_to'].split(',') if form_data.get('mail_cc'): cc_addresses = form_data['mail_cc'].split(',') else: to_addresses = form_data["mail_to"].split(";") if form_data.get('mail_cc'): cc_addresses = form_data["mail_cc"].split(";") # populate schema with data from POST mail_schema = schema.MailSchema.from_flat(form_data) to_member_schema = mail_schema['to'].member_schema cc_member_schema = mail_schema['cc'].member_schema for address in to_addresses: mail_schema['to'].append(to_member_schema(address)) for address in cc_addresses: mail_schema['cc'].append(cc_member_schema(address)) if mail_schema.validate(): # flatten schema mail_data = {} mail_data.update(mail_schema.flatten()) mail_data['mail_to'] = to_addresses mail_data['mail_cc'] = cc_addresses # construct recipients from "to" recipients = mail_data['mail_to'] # send email msg = Message(mail_data['mail_subject'], sender = meeting.decoded_data['info_admin_email'], recipients=recipients, cc=mail_data['mail_cc'], body=mail_data['mail_message']) # render form in participant language participant_lang = {"E": "en", "S": "es", "F": "fr"}.get(person.lang, "E") sugar.set_lang(participant_lang) pdf = sugar.generate_pdf_from_html( flask.render_template('participant/credentials.html', **{ 'person': person, 'meeting': meeting, 'credentials_strings': refdata.credentials_strings, 'labeled': labeled, 'phrases': phrases, 'category': category, 'event_form': event_form, }) ) msg.attach('registration_details.pdf', 'application/pdf', pdf) mail.send(msg) # log mail mail_log_data = { 'date': date.today(), 'meeting_id': meeting.id, 'person_id': person_id, 'type': 'single_mail', } mail_log_data.update(mail_data) mail_log_schema = schema.MailLogSchema.from_flat(mail_log_data) if mail_log_schema.validate(): mail_log_row = database.new('mail_log') mail_log_row.update(mail_log_schema.flatten()) session.save(mail_log_row) session.commit() # update acknowledged date person.update_meeting_flags(meeting_id, { 'meeting_flags_acknowledged': str(datetime.now().replace( second=0, microsecond=0)) }) if app.config['MAIL_SUPPRESS_SEND']: flask.flash(u'This is a demo, no real email was sent', 'info') else: # flash a success message success_msg = u'Mail sent to %d recipients.' % ( len(to_addresses) + len(cc_addresses)) flask.flash(success_msg, 'success') return flask.redirect( flask.url_for('participant.send_mail', meeting_id=meeting_id, person_id=person_id)) else: flask.flash(u'Errors in mail information', 'error') else: # create a schema with default data mail_schema = schema.MailSchema({ 'to': [person.data['personal_email']], 'subject': phrases['EM_Subj'].decoded_data['description_%s' % lang_code], 'message': '\n\n\n%s' % phrases['Intro'].decoded_data['description_%s' % lang_code], }) return { 'mk': sugar.MarkupGenerator( app.jinja_env.get_template('widgets/widgets_mail.html') ), 'person': person, 'category': category, 'mail_schema': mail_schema, 'meeting': meeting, 'phrases': phrases, }
#-*-coding:utf8-*- from flaskext.mail import Mail from flask_mail import Message from application import app from threading import Thread mail = Mail(app) def send_async_email(app,msg): with app.app_context(): mail.send(msg) def sendmail(recipients, subject, message): msg = Message() msg.subject = subject msg.recipients = recipients msg.html = message msg.charset = 'utf-8' try: thread = Thread(target=send_async_email,args=[app,msg]) thread.start() except Exception,e: data = {"status": "fail", "error": "send email error"} return data return True
class RentMyBike(Flask): request_class = Request strict_slashes = False def __init__(self, *args, **kwargs): kwargs['static_folder'] = config['TEMPLATES']['STATIC_DIR'] kwargs['static_url_path'] = '' super(RentMyBike, self).__init__(config['APPLICATION_NAME'], *args, **kwargs) self.debug = self.config['DEBUG'] self._register_error_handler(None, Exception, self.error_handler) self._register_error_handler(None, 500, self.error_handler) self.before_request(self.inject_csrf_token) self.teardown_request(self.session_cleanup) self.emailer = Mail() self.emailer.init_app(self) balanced.configure(self.config['BALANCED_SECRET']) self.marketplace_uri = balanced.Marketplace.mine.uri def request_context(self, environ): ctx = super(RentMyBike, self).request_context(environ) ctx.g.url_adapter = ctx.url_adapter return ctx def make_config(self, instance_relative=False): return config def make_response(self, rv): if not rv: rv = Response('') elif not isinstance(rv, (BaseResponse, Exception)): template_name, payload = rv payload['marketplace_uri'] = self.marketplace_uri rv = render(template_name, request, **payload) return super(RentMyBike, self).make_response(rv) def add_dummy_data(self): for name, email, password in config['DEFAULT_USERS']: user = User.query.filter(User.email_address == email).count() if not user: user = User(name=name, email_address=email, password=password) Session.add(user) for i in range(4): listing = Listing.query.filter(Listing.id == i + 1).count() if not listing: listing = Listing(id=i + 1) Session.add(listing) Session.commit() def generate_csrf_token(self): return self.jinja_env.globals['csrf_token']() def inject_csrf_token(self): if request.method != 'POST' and '_csrf_token' not in session: session['_csrf_token'] = self.generate_csrf_token() def error_handler(self, ex): try: Session.rollback() except InterfaceError as ex: if not ex.connection_invalidated: logger.exception(ex) raise logger.exception(ex) ex_type = sys.exc_info()[0] ex_tb = sys.exc_info()[2] fmt_tb = traceback.format_exception(ex_type, ex, ex_tb) encoded_tb = [unicode(l, 'utf-8') for l in fmt_tb] tb = ''.join(encoded_tb) ex.traceback = tb response = render('error.mako', request, exception=ex, status_code=500) return response def session_cleanup(self, ex): try: Session.rollback() Session.expunge_all() Session.remove() except InterfaceError as ex: if not ex.connection_invalidated: logger.exception(ex) raise Session.close()
# -*- coding: utf-8 -*- """ Website server for geekup.in """ from flask import Flask from flaskext.assets import Environment, Bundle from flaskext.mail import Mail from coaster import configureapp from os import environ # First, make an app and config it app = Flask(__name__, instance_relative_config=True) configureapp(app, 'GEEKUP_ENV') mail = Mail() mail.init_app(app) assets = Environment(app) # Second, setup assets js = Bundle('js/libs/jquery-1.6.4.js', 'js/libs/jquery.form.js', 'js/scripts.js', filters='jsmin', output='js/packed.js') assets.register('js_all', js) # Third, after config, import the models and views
def send_mail(meeting_id): app = flask.current_app session = database.get_session() meeting = sugar.get_object_or_404(models.Meeting, id=meeting_id) all_categories = meeting.get_categories() if flask.request.method == 'POST': mail = Mail(app) initial_form_data = flask.request.form form_data = initial_form_data.to_dict() categories = initial_form_data.getlist('mail_categories') categories = map(int, categories) mail_schema = schema.BulkMailSchema.from_flat(form_data) mail_schema['categories'].set(categories) mail_schema.set_category_labels(all_categories) if mail_schema.validate(): mail_data = {} mail_data.update(mail_schema.flatten()) mail_data['mail_categories'] = categories lang = form_data['mail_to'] filters = { 'personal_language': lang } if not categories: persons = (models.Person.select().where(data__contains=filters)) persons = sugar.append_persons_query(persons, meeting_id) recipients = set([p.data['personal_email'] for p in persons if p.data.get('personal_email')]) else: persons = ( models.Person.select().where(data__contains=filters) .where(data_value_in('personal_category', map(str, categories))) ) persons = sugar.append_persons_query(persons, meeting_id) recipients = set([p.data['personal_email'] for p in persons if p.data.get('personal_email')]) with mail.connect() as conn: for person in recipients: msg = Message(mail_data['mail_subject'], sender=meeting.data['info_admin_email'], recipients=[person], body=mail_data['mail_message']) conn.send(msg) mail_log_data = { 'date': date.today(), 'meeting_id': meeting.id, 'type': 'bulk_mail', } mail_log_data.update(mail_data) mail_log_schema = schema.BulkMailLogSchema.from_flat(mail_log_data) mail_log_schema.set_category_labels(all_categories) if mail_log_schema.validate(): mail_log_row = database.new('mail_log') mail_log_row.update(mail_log_schema.flatten()) session.save(mail_log_row) session.commit() language = refdata.language.get(lang) if app.config['MAIL_SUPPRESS_SEND']: flask.flash(u'This is a demo, no real email was sent', 'info') else: success_msg = u'Mail sent to all %s speakers' % language flask.flash(success_msg, 'success') return flask.redirect(flask.url_for('meeting.send_mail', meeting_id=meeting.id)) else: flask.flash(u'Errors in mail information', 'error') else: mail_schema = schema.BulkMailSchema({}) mail_schema.set_category_labels(all_categories) return { 'mk': sugar.MarkupGenerator( app.jinja_env.get_template('widgets/widgets_mail.html') ), 'meeting': meeting, 'mail_schema': mail_schema, }
</tr> </tbody> </table> <hr style="margin: 3em 0;"/> <img src="{{ url_for('static', filename='img.png', _external=True) }}" /> {% endblock %} </body> </html> """ def create_pdf(pdf_data): pdf = StringIO() pisa.CreatePDF(StringIO(pdf_data.encode('utf-8')), pdf) return pdf mail_ext = Mail(app) @app.route('/your/url') def your_view(): subject = "Mail with PDF" receiver = "*****@*****.**" mail_to_be_sent = Message(subject=subject, recipients=[receiver]) mail_to_be_sent.body = "This email contains PDF." pdf = create_pdf(render_template('your/template.html')) mail_to_be_sent.attach("file.pdf", "application/pdf", pdf.getvalue()) mail_ext.send(mail_to_be_sent) return redirect(url_for('other_view'))
def send_mail(person_id): app = flask.current_app session = database.get_session() person = schema.Person.get_or_404(person_id) phrases = {item["id"]: item["name"] for item in schema._load_json("refdata/phrases.json")} if flask.request.method == "POST": mail = Mail(app) # populate schema with data from POST mail_schema = schema.MailSchema.from_flat(flask.request.form.to_dict()) if mail_schema.validate(): # flatten schema mail_data = {} mail_data.update(mail_schema.flatten()) # construct recipients from "to" recipients = [mail_data["to"]] # recipients = ["*****@*****.**"] # send email msg = Message(mail_data["subject"], sender="*****@*****.**", recipients=recipients, cc=[mail_data["cc"]], body=mail_data["message"]) pdf = sugar.generate_pdf_from_html( flask.render_template("participant/credentials.html", **{ "person": schema.Person.get_or_404(person_id), "meeting_description": MEETING_DESCRIPTION, "meeting_address": MEETING_ADDRESS, }) ) msg.attach("credentials.pdf", "application/pdf", pdf) mail.send(msg) if app.config["MAIL_SUPPRESS_SEND"]: flask.flash(u"This is a demo, no real email was sent", "info") else: # flash a success message success_msg = u"Mail sent to %s" % mail_data["to"] if mail_data["cc"]: success_msg += u" and to %s" % mail_data["cc"] flask.flash(success_msg, "success") else: flask.flash(u"Errors in mail information", "error") else: # create a schema with default data mail_schema = schema.MailSchema({ "to": person["personal"]["email"], "subject": phrases["EM_Subj"], "message": "\n\n\n%s" % phrases["Intro"], }) return { "mk": sugar.MarkupGenerator( app.jinja_env.get_template("widgets/widgets_mail.html") ), "person": person, "mail_schema": mail_schema, }