示例#1
0
    def dispatch(self, object, *args, **kwargs):
        self.object = object
        languages = [get_language(), self.fallback_language]
        receivers = self.get_receiver_emails()
        context = self.get_context()
        context.update(kwargs)
        attachments = self.get_attachments()
        template = self.template_name

        subject = select_template([
            'emails/{}.{}.subject'.format(template, lang) for lang in languages
        ])
        plaintext = select_template([
            'emails/{}.{}.txt'.format(template, lang) for lang in languages
         ])
        html = select_template([
            'emails/{}.{}.html'.format(template, lang) for lang in languages
        ])
        mail = EmailMultiAlternatives(
            subject=subject.render(context).strip(),
            body=plaintext.render(context),
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=receivers,
        )
        if len(attachments) > 0:
            mail.mixed_subtype = 'related'

            for attachment in attachments:
                mail.attach(attachment)

        mail.attach_alternative(html.render(context), 'text/html')
        mail.send()
        return mail
示例#2
0
 def send_bulk_emails(cls, subject, body, from_email, to_email_list, dict_images=None):
     msg_list = []
     for email in to_email_list:
         msg = EmailMultiAlternatives(subject, body, from_email, [email])
         if dict_images:
             for key in dict_images.keys():
                 image_path = dict_images.get(key)
                 fp = open(image_path, 'rb')
                 mimeImage = MIMEImage(fp.read())
                 fp.close()
                 mimeImage.add_header('Content-ID', '<'+ key +'>')
                 msg.attach(mimeImage)
         msg.attach_alternative(body, "text/html")
         msg.encoding = "utf-8"
         msg.mixed_subtype = 'related'
         #msg.content_subtype = "html" # Doute
         msg_list.append(msg)
     
     connection = mail.get_connection()
     connection.open()
     ten_msg_list = []
     while msg_list <> []:
         if len(ten_msg_list) < 1000:
             ten_msg_list.append(msg_list[0])
             msg_list.pop(0)
         else:
             connection.send_messages(ten_msg_list)
             ten_msg_list = []
     if ten_msg_list <> []:
         connection.send_messages(ten_msg_list)
     connection.close()
示例#3
0
def send_application_proposal(app_proposal):
    from mcod.datasets.models import Dataset
    conn = get_connection(settings.EMAIL_BACKEND)
    emails = [
        config.CONTACT_MAIL,
    ]

    title = app_proposal["title"]
    applicant_email = app_proposal.get('applicant_email', "")
    img_data = app_proposal.get('image', None)
    if img_data:
        data = img_data.split(';base64,')[-1].encode('utf-8')
        decoded_img = base64.b64decode(data)

        image = MIMEImage(decoded_img)
        img_name = slugify(app_proposal['title'])
        filename = f"{img_name}.{image.get_content_subtype()}"
        image.add_header('content-disposition',
                         'attachment',
                         filename=filename)
        image.add_header('Content-ID', '<app-logo>')

    datasets = Dataset.objects.filter(id__in=app_proposal.get('datasets', []))
    app_proposal['datasets'] = '\n'.join(f"{settings.BASE_URL}/dataset/{ds.id}"
                                         for ds in datasets)
    app_proposal['dataset_links'] = '<br />'.join(
        f"<a href=\"{settings.BASE_URL}/dataset/{ds.id}\">{ds.title}</a>\n"
        for ds in datasets)

    external_datasets = app_proposal.get('external_datasets', [])
    app_proposal['external_datasets'] = '\n'.join(
        f"{eds.get('title', '(nie nazwany)')}: {eds.get('url', '(nie podano url)')}\n"
        for eds in external_datasets)
    app_proposal['external_dataset_links'] = '<br />'.join((
        f"{eds.get('title')}: <a href=\"{eds.get('url')}\">{eds.get('url')}</a>\n"
        if 'url' in eds else eds.get('title')) for eds in external_datasets)
    app_proposal['keywords'] = ', '.join(app_proposal.get('keywords', tuple()))
    app_proposal['host'] = settings.BASE_URL

    msg_plain = render_to_string('mails/propose-application.txt', app_proposal)
    msg_html = render_to_string('mails/propose-application.html', app_proposal)

    if settings.DEBUG and config.TESTER_EMAIL:
        emails = [config.TESTER_EMAIL]

    mail = EmailMultiAlternatives(f'Zgłoszono propozycję aplikacji {title}',
                                  msg_plain,
                                  from_email=config.NO_REPLY_EMAIL,
                                  to=emails,
                                  connection=conn)
    mail.mixed_subtype = 'related'
    mail.attach_alternative(msg_html, 'text/html')
    if img_data:
        mail.attach(image)
    mail.send()

    return {'application_proposed': f'{title} - {applicant_email}'}
示例#4
0
    def dispatch(self, object, *args, **kwargs):
        self.object = object
        self.kwargs = kwargs
        receivers = self.get_receivers()
        context = self.get_context()
        context.update(kwargs)
        attachments = self.get_attachments()
        template = self.template_name

        mails = []
        mail_exceptions = []
        for receiver in receivers:
            context['receiver'] = receiver
            (subject, text, html) = self.render(template, context)
            context.pop('receiver')

            if hasattr(receiver, 'email'):
                to_address = receiver.email
            else:
                to_address = receiver

            subject_clean = re.sub(r'[\r\n]', '', subject).strip()

            mail = EmailMultiAlternatives(
                subject=subject_clean,
                body=text,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[to_address],
                reply_to=self.get_reply_to(),
            )

            if len(attachments) > 0:
                mail.mixed_subtype = 'related'

                for attachment in attachments:
                    mail.attach(attachment)

            mail.attach_alternative(html, 'text/html')
            mails.append(mail)

            if self.enable_reporting:
                try:
                    mail.send()
                except SMTPException as exc:
                    mail_exceptions.append(exc)
            else:
                mail.send()

        if self.enable_reporting:
            self.handle_report(mails, mail_exceptions)

        return mails
示例#5
0
    def email_two_factor_success(self, user: get_user_model(), token):
        """ Sends email containing one-time token """

        subject = "Two-Factor Authentication Successful"
        msg = EmailMultiAlternatives(
            subject=subject,
            body=self.build_html_content(user, token),
            from_email=settings.DEFAULT_FROM_EMAIL_SES,
            to=[user.email],
        )
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()
示例#6
0
    def email_two_factor_token(self, user: get_user_model(), token):
        """ Sends email containing current token """

        subject = "Your One Time Token"
        msg = EmailMultiAlternatives(
            subject=subject,
            body=self.build_html_content(user, token),
            from_email=settings.DEFAULT_FROM_EMAIL_SES,
            to=[user.email],
        )
        msg.content_subtype = 'html'
        msg.mixed_subtype = 'related'
        msg.send()
示例#7
0
def send_emails_from_template(to_emails, from_email, subject,
                              markdown_template=None, text_template=None,
                              html_template=None, fail_silently=False,
                              context=None, attachments=None, **kwargs):
    """Send many emails from single template.  Each email address listed in the
    ``to_emails`` will receive an separate email.

    :param to_emails: list of email address to send the email to
    :param from_email: the email address the email will be from
    :param subject: the subject of the email
    :param markdown_template: the markdown syntax template to use for the
        email.  If provided, this will generate both the text and html versions
        of the email. You must have the "markdown" library installed in order
        to use this. pip install markdown.
    :param text_template: the template for the text version of the email. This
        can be omitted if the markdown_template is provided.
    :param html_template: the template for the html version of the email. This
        can be omitted if the markdown_template is provided.
    :param context: the context for the email templates
    :param attachments: list of additional attachments to add to the email
        (example: email.mime.image.MIMEImage object).  The attachments will be
        added to each email sent.
    """
    if not to_emails:
        return

    if context is None:
        context = {}

    if markdown_template:
        try:
            from markdown import markdown
        except ImportError:
            raise ImportError(
                'The application is attempting to send an email by using the '
                '"markdown" library, but markdown is not installed.  Please '
                'install it. See: '
                'http://pythonhosted.org/Markdown/install.html'
            )

        base_html_template = getattr(settings,
                                     'CORE_BASE_HTML_EMAIL_TEMPLATE',
                                     'django_core/mail/base_email.html')

        text_content = render_to_string(markdown_template, context)
        context['email_content'] = markdown(text_content)
        html_content = render_to_string(base_html_template, context)
    else:
        text_content = render_to_string(text_template, context)
        html_content = render_to_string(html_template, context)

    emails = []

    for email_address in to_emails:
        email = EmailMultiAlternatives(
            subject=subject,
            body=text_content,
            from_email=from_email,
            to=[email_address],
            alternatives=[(html_content, 'text/html')]
        )

        if attachments:
            email.mixed_subtype = 'related'

            for attachment in attachments:
                email.attach(attachment)

        emails.append(email)

    connection = mail.get_connection()

    connection.open()
    connection.send_messages(emails)
    connection.close()
示例#8
0
def send_emails_from_template(to_emails,
                              from_email,
                              subject,
                              markdown_template=None,
                              text_template=None,
                              html_template=None,
                              fail_silently=False,
                              context=None,
                              attachments=None,
                              **kwargs):
    """Send many emails from single template.  Each email address listed in the
    ``to_emails`` will receive an separate email.

    :param to_emails: list of email address to send the email to
    :param from_email: the email address the email will be from
    :param subject: the subject of the email
    :param markdown_template: the markdown syntax template to use for the
        email.  If provided, this will generate both the text and html versions
        of the email. You must have the "markdown" library installed in order
        to use this. pip install markdown.
    :param text_template: the template for the text version of the email. This
        can be omitted if the markdown_template is provided.
    :param html_template: the template for the html version of the email. This
        can be omitted if the markdown_template is provided.
    :param context: the context for the email templates
    :param attachments: list of additional attachments to add to the email
        (example: email.mime.image.MIMEImage object).  The attachments will be
        added to each email sent.
    """
    if not to_emails:
        return

    if context is None:
        context = {}

    if markdown_template:
        try:
            from markdown import markdown
        except ImportError:
            raise ImportError(
                'The application is attempting to send an email by using the '
                '"markdown" library, but markdown is not installed.  Please '
                'install it. See: '
                'http://pythonhosted.org/Markdown/install.html')

        base_html_template = getattr(settings, 'CORE_BASE_HTML_EMAIL_TEMPLATE',
                                     'django_core/mail/base_email.html')

        text_content = render_to_string(markdown_template, context)
        context['email_content'] = markdown(text_content)
        html_content = render_to_string(base_html_template, context)
    else:
        text_content = render_to_string(text_template, context)
        html_content = render_to_string(html_template, context)

    emails = []

    for email_address in to_emails:
        email = EmailMultiAlternatives(subject=subject,
                                       body=text_content,
                                       from_email=from_email,
                                       to=[email_address],
                                       alternatives=[(html_content,
                                                      'text/html')])

        if attachments:
            email.mixed_subtype = 'related'

            for attachment in attachments:
                email.attach(attachment)

        emails.append(email)

    connection = mail.get_connection()

    connection.open()
    connection.send_messages(emails)
    connection.close()
示例#9
0
    def send_application_proposal_mail(cls, data):
        dataset_model = apps.get_model('datasets.Dataset')
        conn = get_connection(settings.EMAIL_BACKEND)

        title = data['title']
        img_data = data.get('image')
        illustrative_graphics = data.get('illustrative_graphics')
        img_name = cls.slugify(
            title) if img_data or illustrative_graphics else None

        if img_data:
            _data = img_data.split(';base64,')[-1].encode('utf-8')
            image = MIMEImage(base64.b64decode(_data))
            filename = f"{img_name}.{image.get_content_subtype()}"
            image.add_header('content-disposition',
                             'attachment',
                             filename=filename)
            image.add_header('Content-ID', '<app-logo>')

        if illustrative_graphics:
            _data = illustrative_graphics.split(';base64,')[-1].encode('utf-8')
            illustrative_graphics_img = MIMEImage(base64.b64decode(_data))
            filename = f'{img_name}_illustrative-graphics.{illustrative_graphics_img.get_content_subtype()}'
            illustrative_graphics_img.add_header('content-disposition',
                                                 'attachment',
                                                 filename=filename)
            illustrative_graphics_img.add_header('Content-ID',
                                                 '<illustrative-graphics>')

        datasets = dataset_model.objects.filter(
            id__in=data.get('datasets', []))
        data['datasets'] = '\n'.join(ds.frontend_absolute_url
                                     for ds in datasets)
        data['dataset_links'] = '<br />'.join(
            f"<a href=\"{ds.frontend_absolute_url}\">{ds.title}</a>\n"
            for ds in datasets)

        external_datasets = data.get('external_datasets', [])
        data['external_datasets'] = '\n'.join(
            f"{eds.get('title', '(nienazwany)')}: {eds.get('url', '(nie podano url)')}\n"
            for eds in external_datasets)
        data['external_dataset_links'] = '<br />'.join((
            f"{eds.get('title')}: <a href=\"{eds.get('url')}\">{eds.get('url')}</a>\n"
            if 'url' in eds else eds.get('title')
        ) for eds in external_datasets)
        data['host'] = settings.BASE_URL

        emails = [
            config.TESTER_EMAIL
        ] if settings.DEBUG and config.TESTER_EMAIL else [config.CONTACT_MAIL]
        html_template = 'applicationproposal' if is_enabled(
            'S39_mail_layout.be') else 'propose-application'
        with translation.override('pl'):
            msg_plain = render_to_string('mails/propose-application.txt', data)
            msg_html = render_to_string(f'mails/{html_template}.html', data)
            mail = EmailMultiAlternatives(
                'Zgłoszono propozycję aplikacji {}'.format(
                    title.replace('\n', ' ').replace('\r', '')),
                msg_plain,
                from_email=config.NO_REPLY_EMAIL,
                to=emails,
                connection=conn)
            mail.mixed_subtype = 'related'
            mail.attach_alternative(msg_html, 'text/html')
            if img_data:
                mail.attach(image)
            if illustrative_graphics:
                mail.attach(illustrative_graphics_img)
            mail.send()