IdHub/idhub/email/views.py

69 lines
2.4 KiB
Python
Raw Normal View History

2023-12-15 13:08:03 +00:00
import logging
2023-10-18 15:30:11 +00:00
from django.conf import settings
from django.template import loader
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
2023-12-15 13:08:03 +00:00
logger = logging.getLogger(__name__)
2023-10-18 15:30:11 +00:00
class NotifyActivateUserByEmail:
2024-01-19 19:37:17 +00:00
subject_template_name = 'idhub/admin/registration/activate_user_subject.txt'
email_template_name = 'idhub/admin/registration/activate_user_email.txt'
html_email_template_name = 'idhub/admin/registration/activate_user_email.html'
def get_email_context(self, user, token):
2023-10-18 15:30:11 +00:00
"""
Define a new context with a token for put in a email
when send a email for add a new password
"""
protocol = 'https' if self.request.is_secure() else 'http'
current_site = get_current_site(self.request)
site_name = current_site.name
domain = current_site.domain
2024-01-19 19:37:17 +00:00
if not token:
token = default_token_generator.make_token(user)
2023-10-18 15:30:11 +00:00
context = {
'email': user.email,
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
2024-01-19 19:37:17 +00:00
'token': token,
2023-10-18 15:30:11 +00:00
'protocol': protocol,
}
return context
2024-01-19 19:37:17 +00:00
def send_email(self, user, token=None):
2023-10-18 15:30:11 +00:00
"""
Send a email when a user is activated.
"""
2024-01-19 19:37:17 +00:00
context = self.get_email_context(user, token)
subject = loader.render_to_string(self.subject_template_name, context)
2023-10-18 15:30:11 +00:00
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
2024-01-19 19:37:17 +00:00
body = loader.render_to_string(self.email_template_name, context)
2023-10-18 15:30:11 +00:00
from_email = settings.DEFAULT_FROM_EMAIL
to_email = user.email
email_message = EmailMultiAlternatives(
subject, body, from_email, [to_email])
2024-01-19 19:37:17 +00:00
html_email = loader.render_to_string(self.html_email_template_name, context)
2023-10-18 15:30:11 +00:00
email_message.attach_alternative(html_email, 'text/html')
2023-11-16 13:30:19 +00:00
try:
if settings.DEVELOPMENT:
2023-12-15 13:08:03 +00:00
logger.warning(to_email)
logger.warning(body)
2023-11-16 13:30:19 +00:00
return
2023-10-18 15:30:11 +00:00
2023-11-16 13:30:19 +00:00
email_message.send()
2023-12-15 13:08:03 +00:00
except Exception as err:
logger.error(err)
2023-11-16 13:30:19 +00:00
return