email.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.email
  4. ~~~~~~~~~~~~~
  5. This module adds the functionality to send emails
  6. :copyright: (c) 2014 by the FlaskBB Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from flask import render_template
  10. from flask_mail import Message
  11. from flask_babelplus import lazy_gettext as _
  12. from flaskbb.extensions import mail
  13. from flaskbb.utils.tokens import make_token
  14. def send_reset_token(user):
  15. """Sends the reset token to the user's email address.
  16. :param user: The user object to whom the email should be sent.
  17. """
  18. token = make_token(user=user, operation="reset_password")
  19. send_email(
  20. subject=_("Password Recovery Confirmation"),
  21. recipients=[user.email],
  22. text_body=render_template(
  23. "email/reset_password.txt",
  24. user=user,
  25. token=token
  26. ),
  27. html_body=render_template(
  28. "email/reset_password.html",
  29. user=user,
  30. token=token
  31. )
  32. )
  33. def send_activation_token(user):
  34. """Sends the activation token to the user's email address.
  35. :param user: The user object to whom the email should be sent.
  36. """
  37. token = make_token(user=user, operation="activate_account")
  38. send_email(
  39. subject=_("Account Activation"),
  40. recipients=[user.email],
  41. text_body=render_template(
  42. "email/activate_account.txt",
  43. user=user,
  44. token=token
  45. ),
  46. html_body=render_template(
  47. "email/activate_account.html",
  48. user=user,
  49. token=token
  50. )
  51. )
  52. def send_email(subject, recipients, text_body, html_body, sender=None):
  53. """Sends an email to the given recipients.
  54. :param subject: The subject of the email.
  55. :param recipients: A list of recipients.
  56. :param text_body: The text body of the email.
  57. :param html_body: The html body of the email.
  58. :param sender: A two-element tuple consisting of name and address.
  59. If no sender is given, it will fall back to the one you
  60. have configured with ``MAIL_DEFAULT_SENDER``.
  61. """
  62. msg = Message(subject, recipients=recipients, sender=sender)
  63. msg.body = text_body
  64. msg.html = html_body
  65. mail.send(msg)