Here are the examples of the python api flask_mail.Message taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
90 Examples
3
Example 1
def test_send(self):
with self.mail.record_messages() as outbox:
msg = Message(subject="testing",
recipients=["[email protected]"],
body="test")
self.mail.send(msg)
self.assertIsNotNone(msg.date)
self.assertEqual(len(outbox), 1)
sent_msg = outbox[0]
self.assertEqual(msg.sender, self.app.extensions['mail'].default_sender)
3
Example 2
Project: flask-mail Source File: tests.py
def test_sendmail_with_non_ascii_body(self):
with self.mail.connect() as conn:
with mock.patch.object(conn, 'host') as host:
msg = Message(subject="testing",
sender="[email protected]",
recipients=["[email protected]"],
body=u"Öö")
conn.send(msg)
host.sendmail.assert_called_once_with(
"[email protected]",
["[email protected]"],
msg.as_bytes() if PY3 else msg.as_string(),
msg.mail_options,
msg.rcpt_options
)
3
Example 3
def test_bad_header_recipient(self):
msg = Message(subject="testing",
sender="[email protected]",
recipients=[
"[email protected]",
"to\r\[email protected]"],
body="testing")
self.assertIn('To: [email protected]', msg.as_string())
3
Example 4
Project: flask-mail Source File: tests.py
def test_unicode_sender_tuple(self):
msg = Message(subject="subject",
sender=(u"ÄÜÖ → ✓", '[email protected]>'),
recipients=["[email protected]"])
self.assertIn('From: =?utf-8?b?w4TDnMOWIOKGkiDinJM=?= <[email protected]>', msg.as_string())
3
Example 5
Project: flask-mail Source File: tests.py
def test_plain_message_with_attachments(self):
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
body="hello")
msg.attach(data=b"this is a test",
content_type="text/plain")
self.assertIn('Content-Type: multipart/mixed', msg.as_string())
3
Example 6
Project: flask-mail Source File: tests.py
def test_multiline_subject(self):
msg = Message(subject="testing\r\n testing\r\n testing \r\n \ttesting",
sender="[email protected]",
body="testing",
recipients=["[email protected]"])
self.mail.send(msg)
response = msg.as_string()
self.assertIn("From: [email protected]", str(response))
self.assertIn("testing\r\n testing\r\n testing \r\n \ttesting", str(response))
3
Example 7
def test_bad_header_subject(self):
msg = Message(subject="testing\n\r",
body="testing",
recipients=["[email protected]"])
with self.mail.connect() as conn:
self.assertRaises(BadHeaderError, conn.send, msg)
3
Example 8
def test_recipients_properly_initialized(self):
msg = Message(subject="subject")
self.assertEqual(msg.recipients, [])
msg2 = Message(subject="subject")
msg2.add_recipient("[email protected]")
self.assertEqual(len(msg2.recipients), 1)
3
Example 9
def _send_reset_password_email(user):
code = _generate_reset_password_code(user)
body = render_template('user/reset_password_email.txt', code=code, user=user)
msg = Message("Reset password", recipients=[user.email])
msg.body = body
mail.send(msg)
3
Example 10
Project: flask-mail Source File: tests.py
def test_sendto_properly_set(self):
msg = Message(subject="subject", recipients=["[email protected]"],
cc=["[email protected]"], bcc=["[email protected]"])
self.assertEqual(len(msg.send_to), 3)
msg.add_recipient("[email protected]")
self.assertEqual(len(msg.send_to), 3)
3
Example 11
def test_date_header(self):
before = time.time()
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
body="hello",
date=time.time())
after = time.time()
self.assertTrue(before <= msg.date <= after)
dateFormatted = email.utils.formatdate(msg.date, localtime=True)
self.assertIn('Date: ' + dateFormatted, msg.as_string())
3
Example 12
Project: flask-mail Source File: tests.py
def test_plain_message_with_unicode_attachment(self):
msg = Message(subject="subject",
recipients=["[email protected]"],
body="hello")
msg.attach(data=b"this is a test",
content_type="text/plain",
filename=u'ünicöde ←→ ✓.txt')
parsed = email.message_from_string(msg.as_string())
self.assertIn(re.sub(r'\s+', ' ', parsed.get_payload()[1].get('Content-Disposition')), [
'attachment; filename*="UTF8\'\'%C3%BCnic%C3%B6de%20%E2%86%90%E2%86%92%20%E2%9C%93.txt"',
'attachment; filename*=UTF8\'\'%C3%BCnic%C3%B6de%20%E2%86%90%E2%86%92%20%E2%9C%93.txt'
])
3
Example 13
def test_attach(self):
msg = Message(subject="testing",
recipients=["[email protected]"],
body="testing")
msg.attach(data=b"this is a test",
content_type="text/plain")
a = msg.attachments[0]
self.assertIsNone(a.filename)
self.assertEqual(a.disposition, 'attachment')
self.assertEqual(a.content_type, "text/plain")
self.assertEqual(a.data, b"this is a test")
3
Example 14
def test_extra_headers(self):
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
body="hello",
extra_headers={'X-Extra-Header': 'Yes'})
self.assertIn('X-Extra-Header: Yes', msg.as_string())
3
Example 15
Project: Flask-Scaffold Source File: baseviews.py
def post(self):
request_dict = request.get_json(force=True)['data']['attributes']
email = request_dict['email']
user = Users.query.filter_by(email=email).first()
if user is not None:
token = create_token(user)
msg = Message("Here's your Password Reset Link :)",
recipients=[email])
msg.html = PASSWORD_RESET_EMAIL.format(token=token)
mail.send(msg)
return {"message": "Password reset mail sent successfully"}, 201
else:
return {"error": "We could not find this email address :("}, 404
3
Example 16
Project: flask-mail Source File: tests.py
def test_send_many(self):
with self.mail.record_messages() as outbox:
with self.mail.connect() as conn:
for i in range(100):
msg = Message(subject="testing",
recipients=["[email protected]"],
body="testing")
conn.send(msg)
self.assertEqual(len(outbox), 100)
sent_msg = outbox[0]
self.assertEqual(sent_msg.sender, self.app.extensions['mail'].default_sender)
3
Example 17
def test_bad_header_sender(self):
msg = Message(subject="testing",
sender="[email protected]\r\n",
recipients=["[email protected]"],
body="testing")
self.assertIn('From: [email protected]', msg.as_string())
3
Example 18
Project: flask-mail Source File: tests.py
def test_sendmail_with_non_ascii_recipient(self):
with self.mail.connect() as conn:
with mock.patch.object(conn, 'host') as host:
msg = Message(subject="testing",
sender="[email protected]",
recipients=[u'ÄÜÖ → ✓ <[email protected]>'],
body="testing")
conn.send(msg)
host.sendmail.assert_called_once_with(
"[email protected]",
["=?utf-8?b?w4TDnMOWIOKGkiDinJM=?= <[email protected]>"],
msg.as_bytes() if PY3 else msg.as_string(),
msg.mail_options,
msg.rcpt_options
)
3
Example 19
Project: knowledge-repo Source File: emails.py
def send_internal_error_email(subject_line, **kwargs):
if 'mail' not in current_app.config:
logger.warning(
'Mail subsystem is not configured. Silently dropping email.')
return
recipients = usernames_to_emails(current_repo.config.editors)
msg = Message(subject_line, recipients)
msg.body = render_template(
"email_templates/internal_error_email.txt", **kwargs)
current_app.config['mail'].send(msg)
3
Example 20
@main.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
msg = Message(
"AnnotateIt.org contact form",
recipients=current_app.config['CONTACT_RECIPIENTS']
)
msg.body = render_template('contact_email.txt', **form.data)
mail.send(msg)
flash('Your message was sent successfully. Thanks!', 'success')
return redirect(url_for('.index'))
return render_template('contact.html', form=form)
3
Example 21
Project: flask-mail Source File: tests.py
def test_plain_message(self):
plain_text = "Hello Joe,\nHow are you?"
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
body=plain_text)
self.assertEqual(plain_text, msg.body)
self.assertIn('Content-Type: text/plain', msg.as_string())
3
Example 22
def test_message_str(self):
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
body="some plain text")
self.assertEqual(msg.as_string(), str(msg))
3
Example 23
Project: knowledge-repo Source File: emails.py
def send_reviewer_request_email(post_id, reviewer):
if 'mail' not in current_app.config:
logger.warning('Mail subsystem is not configured. Silently dropping email.')
return
subject = "Someone requested a web post review from you!"
msg = Message(subject, [reviewer])
msg.body = render_template("email_templates/reviewer_request_email.txt",
post_id=post_id)
current_app.config['mail'].send(msg)
3
Example 24
Project: flask-mail Source File: tests.py
def test_plain_message_with_ascii_attachment(self):
msg = Message(subject="subject",
recipients=["[email protected]"],
body="hello")
msg.attach(data=b"this is a test",
content_type="text/plain",
filename='test doc.txt')
self.assertIn('Content-Disposition: attachment; filename="test doc.txt"', msg.as_string())
3
Example 25
def test_reply_to(self):
msg = Message(subject="testing",
recipients=["[email protected]"],
sender="spammer <[email protected]>",
reply_to="somebody <[email protected]>",
body="testing")
response = msg.as_string()
h = Header("Reply-To: %s" % sanitize_address('somebody <[email protected]>'))
self.assertIn(h.encode(), str(response))
3
Example 26
def test_json_message(self):
json_text = '{"msg": "Hello World!}'
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
alts={'json': json_text})
self.assertEqual(json_text, msg.alts['json'])
self.assertIn('Content-Type: multipart/alternative', msg.as_string())
3
Example 27
Project: flask-mail Source File: tests.py
def test_plain_message_with_ascii_converted_attachment(self):
with self.mail_config(ascii_attachments=True):
msg = Message(subject="subject",
recipients=["[email protected]"],
body="hello")
msg.attach(data=b"this is a test",
content_type="text/plain",
filename=u'ünicödeß ←.→ ✓.txt')
parsed = email.message_from_string(msg.as_string())
self.assertIn(
'Content-Disposition: attachment; filename="unicode . .txt"',
msg.as_string())
3
Example 28
def test_cc(self):
msg = Message(sender="[email protected]",
subject="testing",
recipients=["[email protected]"],
body="testing",
cc=["[email protected]"])
response = msg.as_string()
self.assertIn("Cc: [email protected]", str(response))
3
Example 29
Project: flask-mail Source File: tests.py
def test_msgid_header(self):
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
body="hello")
# see RFC 5322 section 3.6.4. for the exact format specification
r = re.compile(r"<\S+@\S+>").match(msg.msgId)
self.assertIsNotNone(r)
self.assertIn('Message-ID: ' + msg.msgId, msg.as_string())
3
Example 30
Project: redash Source File: manage.py
@manager.option('email', default=None, help="Email address to send test message to (default: the address you defined in MAIL_DEFAULT_SENDER)")
def send_test_mail(email=None):
from redash import mail
from flask_mail import Message
if email is None:
email = settings.MAIL_DEFAULT_SENDER
mail.send(Message(subject="Test Message from re:dash", recipients=[email], body="Test message."))
3
Example 31
Project: flask-mail Source File: tests.py
def test_unicode_sender(self):
msg = Message(subject="subject",
sender=u'ÄÜÖ → ✓ <[email protected]>>',
recipients=["[email protected]"])
self.assertIn('From: =?utf-8?b?w4TDnMOWIOKGkiDinJM=?= <[email protected]>', msg.as_string())
3
Example 32
def test_bad_header_subject(self):
msg = Message(subject="testing\r\n",
sender="[email protected]",
body="testing",
recipients=["[email protected]"])
self.assertRaises(BadHeaderError, self.mail.send, msg)
3
Example 33
Project: flask-mail Source File: tests.py
def test_empty_subject_header(self):
msg = Message(sender="[email protected]",
recipients=["[email protected]"])
msg.body = "normal ascii text"
self.mail.send(msg)
self.assertNotIn('Subject:', msg.as_string())
3
Example 34
def send_email(subject, recipients, text_body, html_body, sender=None):
"""Sends an email to the given recipients.
:param subject: The subject of the email.
:param recipients: A list of recipients.
:param text_body: The text body of the email.
:param html_body: The html body of the email.
:param sender: A two-element tuple consisting of name and address.
If no sender is given, it will fall back to the one you
have configured with ``MAIL_DEFAULT_SENDER``.
"""
msg = Message(subject, recipients=recipients, sender=sender)
msg.body = text_body
msg.html = html_body
mail.send(msg)
3
Example 35
Project: flask-mail Source File: tests.py
def test_send_single(self):
with self.mail.record_messages() as outbox:
with self.mail.connect() as conn:
msg = Message(subject="testing",
recipients=["[email protected]"],
body="testing")
conn.send(msg)
self.assertEqual(len(outbox), 1)
sent_msg = outbox[0]
self.assertEqual(sent_msg.subject, "testing")
self.assertEqual(sent_msg.recipients, ["[email protected]"])
self.assertEqual(sent_msg.body, "testing")
self.assertEqual(sent_msg.sender, self.app.extensions['mail'].default_sender)
3
Example 36
Project: flask-mail Source File: tests.py
def test_bad_multiline_subject(self):
msg = Message(subject="testing\r\n testing\r\n ",
sender="[email protected]",
body="testing",
recipients=["[email protected]"])
self.assertRaises(BadHeaderError, self.mail.send, msg)
msg = Message(subject="testing\r\n testing\r\n\t",
sender="[email protected]",
body="testing",
recipients=["[email protected]"])
self.assertRaises(BadHeaderError, self.mail.send, msg)
msg = Message(subject="testing\r\n testing\r\n\n",
sender="[email protected]",
body="testing",
recipients=["[email protected]"])
self.assertRaises(BadHeaderError, self.mail.send, msg)
3
Example 37
def test_send_without_recipients(self):
msg = Message(subject="testing",
recipients=[],
body="testing")
with self.mail.connect() as conn:
self.assertRaises(AssertionError, conn.send, msg)
3
Example 38
Project: braindump Source File: email.py
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,
sender=app.config['MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
3
Example 39
Project: flask-mail Source File: tests.py
def test_sendmail_with_ascii_recipient(self):
with self.mail.connect() as conn:
with mock.patch.object(conn, 'host') as host:
msg = Message(subject="testing",
sender="[email protected]",
recipients=["[email protected]"],
body="testing")
conn.send(msg)
host.sendmail.assert_called_once_with(
"[email protected]",
["[email protected]"],
msg.as_bytes() if PY3 else msg.as_string(),
msg.mail_options,
msg.rcpt_options
)
3
Example 40
Project: flask-mail Source File: tests.py
def test_bad_header_reply_to(self):
msg = Message(subject="testing",
sender="[email protected]",
reply_to="[email protected]\r",
recipients=["[email protected]"],
body="testing")
self.assertIn('From: [email protected]', msg.as_string())
self.assertIn('To: [email protected]', msg.as_string())
self.assertIn('Reply-To: [email protected]', msg.as_string())
3
Example 41
Project: flask-mail Source File: tests.py
def test_sendmail_with_ascii_body(self):
with self.mail.connect() as conn:
with mock.patch.object(conn, 'host') as host:
msg = Message(subject="testing",
sender="[email protected]",
recipients=["[email protected]"],
body="body")
conn.send(msg)
host.sendmail.assert_called_once_with(
"[email protected]",
["[email protected]"],
msg.as_bytes() if PY3 else msg.as_string(),
msg.mail_options,
msg.rcpt_options
)
3
Example 42
Project: flask-mail Source File: tests.py
def test_esmtp_options_properly_initialized(self):
msg = Message(subject="subject")
self.assertEqual(msg.mail_options, [])
self.assertEqual(msg.rcpt_options, [])
msg = Message(subject="subject", mail_options=['BODY=8BITMIME'])
self.assertEqual(msg.mail_options, ['BODY=8BITMIME'])
msg2 = Message(subject="subject", rcpt_options=['NOTIFY=SUCCESS'])
self.assertEqual(msg2.rcpt_options, ['NOTIFY=SUCCESS'])
3
Example 43
Project: flasky Source File: email.py
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
3
Example 44
Project: flask-mail Source File: tests.py
def test_emails_are_sanitized(self):
msg = Message(subject="testing",
sender="sender\r\[email protected]",
reply_to="reply_to\r\[email protected]",
recipients=["recipient\r\[email protected]"])
self.assertIn('[email protected]', msg.as_string())
self.assertIn('[email protected]', msg.as_string())
self.assertIn('[email protected]', msg.as_string())
3
Example 45
Project: pjuu Source File: mail.py
def send_mail(subject, recipients, sender=None,
text_body='', html_body=''):
"""
Sends e-mail via flask-mail
"""
# Set the default sender if one is not supplied
if sender is None: # pragma: no branch
sender = app.config['MAIL_DEFAULT_SENDER']
msg = Message()
msg.subject = subject
msg.recipients = recipients
msg.sender = sender
msg.body = text_body
msg.html = html_body
mail.send(msg)
3
Example 46
Project: knowledge-repo Source File: emails.py
def send_review_email(post_id, comment_text, commenter='Someone'):
if 'mail' not in current_app.config:
logger.warning('Mail subsystem is not configured. Silently dropping email.')
return
webpost = (db_session.query(Post)
.filter(Post.id == post_id)
.first())
post_title = webpost.title
authors = [author.username for author in webpost.authors]
post_author_emails = usernames_to_emails(authors)
subject = "Someone reviewed your web post!"
msg = Message(subject, post_author_emails)
msg.body = render_template("email_templates/review_email.txt",
commenter=commenter,
comment_text=comment_text,
post_title=post_title,
post_id=post_id)
current_app.config['mail'].send(msg)
3
Example 47
def test_bcc(self):
msg = Message(sender="[email protected]",
subject="testing",
recipients=["[email protected]"],
body="testing",
bcc=["[email protected]"])
response = msg.as_string()
self.assertNotIn("[email protected]", str(response))
3
Example 48
def test_html_message(self):
html_text = "<p>Hello World</p>"
msg = Message(sender="[email protected]",
subject="subject",
recipients=["[email protected]"],
html=html_text)
self.assertEqual(html_text, msg.html)
self.assertIn('Content-Type: multipart/alternative', msg.as_string())
0
Example 49
Project: picoCTF-web Source File: email.py
def request_password_reset(username):
"""
Emails a user a link to reset their password.
Checks that a username was submitted to the function and grabs the relevant team info from the db.
Generates a secure token and inserts it into the team's docuement as 'password_reset_token'.
A link is emailed to the registered email address with the random token in the url. The user can go to this
link to submit a new password, if the token submitted with the new password matches the db token the password
is hashed and updated in the db.
Args:
username: the username of the account
"""
validate(password_reset_request_schema, {"username":username})
user = safe_fail(api.user.get_user, name=username)
if user is None:
raise WebException("No registration found for '{}'.".format(username))
token_value = api.token.set_token({"uid": user['uid']}, "password_reset")
body = """We recently received a request to reset the password for the following {0} account:\n\n\t{2}\n\nOur records show that this is the email address used to register the above account. If you did not request to reset the password for the above account then you need not take any further steps. If you did request the password reset please follow the link below to set your new password. \n\n {1}/reset#{3} \n\n Best of luck! \n The {0} Team""".format(api.config.competition_name, api.config.competition_urls[0], username, token_value)
subject = "{} Password Reset".format(api.config.competition_name)
message = Message(body=body, recipients=[user['email']], subject=subject)
mail.send(message)
0
Example 50
def send_user_verification_email(username):
"""
Emails the user a link to verify his account. If email_verification is
enabled in the config then the user won't be able to login until this step is completed.
"""
settings = api.config.get_settings()
db = api.common.get_conn()
user = api.user.get_user(name=username)
key_query = {"$and": [{"uid": user["uid"]}, {"email_verification_count": {"$exists": True}}]}
previous_key = api.token.find_key(key_query)
if previous_key is None:
token_value = api.token.set_token({"uid": user["uid"], "email_verification_count": 1}, "email_verification")
else:
if previous_key["email_verification_count"] < settings["email"]["max_verification_emails"]:
token_value = previous_key["tokens"]["email_verification"]
db.tokens.find_and_modify(key_query, {"$inc": {"email_verification_count": 1}})
else:
raise InternalException("User has been sent the maximum number of verification emails.")
#Is there a better way to do this without dragging url_for + app_context into it?
verification_link = "{}/api/user/verify?uid={}&token={}".\
format(api.config.competition_urls[0], user["uid"], token_value)
body = """
Welcome to {0}!
You will need to visit the verification link below to finalize your account's creation. If you believe this to be a mistake, and you haven't recently created an account for {0} then you can safely ignore this email.
Verification link: {1}
Good luck and have fun!
The {0} Team.
""".format(api.config.competition_name, verification_link)
subject = "{} Account Verification".format(api.config.competition_name)
message = Message(body=body, recipients=[user['email']], subject=subject)
mail.send(message)