email.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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, celery
  13. from flaskbb.utils.tokens import make_token
  14. @celery.task
  15. def send_reset_token(user):
  16. """Sends the reset token to the user's email address.
  17. :param user: The user object to whom the email should be sent.
  18. """
  19. token = make_token(user=user, operation="reset_password")
  20. send_email(
  21. subject=_("Password Recovery Confirmation"),
  22. recipients=[user.email],
  23. text_body=render_template(
  24. "email/reset_password.txt",
  25. user=user,
  26. token=token
  27. ),
  28. html_body=render_template(
  29. "email/reset_password.html",
  30. user=user,
  31. token=token
  32. )
  33. )
  34. @celery.task
  35. def send_activation_token(user):
  36. """Sends the activation token to the user's email address.
  37. :param user: The user object to whom the email should be sent.
  38. """
  39. token = make_token(user=user, operation="activate_account")
  40. send_email(
  41. subject=_("Account Activation"),
  42. recipients=[user.email],
  43. text_body=render_template(
  44. "email/activate_account.txt",
  45. user=user,
  46. token=token
  47. ),
  48. html_body=render_template(
  49. "email/activate_account.html",
  50. user=user,
  51. token=token
  52. )
  53. )
  54. @celery.task
  55. def send_async_email(*args, **kwargs):
  56. send_email(*args, **kwargs)
  57. def send_email(subject, recipients, text_body, html_body, sender=None):
  58. """Sends an email to the given recipients.
  59. :param subject: The subject of the email.
  60. :param recipients: A list of recipients.
  61. :param text_body: The text body of the email.
  62. :param html_body: The html body of the email.
  63. :param sender: A two-element tuple consisting of name and address.
  64. If no sender is given, it will fall back to the one you
  65. have configured with ``MAIL_DEFAULT_SENDER``.
  66. """
  67. msg = Message(subject, recipients=recipients, sender=sender)
  68. msg.body = text_body
  69. msg.html = html_body
  70. mail.send(msg)