Ejemplo n.º 1
0
def _send_login_email(user, uri):
    global _smtp
    if not _smtp:
        if not (pkconfig.channel_in('dev')
                and cfg.smtp_server == _DEV_SMTP_SERVER):
            a = sirepo.util.flask_app()
            a.config.update(
                MAIL_USE_TLS=True,
                MAIL_PORT=587,
                MAIL_SERVER=cfg.smtp_server,
                MAIL_USERNAME=cfg.smtp_user,
                MAIL_PASSWORD=cfg.smtp_password,
            )
            _smtp = flask_mail.Mail(a)
        else:
            pkdlog('{}', uri)
            return http_reply.gen_json_ok({'uri': uri})
    login_text = u'sign in to' if user.user_name else \
        u'confirm your email and finish creating'
    msg = flask_mail.Message(subject='Sign in to Sirepo',
                             sender=(cfg.from_name, cfg.from_email),
                             recipients=[user.unverified_email],
                             body=u'''
Click the link below to {} your Sirepo account.

This link will expire in {} hours and can only be used once.

{}
'''.format(login_text, _EXPIRES_MINUTES / 60, uri))
    _smtp.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 2
0
def api_comsolRegister():
    import flask
    import flask_mail
    import sirepo.util

    global _mail
    if not _mail:
        a = sirepo.util.flask_app()
        a.config.update(
            MAIL_USE_TLS=True,
            MAIL_PORT=587,
            MAIL_SERVER=cfg.mail_server,
            MAIL_USERNAME=cfg.mail_username,
            MAIL_PASSWORD=cfg.mail_password,
        )
        _mail = flask_mail.Mail(a)
    req = http_request.parse_json()
    msg = flask_mail.Message(
        subject='Sirepo / COMSOL Registration',
        sender=cfg.mail_support_email,
        recipients=[cfg.mail_recipient_email],
        body=u'''
Request for access to Sirepo / COMSOL.

Name: {}
Email: {}
'''.format(req.name, req.email),
    )
    _mail.send(msg)
    return http_reply.gen_json_ok()
Ejemplo n.º 3
0
Archivo: ext.py Proyecto: mardix/Mocha
    def init_app(self, app):
        self.config = app.config
        scheme = None

        mailer_uri = self.config.get("MAIL_URL")
        if mailer_uri:
            mailer_uri = utils.urlparse(mailer_uri)
            scheme = mailer_uri.scheme
            hostname = mailer_uri.hostname

            # Using ses-mailer
            if "ses" in scheme.lower():
                self.provider = "SES"

                access_key = mailer_uri.username or app.config.get(
                    "AWS_ACCESS_KEY_ID")
                secret_key = mailer_uri.password or app.config.get(
                    "AWS_SECRET_ACCESS_KEY")
                region = hostname or self.config.get("AWS_REGION", "us-east-1")

                self.mail = ses_mailer.Mail(
                    aws_access_key_id=access_key,
                    aws_secret_access_key=secret_key,
                    region=region,
                    sender=self.config.get("MAIL_SENDER"),
                    reply_to=self.config.get("MAIL_REPLY_TO"),
                    template=self.config.get("MAIL_TEMPLATE"),
                    template_context=self.config.get("MAIL_TEMPLATE_CONTEXT"))

            # SMTP will use flask-mail
            elif "smtp" in scheme.lower():
                self.provider = "SMTP"

                class _App(object):
                    config = {
                        "MAIL_SERVER": mailer_uri.hostname,
                        "MAIL_USERNAME": mailer_uri.username,
                        "MAIL_PASSWORD": mailer_uri.password,
                        "MAIL_PORT": mailer_uri.port,
                        "MAIL_USE_TLS":
                        True if "tls" in mailer_uri.scheme else False,
                        "MAIL_USE_SSL":
                        True if "ssl" in mailer_uri.scheme else False,
                        "MAIL_DEFAULT_SENDER": app.config.get("MAIL_SENDER"),
                        "TESTING": app.config.get("TESTING"),
                        "DEBUG": app.config.get("DEBUG")
                    }
                    debug = app.config.get("DEBUG")
                    testing = app.config.get("TESTING")

                _app = _App()
                self.mail = flask_mail.Mail(app=_app)

                _ses_mailer = ses_mailer.Mail(
                    template=self.config.get("MAIL_TEMPLATE"),
                    template_context=self.config.get("MAIL_TEMPLATE_CONTEXT"))
                self._template = _ses_mailer.parse_template
            else:
                logging.warning("Mailer Error. Invalid scheme '%s'" % scheme)
Ejemplo n.º 4
0
Archivo: webapp.py Proyecto: mcptr/ki
    def init_extensions(self):
        mail_app = flask_mail.Mail(self.flask_app)
        babel = flask_babel.Babel(self.flask_app)
        babel.locale_selector_func = self.locale_selector

        self.extensions.update(
            babel=babel,
            mail=mail_app,
        )
 def test_unicode_subject(self):
     app = flask.Flask(__name__)
     flask_mail.Mail(app)
     with app.app_context():
         msg = SuperdeskMessage(self.subject, sender="root", body="test")
         out = msg.as_bytes()
     parsed = Parser().parsestr(out.decode("utf-8"), headersonly=True)
     decoded, charset = decode_header(parsed["subject"])[0]
     self.assertEqual(self.subject, decoded.decode(charset))
Ejemplo n.º 6
0
def report():
    service = auth.get_calendar_service()
    req_json = request.get_json()
    event_id = req_json['body']['eventId']
    # Send email
    event = calendar_api.get_event(service, event_id)
    event_info = calendar_api.parse_event_info(event)
    mail = flask_mail.Mail(app)
    message = flask_mail.Message(subject='Zoom Event Reported',
                                 html=render_template('report_event.html',
                                                      **event_info),
                                 recipients=['*****@*****.**'])
    mail.send(message)
    return SUCCESS_STATUS
Ejemplo n.º 7
0
def send_email(title, html_text, body_text, recipients):
    # Prepare email
    css = sass.compile(string=flask.render_template('email/base.scss'))
    html = flask.render_template('email/base.html',
                                 title=title,
                                 css=css,
                                 text=html_text)
    html = premailer.Premailer(html, strip_important=False).transform()

    body = flask.render_template('email/base.txt', title=title, text=body_text)

    # Send email
    mail = flask_mail.Mail(flask.current_app)
    msg = flask_mail.Message(title,
                             recipients=recipients,
                             body=body,
                             html=html)
    mail.send(msg)
Ejemplo n.º 8
0
def delete_event():
    """Removes calendar event with specified eventId."""
    service = auth.get_calendar_service()
    event_id = request.form.get('event_id')
    event = calendar_api.get_event(service, event_id)
    event_info = calendar_api.parse_event_info(event)
    calendar_api.delete_event(service, event_id)

    # Send email to whoever's event it was notifying them.
    mail = flask_mail.Mail(app)
    message = flask_mail.Message(subject='Your Zoom Event was Removed',
                                 html=render_template('removed_event.html',
                                                      **event_info),
                                 recipients=[event_info['creator']])
    mail.send(message)

    return "Event %s with ID %s was successfully removed." % (
        event_info['summary'], event_id)
Ejemplo n.º 9
0
def email_sender(mail, app, subject: str, body: str, recipients: list,
                 sender: str):

    msg = flask_mail.Message(
        subject,
        sender=sender,
        recipients=recipients,
    )
    msg.body = body

    mail = flask_mail.Mail(app) if mail is None else mail

    try:
        mail.send(msg)
    except smtplib.SMTPAuthenticationError:
        return ('Please log in with your web browser and then try again.', 401)
    except BaseException as error:
        return ('Unexpected error occured while sending email. '
                'Traceback: {}'.format(error), 500)
    return 'Email was sent.', 200
Ejemplo n.º 10
0
def init_apis(app, *args, **kwargs):
    global cfg
    cfg = pkconfig.init(
        mail_server=(None, str, 'Mail server'),
        mail_username=(None, str, 'Mail user name'),
        mail_password=(None, str, 'Mail password'),
        mail_support_email=(None, str, 'Support email address'),
        mail_recipient_email=(None, str,
                              'Email to receive registration messages'),
    )
    assert cfg.mail_server and cfg.mail_username and cfg.mail_password \
        and cfg.mail_support_email and cfg.mail_recipient_email, \
        'Missing mail config'
    app.config.update(
        MAIL_USE_TLS=True,
        MAIL_PORT=587,
        MAIL_SERVER=cfg.mail_server,
        MAIL_USERNAME=cfg.mail_username,
        MAIL_PASSWORD=cfg.mail_password,
    )
    global _mail
    _mail = flask_mail.Mail(app)
Ejemplo n.º 11
0
def resetpass():
    cursor = connexiondb()
    msg = ''
    try:
        if request.method == "POST":
            rmail = request.form['Resetmail']
            cursor.execute("SELECT * FROM Administrateur WHERE Email=%s",
                           (rmail))
            requet = cursor.fetchall()
            if len(requet) == 1:

                envoi = flask_mail.Message(
                    subject='hello',
                    sender=app.config.get('MAIL_USERNAME'),
                    body='hallo hello flask test')
                envoi.add_recipient(rmail)
                flask_mail.Mail().send(envoi)
                msg = 'mail envoyer'
            else:
                msg = 'mail incorrect'
    except Exception, e:
        return str(e)
Ejemplo n.º 12
0
def init_apis(app, *args, **kwargs):
    global cfg
    cfg = pkconfig.init(
        #TODO(robnagler) validate email
        from_email=pkconfig.Required(str, 'From email address'),
        from_name=pkconfig.Required(str, 'From display name'),
        smtp_password=pkconfig.Required(str, 'SMTP auth password'),
        smtp_server=pkconfig.Required(str, 'SMTP TLS server'),
        smtp_user=pkconfig.Required(str, 'SMTP auth user'),
    )
    auth_db.init_model(app, _init_model)
    if pkconfig.channel_in('dev') and cfg.smtp_server == _DEV_SMTP_SERVER:
        return
    app.config.update(
        MAIL_USE_TLS=True,
        MAIL_PORT=587,
        MAIL_SERVER=cfg.smtp_server,
        MAIL_USERNAME=cfg.smtp_user,
        MAIL_PASSWORD=cfg.smtp_password,
    )
    global _smtp
    _smtp = flask_mail.Mail(app)
Ejemplo n.º 13
0
import flask
import flask_mail
import jwt

app = flask.Flask(__name__)

app.config["SECRET_KEY"] = 'ShHhHhhhitsasecret'
app.config['MAIL_SERVER'] = '*****@*****.**'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = "******"
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = "******"
app.config['MAIL_PASSWORD'] = "******"

payload = {'message': 'helloooo'}
token = jwt.encode(payload, 'ShHhHhhhitsasecret')
print('encoded token: ' + token)

decoded = jwt.decode(token, app.config['SECRET_KEY'])
print(decoded)

print(payload)

mail_mgr = flask_mail.Mail(app)

from . import views
Ejemplo n.º 14
0
import flask as fl
import flaskext.mysql as sql
import flask_mail as fmail
from flask_uploads import UploadSet, configure_uploads, IMAGES
from csming import config as cfg

# init app
app = fl.Flask(__name__)
app.secret_key = cfg.BasicConfig.secret_key

# init flask-uploads
photos = UploadSet('photos', IMAGES)

# config
app.config.from_object(cfg.BasicConfig)
configure_uploads(app, photos)

# init mail
mail = fmail.Mail(app)
# init MySQL
mysql = sql.MySQL(app)

import csming.views
Ejemplo n.º 15
0
from flask import Flask
import flask_mail as eMail
'''
    Add the Job and depratment connection to the Empoyee
    Make the edit option available using the select list

'''

app = Flask(__name__)

mail_settings = {
    "MAIL_SERVER": 'smtp.gmail.com',
    "MAIL_PORT": 465,
    "MAIL_USE_TLS": False,
    "MAIL_USE_SSL": True,
    "MAIL_USERNAME": "******",
    "MAIL_PASSWORD": "******"
}

app.config.update(mail_settings)
mail = eMail.Mail(app)

app.config["UploadImageFolder"] = "Beec\\UploadedImgs"

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

import Beec.OnlyWebsite
import Beec.OnlyApp
import Beec.LoginRouts
Ejemplo n.º 16
0
from flask_debugtoolbar import DebugToolbarExtension
from flask_bcrypt import Bcrypt
import flask_mail
import flask_fanstatic
from dotenv import load_dotenv
import os

from werkzeug.middleware.proxy_fix import ProxyFix

import logging
from logging.config import dictConfig

toolbar = DebugToolbarExtension()
flask_bcrypt = Bcrypt()
flask_mailer = flask_mail.Mail()
fanstatic = flask_fanstatic.Fanstatic()


def create_app(test_config=None):
    # create and configure the app
    log.info("create_app: called")

    app = Flask(__name__, instance_relative_config=True)
    app.wsgi_app = ProxyFix(app.wsgi_app,
                            x_for=1,
                            x_proto=1,
                            x_host=1,
                            x_port=1,
                            x_prefix=1)
Ejemplo n.º 17
0
def create_app(is_sentry_on=False, **kwargs):
    app = Flask(__name__)

    app.config.update(kwargs or {})

    db = MongoEngine()

    CORS(app)

    if 'TESTING' in kwargs and kwargs['TESTING']:
        app.testing = True

        db.init_app(
            app, {
                'MONGODB_SETTINGS': {
                    'db':
                    'testing',
                    'host':
                    'mongodb://*****:*****@ds111876.mlab.com:11876/testing'
                }
            })
        # db.connection
    else:
        app.config['MONGODB_SETTINGS'] = {
            'db':
            'cheapbookdev',
            'host':
            'mongodb://*****:*****@ds053305.mlab.com:53305/cheapbookdev'
        }
        db.init_app(app)

    import models
    configs = models.Config.objects.get(config_id='initials')
    app.config.from_object(configs)
    app.config['DEBUG'] = False

    mail = flask_mail.Mail()
    mail.init_app(app=app)
    if is_sentry_on:
        sentry = Sentry(
            dsn=
            'https://*****:*****@sentry.io/177217'
        )
        sentry.init_app(app)
    flask_mobility.Mobility().init_app(app=app)

    from utils.exception_handler import error_dict, Handler

    for e in error_dict:
        app.register_error_handler(e, Handler(e).generate_response)
    from utils.exceptions import general_exceptions

    # @app.errorhandler(404)
    # @app.errorhandler(401)
    @app.errorhandler(500)
    @json_response
    def page_not_found_500(error):
        print(error)
        return general_exceptions.BASIC_ERROR_500

    @app.errorhandler(404)
    @json_response
    def page_not_found_404(error):
        print(error)
        return general_exceptions.BASIC_ERROR_500

    @app.before_request
    def before_request():
        request_data = save_request(request)
        global_storage.request_data = request_data

    @app.after_request
    def after_request(resp):
        resp_data = save_response(resp)
        request_data = global_storage.request_data
        traffic = models.Traffic(request=request_data, response=resp_data)
        traffic.save()
        return resp

    import URLs
    routes = URLs.get_urls()
    for model in dir(models):
        temp_class = getattr(models, model)
        if inspect.isclass(temp_class) and issubclass(
                temp_class, models.base.BaseDocument):
            print(temp_class.__name__)
            app.url_map.converters[
                temp_class.__name__] = temp_class.get_converter()

    for route in routes:
        imported_class = route['cls']

        route_object = imported_class()
        app.add_url_rule(route['route'],
                         view_func=route_object.dispatcher,
                         endpoint=route['endpoint'],
                         methods=['GET', 'POST', 'PUT', 'DELETE'])

    return app
Ejemplo n.º 18
0
import flask
import flask_sqlalchemy
import flask_migrate
import flask_mail
from flask_login import LoginManager
from .static import enums
import os

db = flask_sqlalchemy.SQLAlchemy()
migrate = flask_migrate.Migrate()
login_manager = LoginManager()
mail_manager = flask_mail.Mail()


def create_app(default_env="production"):
    # imports
    from config import config
    from .views import main_blueprint
    from .user_managment import user_blueprint
    from .learning_hub import learning_hub_bp
    from . import models

    #learning_app init
    app = flask.Flask(__name__)

    # environment
    env = os.environ.get(
        "FLASK_ENV", default_env
    )  # This will be different given the computer python is running on
    app.config.from_object(config[env])
    # learning_app.config['SECRET_KEY'] = "secretKey"
Ejemplo n.º 19
0
    def __init(self, instance):
        instance.config.from_envvar('FLASK_SETTING')
        self.settings = instance.config
        if instance.debug:
            current = os.path.dirname(__file__)
            self.path = os.path.join(current, '..', 'dump', 'data')
            self.lpath = os.path.join(current, '..', 'dump', 'logs')
        else:
            self.path = os.path.join('/', 'var', 'rere1')
            self.lpath = os.path.join('/', 'var', 'logs')
            instance.wsgi_app = \
                werkzeug.contrib.fixers.ProxyFix(instance.wsgi_app)
            self.sentry = raven.contrib.flask.Sentry(
                instance,
                logging=True,
                level=logging.WARNING,
            )

        const = base.Constant
        with instance.app_context():
            for _ in range(0,
                           self.settings[const.SETTING_MAX_RECONNECTION_TRY]):
                try:
                    self.db = base.Alchemy
                    self.db.init_app(instance)
                    self.db.create_all()
                    self.db.session.commit()
                    break
                except Exception as exception:
                    time.sleep(self.settings[const.SETTING_DEFAULT_SLEEP_TIME])

            self.redis = flask_redis.FlaskRedis()
            self.redis.init_app(instance, decode_responses=True)

            for _ in range(0,
                           self.settings[const.SETTING_MAX_RECONNECTION_TRY]):
                try:
                    if self.redis.ping():
                        break
                    else:
                        raise Exception()
                except Exception as exception:
                    time.sleep(self.settings[const.SETTING_DEFAULT_SLEEP_TIME])

            flask_cors.CORS(instance)

            self.extensions = {}
            self.extensions['mail'] = flask_mail.Mail()
            self.extensions['mail'].init_app(instance)
            remote = flask_limiter.util.get_remote_address
            self.extensions['limiter'] = flask_limiter.Limiter(key_func=remote)
            self.extensions['limiter'].init_app(instance)
            self.extensions['cache'] = flask_cache.Cache(with_jinja2_ext=False)
            self.extensions['cache'].init_app(instance)

        if not instance.debug:
            for name, exception in werkzeug.exceptions.__dict__.items():
                if isinstance(exception, type):
                    if issubclass(exception, Exception):
                        instance.register_error_handler(
                            exception,
                            lambda exception: flask.jsonify({}),
                        )

        if not instance.debug:
            instance.logger.removeHandler(flask.logging.default_handler)
            handler = logging.FileHandler(os.path.join(self.lpath,
                                                       'api.log'), )
            handler.setLevel(logging.WARNING)
            instance.logger.addHandler(handler)

        self.__components = {}
        for name, component in components.__dict__.items():
            if isinstance(component, type):
                if issubclass(component, base.Component):
                    self.__components[name.lower()] = component(self)

        self.__actions = {}
        for name, action in actions.__dict__.items():
            if isinstance(action, type):
                if issubclass(action, base.Action):
                    self.__actions[name.lower()] = action(self)

        for name, command in commands.__dict__.items():
            if isinstance(command, type):
                if issubclass(command, base.Command):
                    cmd = functools.partial(command.execute, command(self))
                    cmd.__name__ = command.NAME
                    cmd = click.command()(cmd)
                    cmd.short_help = command.DESCRIPTION
                    for argument in command.ARGUMENTS:
                        cmd = click.option(
                            '--' + argument['name'],
                            type=argument['type'],
                            default=argument['default'],
                            help=argument['description'],
                        )(cmd)
                    instance.cli.add_command(cmd)
Ejemplo n.º 20
0
import flask_migrate
import flask_bootstrap
import flask_login
import flask_mail
import flask_moment

import werkzeug

from app import config
# ~ from app import forms

bazadanych = flask_sqlalchemy.SQLAlchemy()
migracje = flask_migrate.Migrate()
stylista = flask_bootstrap.Bootstrap()
zalogowany = flask_login.LoginManager()
wysylacz = flask_mail.Mail()
momencik = flask_moment.Moment()

# ~ from app import models

# ~ aplikacja = flask.Flask( __name__ )
# ~ aplikacja.config.from_object( config.Config )

# ~ bazadanych.init_app( aplikacja )
# ~ migracje.init_app( aplikacja, bazadanych )
# ~ stylista.init_app( aplikacja )
# ~ zalogowany.init_app( aplikacja )

# ~ from app.auth import auth as bp_auth
# ~ aplikacja.register_blueprint( bp_auth )
Ejemplo n.º 21
0
conf = configparser.ConfigParser()
config_path = util.get_root_path() + "/conf/platform.conf"
conf.read(config_path)
host = conf.get("system", "host")
port = conf.get("system", "port")

stp_app = flask.Flask("SubwayTraffic")
stp_app.config.update(
    MAIL_SERVER="smtp.qq.com",
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USERNAME=conf.get("deploy", "admin_email"),
    MAIL_PASSWORD=conf.get("deploy", "admin_email_pwd"),
)
stp_email = flask_mail.Mail(stp_app)

server_init.register(stp_app)


def send_mail(**kwargs):
    subject = kwargs["header"]
    mail_type = kwargs["type"]
    message = flask_mail.Message(
        subject,
        recipients=kwargs["receiver"],
        sender=("SubwayTraffic", conf.get("deploy", "admin_email")),
    )
    if mail_type == "send_code":
        message.html = flask.render_template("send_code.html",
                                             operate=kwargs["operate"],
Ejemplo n.º 22
0
import os.path
import smtplib
import time
import uuid

import couchdb2
import flask
import flask_mail
import jinja2.utils
import marko
import werkzeug.routing

from anubis import constants

# Global instance of mail interface.
MAIL = flask_mail.Mail()


def init(app):
    """Initialize.
    - Add template filters.
    - Update CouchDB design documents.
    """
    MAIL.init_app(app)
    app.add_template_filter(display_markdown)
    app.add_template_filter(display_field_value)
    app.add_template_filter(display_value)
    app.add_template_filter(display_datetime_local_server)
    app.add_template_filter(display_boolean)
    app.add_template_filter(user_link)
    app.add_template_filter(call_link)
Ejemplo n.º 23
0
import datetime
import itertools

import werkzeug
import flask
import flask_appconfig.env
import flask_mail
import flask.ext.cache
import flask.ext.compress
import flask.ext.assets

import identity

app = flask.Flask(__name__)
flask_appconfig.env.from_envvars(app.config, prefix='MPCV_')
mail = flask_mail.Mail(app)
cache = flask.ext.cache.Cache(app,config={'CACHE_TYPE': 'simple'})
flask.ext.compress.Compress(app)
assets = flask.ext.assets.Environment(app)

import lookups
import constants

# Log to stderr for Heroku
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
app.logger.addHandler(stream_handler)

#####################################################################
# Sitemap and global API
Ejemplo n.º 24
0
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of MyDojo package (https://github.com/honzamach/mydojo).
#
# Copyright (C) since 2018 Honza Mach <*****@*****.**>
# Use of this source is governed by the MIT license, see LICENSE file.
#-------------------------------------------------------------------------------
"""
This module contains mailing functions for MyDojo application. They are built on
top of :py:mod:`flask_mail` extension.
"""

__author__ = "Honza Mach <*****@*****.**>"

import flask_mail

MAILER = flask_mail.Mail()
"""Global application resource: :py:mod:`flask_mail` mailer."""


def on_email_sent(message, app):
    """
    Signal handler for handling :py:func:`flask_mail.email_dispatched` signal.
    Log subject and recipients of all email that have been sent.
    """
    app.logger.info("Sent email '%s' to '%s'", message.subject,
                    ', '.join(message.recipients))


flask_mail.email_dispatched.connect(on_email_sent)
Ejemplo n.º 25
0
import smtplib
from typing import Any, Dict

import flask
import flask_mail

from . import config

mail = flask_mail.Mail()


def send_mail(email: str, template: str, params: Dict[str, Any]) -> bool:
    message = flask_mail.Message()

    message.sender = '{} <{}>'.format(
        config.get('APP_EMAIL_SENDER_NAME'),
        config.get('APP_EMAIL_SENDER_MAIL'),
    )
    message.recipients = [email]
    message.subject = flask.render_template(
        '{}/subject.txt'.format(template),
        **params,
    )
    message.body = flask.render_template(
        '{}/body.txt'.format(template),
        **params,
    )

    mail: flask_mail.Mail = flask.current_app.extensions['mail']
    try:
        mail.send(message)
Ejemplo n.º 26
0
Archivo: app.py Proyecto: BitKil/-
from flask import Flask, request, url_for, render_template, session

app = Flask(__name__)
app.config['DEBUG'] = True
app.secret_key = 'asd'
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)

# mail和redis配置
app.config['MAIL_SERVER'] = 'smtp.126.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '******'
app.config['MAIL_PASSWORD'] = '******'
app.config['FLASK_MAIL_SENDER'] = '皮皮虾!我们走!<*****@*****.**>'
app.config['FLASK_MAIL_SUBJECT_PREFIX'] = '[皮皮虾!我们走]'
mail = flaskmail.Mail(app)
redis_store = redis.StrictRedis(host='127.0.0.1', port='6379')


@app.route('/')
def toLogin():
    return render_template('login.html')


@app.route('/reNewPwd.html')
def toReNewPwd():
    return render_template('reNewPwd.html')


@app.route('/index.html')
def toIndex():