diff --git a/mails/core.py b/mails/core.py index d901dad943a65688c9dbc0adef34565e315ea902..3a3493566e4239ad20cc257930484b32cf0587b3 100644 --- a/mails/core.py +++ b/mails/core.py @@ -52,15 +52,6 @@ class MailEngine: 'recipient_list': recipient_list, 'context_object_name': context_object_name, } - - # # Quick check given parameters - # if from_email: - # if not isinstance(from_email, str): - # raise TypeError('"from_email" argument must be a string') - # if recipient_list and not isinstance(recipient_list, list): - # raise TypeError('"recipient_list" argument must be a list') - # if bcc and not isinstance(bcc, list): - # raise TypeError('"bcc" argument must be a list') self.template_variables = kwargs def __repr__(self): @@ -238,180 +229,3 @@ class MailEngine: raise KeyError('The property (%s) does not exist.' % entry) return mail_to raise KeyError('Neither an email adress nor db instance is given.') - - # def pre_validation(self, *args, **kwargs): - # """Validate the incoming data to initiate a specific mail.""" - # self.mail_code = kwargs.pop('mail_code') - # self.instance = kwargs.pop('instance', None) - # kwargs['object'] = self.instance # Similar template nomenclature as Django. - # self.mail_data = { - # 'subject': kwargs.pop('subject', ''), - # 'to_address': kwargs.pop('to', ''), - # 'bcc_to': kwargs.pop('bcc', ''), - # 'from_address_name': kwargs.pop('from_name', 'SciPost'), - # 'from_address': kwargs.pop('from', 'no-reply@scipost.org'), - # } - # - # # Gather meta data - # json_location = '%s/templates/email/%s.json' % (settings.BASE_DIR, self.mail_code) - # - # try: - # self.mail_data.update(json.loads(open(json_location).read())) - # except OSError: - # if not self.mail_data['subject']: - # raise NotImplementedError(('You did not create a valid .html and .json file ' - # 'for mail_code: %s' % self.mail_code)) - # - # # Save central object/instance if not already - # self.instance = self.get_object(**kwargs) - # - # # Digest the templates - # if not self.delayed_processing: - # mail_template = loader.get_template('email/%s.html' % self.mail_code) - # if self.instance and self.mail_data.get('context_object'): - # kwargs[self.mail_data['context_object']] = self.instance - # self.mail_template = mail_template.render(kwargs) # Damn slow. - # - # # Gather Recipients data - # try: - # self.original_recipient = self._validate_single_entry(self.mail_data.get('to_address'))[0] - # except IndexError: - # self.original_recipient = '' - # - # self.subject = self.mail_data['subject'] - # - # def get_object(self, **kwargs): - # if self.instance: - # return self.instance - # - # if self.mail_data.get('context_object'): - # return kwargs.get(self.mail_data['context_object'], None) - # - # def _validate_single_entry(self, entry): - # """ - # entry -- raw email string or path or properties leading to email mail field - # - # Returns a list of email addresses found. - # """ - # if entry and self.instance: - # if re.match("[^@]+@[^@]+\.[^@]+", entry): - # # Email string - # return [entry] - # else: - # mail_to = self.instance - # for attr in entry.split('.'): - # try: - # mail_to = getattr(mail_to, attr) - # if inspect.ismethod(mail_to): - # mail_to = mail_to() - # except AttributeError: - # # Invalid property/mail - # return [] - # - # if not isinstance(mail_to, list): - # return [mail_to] - # else: - # return mail_to - # elif re.match("[^@]+@[^@]+\.[^@]+", entry): - # return [entry] - # else: - # return [] - # # - # def validate_bcc_list(self): - # """ - # bcc_to in the .json file may contain multiple raw email addreses or property paths to - # an email field. The different entries need to be comma separated. - # """ - # # Get recipients list. Try to send through BCC to prevent privacy issues! - # self.bcc_list = [] - # if self.mail_data.get('bcc_to'): - # for bcc_entry in self.mail_data['bcc_to'].split(','): - # self.bcc_list += self._validate_single_entry(bcc_entry) - # - # def validate_recipients(self): - # # Check the send list - # if isinstance(self.original_recipient, list): - # recipients = self.original_recipient - # elif not isinstance(self.original_recipient, str): - # try: - # recipients = list(self.original_recipient) - # except TypeError: - # recipients = [self.original_recipient] - # else: - # recipients = [self.original_recipient] - # recipients = list(recipients) - # - # # Check if email needs to be taken from an instance - # _recipients = [] - # for recipient in recipients: - # if isinstance(recipient, Contributor): - # _recipients.append(recipient.user.email) - # elif isinstance(recipient, get_user_model()): - # _recipients.append(recipient.email) - # elif isinstance(recipient, str): - # _recipients.append(recipient) - # self.recipients = _recipients - # - # def validate_message(self): - # if not self.html_message: - # self.html_message = self.mail_template - # handler = HTML2Text() - # self.message = handler.handle(self.html_message) - # - # def validate(self): - # """Execute different validation methods. - # - # Only to be used when the default data is used, eg. not in the EmailTemplateForm. - # """ - # self.validate_message() - # self.validate_bcc_list() - # self.validate_recipients() - # self.save_mail_data() - # - # def save_mail_data(self): - # """Save mail validated mail data; update default values of mail data.""" - # self.mail_data.update({ - # 'subject': self.subject, - # 'message': self.message, - # 'html_message': self.html_message, - # 'recipients': self.recipients, - # 'bcc_list': self.bcc_list, - # }) - # - # def set_alternative_sender(self, from_name, from_address): - # """TODO: REMOVE; DEPRECATED - # - # Set an alternative from address/name from the default values received from the json - # config file. The arguments only take raw string data, no methods/properties! - # """ - # self.mail_data['from_address_name'] = from_name - # self.mail_data['from_address'] = from_address - # - # def send(self): - # """Send the mail assuming `mail_data` is validated and complete.""" - # if self.mail_sent: - # # Prevent double sending when using a Django form. - # return - # - # email = EmailMultiAlternatives( - # self.mail_data['subject'], - # self.mail_data['message'], - # '%s <%s>' % (self.mail_data['from_address_name'], self.mail_data['from_address']), - # self.mail_data['recipients'], - # bcc=self.mail_data['bcc_list'], - # reply_to=[self.mail_data['from_address']], - # headers={ - # 'delayed_processing': self.delayed_processing, - # 'content_object': self.get_object(), - # 'mail_code': self.mail_code, - # }) - # - # # Send html version if available - # if 'html_message' in self.mail_data: - # email.attach_alternative(self.mail_data['html_message'], 'text/html') - # - # email.send(fail_silently=False) - # self.mail_sent = True - # - # if self.instance and hasattr(self.instance, 'mail_sent'): - # self.instance.mail_sent() diff --git a/mails/forms.py b/mails/forms.py index 5ff996511459f0e0e64dcbfe5894fceab5931c07..7d4337a49ce1633f7a90f8f17711f844ba79bcee 100644 --- a/mails/forms.py +++ b/mails/forms.py @@ -53,10 +53,6 @@ class EmailForm(forms.Form): self.fields['text'].initial = self.engine.mail_data['html_message'] self.fields['subject'].initial = self.engine.mail_data['subject'] - # if not self.original_recipient: - # self.fields['mail_field'].label = "Send this email to" - # self.fields['mail_field'].required = True - def is_valid(self): """Fallback used in CBVs.""" if super().is_valid(): @@ -79,75 +75,3 @@ class EmailForm(forms.Form): class EmailTemplateForm(forms.Form): """Deprecated.""" pass -# subject = forms.CharField(max_length=250, label="Subject*") -# text = forms.CharField(widget=SummernoteEditor, label="Text*") -# extra_recipient = forms.EmailField(label="Optional: bcc this email to", required=False) -# prefix = 'mail_form' -# -# def __init__(self, *args, **kwargs): -# self.pre_validation(*args, **kwargs) -# -# # This form shouldn't be is_bound==True is there is any non-relavant POST data given. -# data = args[0] if args else {} -# if not data: -# data = {} -# if '%s-subject' % self.prefix in data.keys(): -# data = { -# '%s-subject' % self.prefix: data.get('%s-subject' % self.prefix), -# '%s-text' % self.prefix: data.get('%s-text' % self.prefix), -# '%s-extra_recipient' % self.prefix: data.get('%s-extra_recipient' % self.prefix), -# } -# elif kwargs.get('data', False): -# data = { -# '%s-subject' % self.prefix: kwargs['data'].get('%s-subject' % self.prefix), -# '%s-text' % self.prefix: kwargs['data'].get('%s-text' % self.prefix), -# '%s-extra_recipient' % self.prefix: kwargs['data'].get('%s-extra_recipient' % self.prefix), -# } -# else: -# data = None -# super().__init__(data or None) -# -# if not self.original_recipient: -# self.fields['extra_recipient'].label = "Send this email to" -# self.fields['extra_recipient'].required = True -# -# # Set the data as initials -# self.fields['text'].initial = self.mail_template -# self.fields['subject'].initial = self.mail_data['subject'] -# -# def save_data(self): -# # Get text and html -# self.html_message = self.cleaned_data['text'] -# self.subject = self.cleaned_data['subject'] -# self.validate_message() -# self.validate_bcc_list() -# -# # Get recipients list. Try to send through BCC to prevent privacy issues! -# if self.cleaned_data.get('extra_recipient') and self.original_recipient: -# self.bcc_list.append(self.cleaned_data.get('extra_recipient')) -# elif self.cleaned_data.get('extra_recipient') and not self.original_recipient: -# self.original_recipient = [self.cleaned_data.get('extra_recipient')] -# elif not self.original_recipient: -# self.add_error('extra_recipient', 'Please fill the bcc field to send the mail.') -# -# self.validate_recipients() -# self.save_mail_data() -# -# def clean(self): -# data = super().clean() -# self.save_data() -# return data -# -# def save(self): -# """Because Django uses .save() by default...""" -# self.send() -# return self.instance -# -# -# -# class HiddenDataForm(forms.Form): -# def __init__(self, form, *args, **kwargs): -# super().__init__(form.data, *args, **kwargs) -# for name, field in form.fields.items(): -# self.fields[name] = field -# self.fields[name].widget = forms.HiddenInput() diff --git a/mails/views.py b/mails/views.py index a004f6045c93df5895e3862622c262df5fd305ea..e00c7bf42862e55882c53aed93c6e6a6f5f8d817 100644 --- a/mails/views.py +++ b/mails/views.py @@ -2,9 +2,6 @@ __copyright__ = "Copyright © Stichting SciPost (SciPost Foundation)" __license__ = "AGPL v3" -# from django.contrib import messages -# from django.db import models -# from django.http import HttpRequest from django.shortcuts import render from django.views.generic.edit import UpdateView @@ -26,13 +23,6 @@ class MailView(UpdateView): kwargs['mail_config'] = self.mail_config return kwargs - # def form_invalid(self, form): - # """If the form is valid, save the associated model.""" - # raise - # self.object = form.save() - # return super().form_valid(form) - - class TestView(MailView): """To be removed; exists for testing purposes only.""" @@ -92,112 +82,8 @@ class MailEditorSubview: class MailEditingSubView: """Deprecated.""" pass -# alternative_from_address = None # Tuple: ('from_name', 'from_address') -# -# def __init__(self, request, mail_code, **kwargs): -# self.request = request -# self.context = kwargs.get('context', {}) -# # self.template_name = kwargs.get('template', 'mails/mail_form.html') -# self.header_template = kwargs.get('header_template', '') -# self.mail_form = EmailForm(request.POST or None, mail_code=mail_code, **kwargs) -# -# @property -# def recipients_string(self): -# return ', '.join(getattr(self.mail_form, 'mail_data', {}).get('recipients', [''])) -# -# def add_form(self, form): -# """DEPRECATED""" -# self.context['transfer_data_form'] = HiddenDataForm(form) -# -# def set_alternative_sender(self, from_name, from_address): -# """DEPRECATED""" -# self.alternative_from_address = (from_name, from_address) -# -# def is_valid(self): -# return self.mail_form.is_valid() -# -# def send(self): -# if self.alternative_from_address: -# self.mail_form.set_alternative_sender( -# self.alternative_from_address[0], self.alternative_from_address[1]) -# return self.mail_form.send() -# -# def return_render(self): -# self.context['form'] = self.mail_form -# self.context['header_template'] = self.header_template -# if hasattr(self.mail_form, 'instance') and self.mail_form.instance: -# self.context['object'] = self.mail_form.instance -# else: -# self.context['object'] = None -# return render(self.request, self.template_name, self.context) class MailEditorMixin: """Deprecated.""" pass - # """ - # Use MailEditorMixin in edit CBVs to automatically implement the mail editor as - # a post-form_valid hook. - # - # The view must specify the `mail_code` variable. - # """ - # object = None - # mail_form = None - # has_permission_to_send_mail = True - # alternative_from_address = None # Tuple: ('from_name', 'from_address') - # - # def __init__(self, *args, **kwargs): - # if not self.mail_code: - # raise AttributeError(self.__class__.__name__ + ' object has no attribute `mail_code`') - # super().__init__(*args, **kwargs) - # - # def get_template_names(self): - # """ - # The mail editor form has its own template. - # """ - # if self.mail_form and not self.mail_form.is_valid(): - # return ['mails/mail_form.html'] - # return super().get_template_names() - # - # def post(self, request, *args, **kwargs): - # """ - # Handle POST requests, but interpect the data if the mail form data isn't valid. - # """ - # if not self.has_permission_to_send_mail: - # # Don't use the mail form; don't send out the mail. - # return super().post(request, *args, **kwargs) - # self.object = self.get_object() - # form = self.get_form() - # if form.is_valid(): - # self.mail_form = EmailForm(request.POST or None, mail_code=self.mail_code, - # instance=self.object) - # if self.mail_form.is_valid(): - # return self.form_valid(form) - # - # return self.render_to_response( - # self.get_context_data(form=self.mail_form, - # transfer_data_form=HiddenDataForm(form))) - # else: - # return self.form_invalid(form) - # - # def form_valid(self, form): - # """ - # If both the regular form and mailing form are valid, save the form and run the mail form. - # """ - # # Don't use the mail form; don't send out the mail. - # if not self.has_permission_to_send_mail: - # return super().form_valid(form) - # - # if self.alternative_from_address: - # # Set different from address if given. - # self.mail_form.set_alternative_sender( - # self.alternative_from_address[0], self.alternative_from_address[1]) - # - # response = super().form_valid(form) - # try: - # self.mail_form.send() - # except AttributeError: - # # self.mail_form is None - # raise AttributeError('Did you check the order in which MailEditorMixin is used?') - # messages.success(self.request, 'Mail sent') - # return response