def init_email_error_handler(app):
"""
Initialize a logger to send emails on error-level messages.
Unhandled exceptions will now send an email message to app.config.ADMINS.
"""
if app.debug: return # Do not send error emails while developing
# Retrieve email settings from app.config
host = app.config['MAIL_SERVER']
port = app.config['MAIL_PORT']
from_addr = app.config['MAIL_DEFAULT_SENDER']
username = app.config['MAIL_USERNAME']
password = app.config['MAIL_PASSWORD']
secure = () if app.config.get('MAIL_USE_TLS') else None
# Retrieve app settings from app.config
to_addr_list = app.config['ADMINS']
subject = app.config.get('APP_SYSTEM_ERROR_SUBJECT_LINE', 'System Error')
# Setup an SMTP mail handler for error-level messages
import logging
from logging.handlers import SMTPHandler
mail_handler = SMTPHandler(
mailhost=(host, port), # Mail host and port
fromaddr=from_addr, # From address
toaddrs=to_addr_list, # To address
subject=subject, # Subject line
credentials=(username, password), # Credentials
secure=secure,
)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
# Log errors using: app.logger.error('Some error message')
python类Mail()的实例源码
def config_app(*args, **kwargs):
"""
Return the app object configured correctly.
This needed to be done for gunicorn.
"""
settings = api.config.get_settings()
if settings["email"]["enable_email"]:
app.config["MAIL_SERVER"] = settings["email"]["smtp_url"]
app.config["MAIL_PORT"] = settings["email"]["smtp_port"]
app.config["MAIL_USERNAME"] = settings["email"]["email_username"]
app.config["MAIL_PASSWORD"] = settings["email"]["email_password"]
app.config["MAIL_DEFAULT_SENDER"] = settings["email"]["from_addr"]
app.config["MAIL_USE_TLS"] = settings["email"]["smtp_security"] == "TLS"
app.config["MAIL_USE_SSL"] = settings["email"]["smtp_security"] == "SSL"
api.email.mail = Mail(app)
app.register_blueprint(api.routes.user.blueprint, url_prefix="/api/user")
app.register_blueprint(api.routes.team.blueprint, url_prefix="/api/team")
app.register_blueprint(api.routes.stats.blueprint, url_prefix="/api/stats")
app.register_blueprint(api.routes.admin.blueprint, url_prefix="/api/admin")
app.register_blueprint(api.routes.group.blueprint, url_prefix="/api/group")
app.register_blueprint(api.routes.problem.blueprint, url_prefix="/api/problems")
app.register_blueprint(api.routes.achievements.blueprint, url_prefix="/api/achievements")
api.logger.setup_logs({"verbose": 2})
return app
def config_app(*args, **kwargs):
"""
Return the app object configured correctly.
This needed to be done for gunicorn.
"""
settings = api.config.get_settings()
if settings["email"]["enable_email"]:
app.config["MAIL_SERVER"] = settings["email"]["smtp_url"]
app.config["MAIL_PORT"] = settings["email"]["smtp_port"]
app.config["MAIL_USERNAME"] = settings["email"]["email_username"]
app.config["MAIL_PASSWORD"] = settings["email"]["email_password"]
app.config["MAIL_DEFAULT_SENDER"] = settings["email"]["from_addr"]
app.config["MAIL_USE_TLS"] = settings["email"]["smtp_security"] == "TLS"
app.config["MAIL_USE_SSL"] = settings["email"]["smtp_security"] == "SSL"
api.email.mail = Mail(app)
app.register_blueprint(api.routes.user.blueprint, url_prefix="/api/user")
app.register_blueprint(api.routes.team.blueprint, url_prefix="/api/team")
app.register_blueprint(api.routes.stats.blueprint, url_prefix="/api/stats")
app.register_blueprint(api.routes.admin.blueprint, url_prefix="/api/admin")
app.register_blueprint(api.routes.group.blueprint, url_prefix="/api/group")
app.register_blueprint(api.routes.problem.blueprint, url_prefix="/api/problems")
app.register_blueprint(api.routes.achievements.blueprint, url_prefix="/api/achievements")
api.logger.setup_logs({"verbose": 2})
return app
def __init__(self, app):
self.mail = Mail()
self.mail.init_app(app)
def __init__(self):
self.mail = Mail(current_app)
def home():
print("hello")
#food = []
food = getAllFoods()
FullLength = len(food)
length1 = len(food)
g.db = connect_db()
#g.db.execute("INSERT INTO entries(food,attributes) VALUES('chicken')")
for x in range(FullLength):
for y in range(len(food[x])):
if len(food[x][y][1]) == "none" :
g.db.execute("INSERT INTO entries(food,attributes) VALUES(?,?)",[food[x][y][0],food[x][y][1]])
g.db.commit()
else:
g.db.execute("INSERT INTO entries(food,attributes) VALUES(?,?)",[food[x][y][0],food[x][y][1]])
g.db.commit()
g.db = connect_db()
#Get everything from entries
cur = g.db.execute('select * from entries')
#Create dictionary using list comprehension
entries = [dict(food=row[1], attributes = row[2]) for row in cur.fetchall()]
#Returns the html to user
return render_template('index.html', entries = entries)
#------Mail aspect of website-----
def init_mail(app):
from flask_mail import Mail
app.config['MAIL_SERVER'] = MAIL_SERVER
app.config['MAIL_PORT'] = MAIL_PORT
app.config['MAIL_USE_TLS'] = MAIL_USER_TLS
app.config['MAIL_USE_SSL'] = MAIL_USER_SSL
app.config['MAIL_USERNAME'] = MAIL_USERNAME
app.config['MAIL_PASSWORD'] = MAIL_PASSWORD
app.config['MAIL_DEBUG'] = MAIL_DEBUG
mail = Mail()
mail.init_app(app)
return mail
def mail_view():
if request.method == 'POST':
recipients = request.form.get('recipients')
recipients = [recipient.strip() for recipient in recipients.split(',')]
cc = request.form.get('cc')
cc = [cc.strip() for cc in cc.split(',')]
title = request.form.get('title')
body = request.form.get('body')
send_mails(recipients, cc, title, body)
return redirect(url_for('mail_view'))
return '''
<!DOCTYPE html>
<html>
<head>
<title>Mail</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="col-md-10 col-md-offset-1">
<h3>Send Mails</h3><hr/>
<form method="POST">
<div class="form-group">
<label>Receivers:</label><input type="text", name="recipients" class="form-control" >
</div>
<div class="form-group">
<label>Cc:</label><input type="text", name="cc" class="form-control" >
</div>
<div class="form-group">
<label>Title:</label>
<input type="text", name="title" class="form-control" >
</div>
<div class="form-group">
<label>Body:</label>
<textarea class="form-control" rows="6" name="body"></textarea>
</div>
<div class="form-group">
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
'''
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)
def send(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs):
"""
To send email
:param to: the recipients, list or string
:param subject: the subject
:param body: the body
:param reply_to: reply_to
:param template: template, will use the templates instead
:param kwargs: context args
:return: bool - True if everything is ok
"""
sender = self.config.get("MAIL_SENDER")
recipients = [to] if not isinstance(to, list) else to
kwargs.update({
"subject": subject,
"body": body,
"reply_to": reply_to
})
if not self.validated:
raise exceptions.MochaError("Mail configuration error")
if self.provider == "SES":
kwargs["to"] = recipients
if template:
self.mail.send_template(template=template, **kwargs)
else:
self.mail.send(**kwargs)
elif self.provider == "SMTP":
if template:
data = self._template(template=template, **kwargs)
kwargs["subject"] = data["subject"]
kwargs["body"] = data["body"]
kwargs["recipients"] = recipients
kwargs["sender"] = sender
# Remove invalid Messages keys
_safe_keys = ["recipients", "subject", "body", "html", "alts",
"cc", "bcc", "attachments", "reply_to", "sender",
"date", "charset", "extra_headers", "mail_options",
"rcpt_options"]
for k in kwargs.copy():
if k not in _safe_keys:
del kwargs[k]
message = flask_mail.Message(**kwargs)
self.mail.send(message)
else:
raise exceptions.MochaError("Invalid mail provider. Must be 'SES' or 'SMTP'")
def init_app(app, extra_config_settings={}):
# Read common settings from 'app/settings.py'
app.config.from_object('app.settings')
# Read environment-specific settings from 'app/local_settings.py'
try:
app.config.from_object('app.local_settings')
except ImportError:
print("The configuration file 'app/local_settings.py' does not exist.\n"+
"Please copy app/local_settings_example.py to app/local_settings.py\n"+
"and customize its settings before you continue.")
exit()
# Add/overwrite extra settings from parameter 'extra_config_settings'
app.config.update(extra_config_settings)
if app.testing:
app.config['WTF_CSRF_ENABLED'] = False # Disable CSRF checks while testing
# Initialize Flask-SQLAlchemy and Flask-Script _after_ app.config has been read
#db.init_app(app)
# Setup Flask-Migrate
#migrate = Migrate(app, db)
#manager.add_command('db', MigrateCommand)
# Setup Flask-Mail
mail = Mail(app)
# Setup WTForms CsrfProtect
#CsrfProtect(app)
# Define bootstrap_is_hidden_field for flask-bootstrap's bootstrap_wtf.html
from wtforms.fields import HiddenField
def is_hidden_field_filter(field):
return isinstance(field, HiddenField)
app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter
# Setup an error-logger to send emails to app.config.ADMINS
init_email_error_handler(app)
# Setup Flask-User to handle user account related forms
#from app.models import User, MyRegisterForm
#from app.views import user_profile_page
#db_adapter = SQLAlchemyAdapter(db, User) # Setup the SQLAlchemy DB Adapter
#user_manager = UserManager(db_adapter, app, # Init Flask-User and bind to app
#register_form=MyRegisterForm, # using a custom register form with UserProfile fields
#user_profile_view_function=user_profile_page,
#)
#import app.manage_commands