email.py 2.5 KB

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