Python flask_mail.Message() Examples
The following are 30
code examples of flask_mail.Message().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask_mail
, or try the search function
.
Example #1
Source File: test_upstream.py From flask-unchained with MIT License | 6 votes |
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="from@example.com", recipients=["to@example.com"], body="body") conn.send(msg) host.sendmail.assert_called_once_with( "from@example.com", ["to@example.com"], msg.as_bytes(), msg.mail_options, msg.rcpt_options )
Example #2
Source File: views.py From CHN-Server with GNU Lesser General Public License v2.1 | 6 votes |
def reset_passwd_request(): if 'email' not in request.json: return error_response(errors.AUTH_EMAIL_MISSING, 400) email = request.json['email'] user = User.query.filter_by(email=email).first() if not user: return error_response(errors.AUTH_NOT_FOUND.format(email), 404) hashstr = hashlib.sha1(str(random.getrandbits(128)) + user.email).hexdigest() # Deactivate all other password resets for this user. PasswdReset.query.filter_by(user=user).update({'active': False}) reset = PasswdReset(hashstr=hashstr, active=True, user=user) db.session.add(reset) db.session.commit() # Send password reset email to user. from mhn import mhn msg = Message( html=reset.email_body, subject='MHN Password reset', recipients=[user.email], sender=mhn.config['DEFAULT_MAIL_SENDER']) try: mail.send(msg) except: return error_response(errors.AUTH_SMTP_ERROR, 500) else: return jsonify({})
Example #3
Source File: plugin.py From lemur with Apache License 2.0 | 6 votes |
def send_via_ses(subject, body, targets): """ Attempts to deliver email notification via SMTP. :param subject: :param body: :param targets: :return: """ client = boto3.client("ses", region_name="us-east-1") client.send_email( Source=current_app.config.get("LEMUR_EMAIL"), Destination={"ToAddresses": targets}, Message={ "Subject": {"Data": subject, "Charset": "UTF-8"}, "Body": {"Html": {"Data": body, "Charset": "UTF-8"}}, }, )
Example #4
Source File: error_mail.py From online-ratings with MIT License | 6 votes |
def email_exception(exception): '''Handles the exception message from Flask by sending an email to the recipients defined in config.ADMINS ''' msg = Message("[AGA Online Ratings|Flask] Exception: %s" % exception.__class__.__name__, recipients=current_app.config['ADMINS']) msg_contents = [ 'Traceback:', '='*80, traceback.format_exc(), ] msg_contents.append('\n') msg_contents.append('Request Information:') msg_contents.append('='*80) for k, v in sorted(request.environ.items()): msg_contents.append('%s: %s' % (k, v)) msg.body = '\n'.join(msg_contents) + '\n' mail = current_app.extensions.get('mail') mail.send(msg)
Example #5
Source File: emails.py From contentdb with GNU General Public License v3.0 | 6 votes |
def sendVerifyEmail(newEmail, token): print("Sending verify email!") msg = Message("Verify email address", recipients=[newEmail]) msg.body = """ This email has been sent to you because someone (hopefully you) has entered your email address as a user's email. If it wasn't you, then just delete this email. If this was you, then please click this link to verify the address: {} """.format(abs_url_for('users.verify_email', token=token)) msg.html = render_template("emails/verify.html", token=token) mail.send(msg)
Example #6
Source File: emails.py From walle-web with Apache License 2.0 | 6 votes |
def send_email(recipient, subject, html_message, text_message): """ Send email from default sender to 'recipient' """ # Make sure that Flask-Mail has been initialized mail_engine = mail if not mail_engine: return 'Flask-Mail has not been initialized. Initialize Flask-Mail or disable USER_SEND_PASSWORD_CHANGED_EMAIL, USER_SEND_REGISTERED_EMAIL and USER_SEND_USERNAME_CHANGED_EMAIL' try: # Construct Flash-Mail message message = Message(subject, recipients=[recipient], html=html_message, body=text_message) return mail.send(message) # Print helpful error messages on exceptions except (socket.gaierror, socket.error) as e: return 'SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.' except smtplib.SMTPAuthenticationError: return 'SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.'
Example #7
Source File: utils.py From flask-unchained with MIT License | 6 votes |
def get_message_plain_text(msg: Message): """ Converts an HTML message to plain text. :param msg: A :class:`~flask_mail.Message` :return: The plain text message. """ if msg.body: return msg.body if BeautifulSoup is None or not msg.html: return msg.html plain_text = '\n'.join(line.strip() for line in BeautifulSoup(msg.html, 'lxml').text.splitlines()) return re.sub(r'\n\n+', '\n\n', plain_text).strip()
Example #8
Source File: views.py From Flask-Framework-Cookbook-Second-Edition with MIT License | 6 votes |
def send_mail(category_id, category_name): with app.app_context(): category = Category(category_name) category.id = category_id message = Message( "New category added", recipients=['some-receiver@domain.com'] ) message.body = render_template( "category-create-email-text.html", category=category ) message.html = render_template( "category-create-email-html.html", category=category ) mail.send(message)
Example #9
Source File: auth.py From flaskapp with MIT License | 6 votes |
def send_verification_email(user): """Send verification email to user """ # create email verification request r = EmailVerificationRequest(key=os.urandom(32).hex(), user=user) db.session.add(r) db.session.flush() # send email subject = 'Flaskapp Account: Please Confirm Email' msg = Message(subject, recipients=[user.email]) verify_url = url_for('.verify_email', key=r.key, email=user.email, \ _external=True) f = '/auth/verify-email-email' msg.body = render_template(f + '.txt', verify_url=verify_url) html = render_template(f + '.html', verify_url=verify_url) base_url = url_for('content.home', _external=True) msg.html = transform(html, base_url=base_url) mail.send(msg)
Example #10
Source File: test_upstream.py From flask-unchained with MIT License | 6 votes |
def test_unicode_headers(self): msg = Message(subject="subject", sender=u'ÄÜÖ → ✓ <from@example.com>', recipients=[u"Ä <t1@example.com>", u"Ü <t2@example.com>"], cc=[u"Ö <cc@example.com>"]) response = msg.as_string() a1 = sanitize_address(u"Ä <t1@example.com>") a2 = sanitize_address(u"Ü <t2@example.com>") h1_a = Header("To: %s, %s" % (a1, a2)) h1_b = Header("To: %s, %s" % (a2, a1)) a3 = sanitize_address(u"ÄÜÖ → ✓ <from@example.com>") h2 = Header("From: %s" % a3) h3 = Header("Cc: %s" % sanitize_address(u"Ö <cc@example.com>")) # Ugly, but there's no guaranteed order of the recipients in the header try: self.assertIn(h1_a.encode(), response) except AssertionError: self.assertIn(h1_b.encode(), response) self.assertIn(h2.encode(), response) self.assertIn(h3.encode(), response)
Example #11
Source File: utils.py From flask-unchained with MIT License | 6 votes |
def _send_mail(subject_or_message: Optional[Union[str, Message]] = None, to: Optional[Union[str, List[str]]] = None, template: Optional[str] = None, **kwargs): """ The default function used for sending emails. :param subject_or_message: A subject string, or for backwards compatibility with stock Flask-Mail, a :class:`~flask_mail.Message` instance :param to: An email address, or a list of email addresses :param template: Which template to render. :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message` """ subject_or_message = subject_or_message or kwargs.pop('subject') to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
Example #12
Source File: emails.py From zou with GNU Affero General Public License v3.0 | 6 votes |
def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): mail_default_sender = app.config["MAIL_DEFAULT_SENDER"] message = Message( sender="Kitsu Bot <%s>" % mail_default_sender, body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
Example #13
Source File: mail_util.py From flask-security with MIT License | 6 votes |
def send_mail( self, template, subject, recipient, sender, body, html, user, **kwargs ): """Send an email via the Flask-Mail extension. :param template: the Template name. The message has already been rendered however this might be useful to differentiate why the email is being sent. :param subject: Email subject :param recipient: Email recipient :param sender: who to send email as (see :py:data:`SECURITY_EMAIL_SENDER`) :param body: the rendered body (text) :param html: the rendered body (html) :param user: the user model """ from flask_mail import Message msg = Message(subject, sender=sender, recipients=[recipient]) msg.body = body msg.html = html mail = current_app.extensions.get("mail") mail.send(msg)
Example #14
Source File: test_upstream.py From flask-unchained with MIT License | 6 votes |
def test_bad_multiline_subject(self): msg = Message(subject="testing\r\n testing\r\n ", sender="from@example.com", body="testing", recipients=["to@example.com"]) self.assertRaises(BadHeaderError, self.mail.send, msg) msg = Message(subject="testing\r\n testing\r\n\t", sender="from@example.com", body="testing", recipients=["to@example.com"]) self.assertRaises(BadHeaderError, self.mail.send, msg) msg = Message(subject="testing\r\n testing\r\n\n", sender="from@example.com", body="testing", recipients=["to@example.com"]) self.assertRaises(BadHeaderError, self.mail.send, msg)
Example #15
Source File: test_upstream.py From flask-unchained with MIT License | 6 votes |
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="from@example.com", recipients=[u'ÄÜÖ → ✓ <to@example.com>'], body="testing") conn.send(msg) host.sendmail.assert_called_once_with( "from@example.com", ["=?utf-8?b?w4TDnMOWIOKGkiDinJM=?= <to@example.com>"], msg.as_bytes(), msg.mail_options, msg.rcpt_options )
Example #16
Source File: test_upstream.py From flask-unchained with MIT License | 6 votes |
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="from@example.com", recipients=["to@example.com"], body="testing") conn.send(msg) host.sendmail.assert_called_once_with( "from@example.com", ["to@example.com"], msg.as_bytes(), msg.mail_options, msg.rcpt_options )
Example #17
Source File: email.py From picoCTF with MIT License | 6 votes |
def send_deletion_notification(username, email, delete_reason): """ Send an email to notify that an account has been deleted. """ refresh_email_settings() settings = api.config.get_settings() body = settings["email"]["deletion_notification_body"].format( competition_name=settings["competition_name"], username=username, delete_reason=delete_reason, ) subject = "{} Account Deletion".format(settings["competition_name"]) message = Message(body=body, recipients=[email], subject=subject) mail.send(message)
Example #18
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_custom_subtype_without_attachment(self): msg = Message(sender="from@example.com", subject="testing", recipients=["to@example.com"], subtype="html") self.assertIn('Content-Type: text/html', msg.as_string())
Example #19
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_send_without_recipients(self): msg = Message(subject="testing", recipients=[], body="testing") self.assertRaises(ValueError, self.mail.send, msg)
Example #20
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_plain_message_with_attachments(self): msg = Message(sender="from@example.com", subject="subject", recipients=["to@example.com"], body="hello") msg.attach(data=b"this is a test", content_type="text/plain") self.assertIn('Content-Type: multipart/mixed', msg.as_string())
Example #21
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_message_str(self): msg = Message(sender="from@example.com", subject="subject", recipients=["to@example.com"], body="some plain text") self.assertEqual(msg.as_string(), str(msg))
Example #22
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_plain_message(self): plain_text = "Hello Joe,\nHow are you?" msg = Message(sender="from@example.com", subject="subject", recipients=["to@example.com"], body=plain_text) self.assertEqual(plain_text, msg.body) self.assertIn('Content-Type: text/plain', msg.as_string())
Example #23
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_fix_recipients_list(self): msg = Message(subject="test") msg.recipients = [["Test", "to@example.com"]] assert msg.recipients[0] == ("Test", "to@example.com")
Example #24
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_bcc(self): msg = Message(sender="from@example.com", subject="testing", recipients=["to@example.com"], body="testing", bcc=["tosomeoneelse@example.com"]) response = msg.as_string() self.assertNotIn("tosomeoneelse@example.com", str(response))
Example #25
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_emails_are_sanitized(self): msg = Message(subject="testing", sender="sender\r\n@example.com", reply_to="reply_to\r\n@example.com", recipients=["recipient\r\n@example.com"]) self.assertIn('sender@example.com', msg.as_string()) self.assertIn('reply_to@example.com', msg.as_string()) self.assertIn('recipient@example.com', msg.as_string())
Example #26
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_cc(self): msg = Message(sender="from@example.com", subject="testing", recipients=["to@example.com"], body="testing", cc=["tosomeoneelse@example.com"]) response = msg.as_string() self.assertIn("Cc: tosomeoneelse@example.com", str(response))
Example #27
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_bad_header_subject(self): msg = Message(subject="testing\r\n", sender="from@example.com", body="testing", recipients=["to@example.com"]) self.assertRaises(BadHeaderError, self.mail.send, msg)
Example #28
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_multiline_subject(self): msg = Message(subject="testing\r\n testing\r\n testing \r\n \ttesting", sender="from@example.com", body="testing", recipients=["to@example.com"]) self.mail.send(msg) response = msg.as_string() self.assertIn("From: from@example.com", str(response)) self.assertIn("testing\r\n testing\r\n testing \r\n \ttesting", str(response))
Example #29
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_bad_header_sender(self): msg = Message(subject="testing", sender="from@example.com\r\n", recipients=["to@example.com"], body="testing") self.assertIn('From: from@example.com', msg.as_string())
Example #30
Source File: test_upstream.py From flask-unchained with MIT License | 5 votes |
def test_bad_header_reply_to(self): msg = Message(subject="testing", sender="from@example.com", reply_to="evil@example.com\r", recipients=["to@example.com"], body="testing") self.assertIn('From: from@example.com', msg.as_string()) self.assertIn('To: to@example.com', msg.as_string()) self.assertIn('Reply-To: evil@example.com', msg.as_string())