本文整理汇总了Python中flask_mail.Mail方法的典型用法代码示例。如果您正苦于以下问题:Python flask_mail.Mail方法的具体用法?Python flask_mail.Mail怎么用?Python flask_mail.Mail使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask_mail
的用法示例。
在下文中一共展示了flask_mail.Mail方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def __init__(self, app):
"""Check config settings and setup Flask-Mail.
Args:
app(Flask): The Flask application instance.
"""
super(SMTPEmailAdapter, self).__init__(app)
# Setup Flask-Mail
try:
from flask_mail import Mail
except ImportError:
raise ConfigError(
"The Flask-Mail package is missing. Install Flask-Mail with 'pip install Flask-Mail'.")
self.mail = Mail(app)
示例2: email_report
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def email_report(email, report):
# Create email message for the form administrator and requestor
email_message = """
<html>
<head></head>
<body>
%s
</body>
</html>
""" % report
# Send email message to admin
mail = Mail(app)
recipients = [email]
msg = Message(subject='Subnet Report', html=email_message, recipients=recipients)
try:
mail.send(msg)
except Exception as e:
return e
return 0
示例3: send_async_email
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def send_async_email(email_data):
"""Background task to send an email with Flask-Mail."""
msg = Message(email_data['subject'],
sender=app.config['MAIL_DEFAULT_SENDER'],
recipients=[email_data['to']])
msg.body = email_data['body']
with app.app_context():
mail.send(msg)
示例4: test_cache
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def test_cache():
assert isinstance(cache, flask_caching.Cache)
# # Mailer
# def test_mailer_none():
# assert mailer.mail is None
#
# def test_mailer_ses():
# app = Flask(__name__)
# app.config.update(**{
# "MAILER_PROVIDER": "SES",
# "MAILER_SES_ACCESS_KEY": "",
# "MAILER_SES_SECRET_KEY": ""
# })
# mailer.init_app(app)
# assert isinstance(mailer.mail, ses_mailer.Mail)
#
# def test_mailer_smtp():
# app = Flask(__name__)
# app.config.update(**{
# "MAILER_PROVIDER": "SMTP",
# "MAILER_SMTP_URI": "smtp://user:pass@mail.google.com:25",
# "DEBUG": False,
# "TESTING": False
# })
#
# mailer.init_app(app)
# assert isinstance(mailer.mail, flask_mail.Mail)
示例5: init_email_error_handler
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
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')
示例6: setUp
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def setUp(self):
self.app = Flask(__name__)
self.app.config.from_object(self)
self.assertTrue(self.app.testing)
self.mail = Mail(self.app)
self.ctx = self.app.test_request_context()
self.ctx.push()
示例7: email_bridge_details
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def email_bridge_details(app, bridge):
if app.config.get('MAIL_SERVER', None):
mail = Mail(app)
twitter_follower_count = 0
if bridge.twitter_oauth_token:
# Fetch twitter follower count
twitter_api = twitter.Api(
consumer_key=app.config['TWITTER_CONSUMER_KEY'],
consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
access_token_key=bridge.twitter_oauth_token,
access_token_secret=bridge.twitter_oauth_secret
)
try:
follower_list = twitter_api.GetFollowerIDs()
except TwitterError as e:
twitter_follower_count = e
else:
twitter_follower_count = len(follower_list)
body = render_template('new_user_email.txt.j2',
bridge=bridge,
twitter_follower_count=twitter_follower_count)
msg = Message(subject="moa.party bridge updated",
body=body,
recipients=[app.config.get('MAIL_TO', None)])
try:
mail.send(msg)
except Exception as e:
app.logger.error(e)
示例8: send_blacklisted_email
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def send_blacklisted_email(app, username):
if app.config.get('MAIL_SERVER', None):
mail = Mail(app)
body = render_template('access_denied.txt.j2', user=f"https://twitter.com/{username}")
msg = Message(subject="moa access denied",
body=body,
recipients=[app.config.get('MAIL_TO', None)])
try:
mail.send(msg)
except Exception as e:
app.logger.error(e)
示例9: create_app
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def create_app():
app = Flask(__name__)
mail = Mail(app)
if SSL:
sslify = SSLify(app)
from personal_mycroft_backend.utils import nice_json
from personal_mycroft_backend.backend.decorators import noindex
from personal_mycroft_backend.backend.auth import get_auth_routes
from personal_mycroft_backend.backend.device import get_device_routes
from personal_mycroft_backend.backend.stt import get_stt_routes
from personal_mycroft_backend.backend.tts import get_tts_routes
app = get_auth_routes(app)
app = get_device_routes(app, mail)
app = get_stt_routes(app)
app = get_tts_routes(app)
@app.route("/", methods=['GET'])
@noindex
def hello():
return nice_json({
"uri": "/",
"welcome to Personal Mycroft Backend": {
"author": "JarbasAI"
}
})
return app
示例10: send_email_message
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
""" Send email message via Flask-Mail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text.
"""
# Construct sender from sender_name and sender_email
sender = '"%s" <%s>' % (sender_name, sender_email) if sender_name else sender_email
# Send email via SMTP except when we're testing
if not current_app.testing: # pragma: no cover
try:
# Prepare email message
from flask_mail import Message
message = Message(
subject,
sender=sender,
recipients=[recipient],
html=html_message,
body=text_message)
# Send email message
self.mail.send(message)
# Print helpful error messages on exceptions
except (socket.gaierror, socket.error) as e:
raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.')
except smtplib.SMTPAuthenticationError:
raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.')
示例11: __init__
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def __init__(self):
"""
Upon initialisation the mail configuration settings are retrieved from the database and
self.mail is intialised.
"""
config = FlicketConfig.query.first()
app.config.update(
MAIL_SERVER=config.mail_server,
MAIL_PORT=config.mail_port,
MAIL_USE_TLS=config.mail_use_tls,
MAIL_USE_SSL=config.mail_use_ssl,
MAIL_DEBUG=config.mail_debug,
MAIL_USERNAME=config.mail_username,
MAIL_PASSWORD=config.mail_password,
MAIL_MAX_EMAILS=config.mail_max_emails,
MAIL_SUPPRESS_SEND=config.mail_suppress_send,
MAIL_ASCII_ATTACHMENTS=config.mail_ascii_attachments,
base_url=config.base_url,
)
self.mail = Mail(app)
self.mail.init_app(app)
self.sender = config.mail_default_sender
示例12: __init__
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def __init__(self, app):
"""
:param app: Flask app object
:type app: Flask
"""
self.app = app
self.mail = Mail(app)
self.config = AppConfigReader()
# self.mail_status = config_reader.get_mail_status_sender()
# self.mail_reply = config_reader.get_mail_reply()
# self.mail_org = config_reader.get_mail_org()
# self.disable = config_reader.get_disable_mail()
示例13: user_inventory_user_inventory_page
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def user_inventory_user_inventory_page():
# Define variables
csv_file = StringIO()
csv_writer = csv.writer(csv_file)
mail = Mail(app)
# Iterate through users and write properties to buffer
for user in g.user.get_api().get_by_object_types('*', 'User'):
# Retrieve access rights for user
user_rights = []
for access_right in user.get_access_rights():
access_object = g.user.get_api().get_entity_by_id(access_right.get_entity_id()).get_name()
user_rights.append('%s for %s with overrides: %s'
% (access_right._api_entity['value'], access_object, access_right._api_entity['overrides']))
# Write user properties to CSV
csv_writer.writerow([
user.get_name(),
user.get_property('email'),
user.get_property('userType'),
user.get_property('userAccessType'),
', '.join(user_rights)
])
# Send email with buffer as an attached CSV
msg = Message(subject=u'User Inventory Report', html='User Inventory Report', recipients=config.ADMINS)
msg.attach('user_inventory_report.csv', 'text/csv', csv_file.getvalue())
try:
mail.send(msg)
except Exception as e:
g.user.logger.error('%s' % util.safe_str(e), msg_type=g.user.logger.EXCEPTION)
return response_handler('Unable to email report with error: %s' % util.safe_str(e), 500)
return response_handler('Inventory report successfully generated', 200)
示例14: init_app
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
def init_app(self, app):
utils.flatten_config_property("MAIL", app.config)
self.config = app.config
scheme = None
mailer_uri = self.config.get("MAIL_URL")
if mailer_uri:
templates_sources = app.config.get("MAIL_TEMPLATE")
if not templates_sources:
templates_sources = app.config.get("MAIL_TEMPLATES_DIR") or app.config.get("MAIL_TEMPLATES_DICT")
mailer_uri = 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=templates_sources,
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=templates_sources,
template_context=self.config.get("MAIL_TEMPLATE_CONTEXT"))
self._template = _ses_mailer.parse_template
else:
logging.warning("Mailer Error. Invalid scheme '%s'" % scheme)
示例15: send
# 需要导入模块: import flask_mail [as 别名]
# 或者: from flask_mail import Mail [as 别名]
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 Error("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 Error("Invalid mail provider. Must be 'SES' or 'SMTP'")