Example #1
0
    def send(self, messages, recipients, *args, **kwargs):
        subject = ' '.join(messages['subject.txt'].splitlines())
        body_html = messages['message.html']
        body = self._strip_tags(body_html)
        addresses = self.get_addresses(recipients)
        if addresses:
            notification_type = ''
            if 'notification_type' in kwargs:
                notification_type = kwargs.pop('notification_type')

            email = EmailMultiAlternatives(subject, body,
                                           settings.DEFAULT_FROM_EMAIL,
                                           addresses)
            if notification_type:
                email.extra_headers = {
                    'X-SMTPAPI': '{"category": "%s"}' % notification_type
                }
            email.attach_alternative(body_html, "text/html")
            print 'Sending email to: ' + str(addresses)
            while True:
                try:
                    email.send()
                    print 'Email Sent Ok!'
                    break
                except:
                    print 'Waiting to try again'
                    import time
                    time.sleep(4)

            return email
def initialise_email(bookmark, campaign_source):
    campaign_name = "monthly alert %s" % date.today().strftime("%Y-%m-%d")
    email_id = "/email/%s/%s/%s" % (campaign_name, campaign_source,
                                    bookmark.id)
    if isinstance(bookmark, NCSOConcessionBookmark):
        subject_prefix = "Your update about "
    else:
        subject_prefix = "Your monthly update about "
    msg = EmailMultiAlternatives(
        truncate_subject(subject_prefix, bookmark.name),
        "...placeholder...",
        settings.DEFAULT_FROM_EMAIL,
        [bookmark.user.email],
    )
    metadata = {
        "subject": msg.subject,
        "campaign_name": campaign_name,
        "campaign_source": campaign_source,
        "email_id": email_id,
    }
    msg.metadata = metadata
    msg.qs = ga_tracking_qs(metadata)
    # Set the message id now, so we can reuse it
    msg.extra_headers = {"message-id": msg.message()["message-id"]}
    return msg
    def send(self, messages, recipients, *args, **kwargs):
        subject = ' '.join(messages['subject.txt'].splitlines())
        body_html = messages['message.html']
        body = self._strip_tags(body_html)
        addresses = self.get_addresses(recipients)
        if addresses:
            notification_type = ''
            if 'notification_type' in kwargs:
                notification_type = kwargs.pop('notification_type')

            email = EmailMultiAlternatives(
                subject, body, settings.DEFAULT_FROM_EMAIL, addresses)
            if notification_type:
                email.extra_headers = {'X-SMTPAPI':'{"category": "%s"}' % notification_type}
            email.attach_alternative(body_html, "text/html")
            print 'Sending email to: ' + str(addresses)
            while True:
                try:
                    email.send()
                    print 'Email Sent Ok!'
                    break
                except:
                    print 'Waiting to try again'
                    import time; time.sleep(4)

            return email
Example #4
0
    def message(self):
        m = EmailMultiAlternatives(self.subject, self.body)
        m.to = self.to
        m.cc = self.cc
        m.bcc = self.bcc
        m.from_email = self.from_email

        m.alternatives = \
            [(att.content, att.mimetype) for att in self.alternatives()]
        for attachment in self.attachments():
            m.attach(attachment.filename, attachment.content.read(),
                     attachment.mimetype)

        m.extra_headers = self.extra_headers

        return m
def _view_subscriber_verification_context(request, form_class):

    """
    A simple view that shows a form for subscription for the newsletter.
    """
    context = {}

    if request.POST:
        context['form'] = form_class(request.POST)
        if context['form'].is_valid():
            subscription = SubscriberVerification()
            contact = context['form'].save()                
            subscription.contact = context['form'].instance
            subscription.save()

            link_id = str(subscription.link_id)

            mail_context = Context({
                'base_url': "%s://%s" % ("https" if request.is_secure() else "http", request.get_host()),
                'link_id': link_id,
            })

            content_html = render_to_string('newsletter/newsletter_mail_verification.html', mail_context)

            content_text = html2text(content_html)

            message = EmailMultiAlternatives()
            message.from_email = smart_str(DEFAULT_HEADER_REPLY)
            message.extra_headers = {'Reply-to': smart_str(DEFAULT_HEADER_REPLY)}
            message.to = [smart_str(context['form'].instance.email)]
            
            message.subject = render_to_string('newsletter/newsletter_mail_verification_subject.html', context)

            message.body = smart_str(content_text)
            message.attach_alternative(smart_str(content_html), "text/html")       

            try:
                message.send()
            except Exception, e:
                print e

            context['send'] = True
Example #6
0
def make_email_with_campaign(bookmark, campaign_source):
    campaign_name = "monthly alert %s" % date.today().strftime("%Y-%m-%d")
    email_id = "/email/%s/%s/%s" % (campaign_name, campaign_source,
                                    bookmark.id)
    subject_prefix = 'Your monthly update about '
    msg = EmailMultiAlternatives(
        truncate_subject(subject_prefix, bookmark.name),
        "This email is only available in HTML", settings.SUPPORT_EMAIL,
        [bookmark.user.email])
    metadata = {
        "subject": msg.subject,
        "campaign_name": campaign_name,
        "campaign_source": campaign_source,
        "email_id": email_id
    }
    msg.metadata = metadata
    msg.qs = ga_tracking_qs(metadata)
    # Set the message id now, so we can reuse it
    msg.extra_headers = {'message-id': msg.message()['message-id']}
    return msg
Example #7
0
    def test_reply_to_property(self):
        backend = SendGridBackend()

        mail = EmailMultiAlternatives(subject='Your subject',
                                      body='Simple text body',
                                      from_email='*****@*****.**',
                                      to=[
                                          '*****@*****.**',
                                      ])
        mail.extra_headers = {'Reply-To': '*****@*****.**'}

        prepared_mail = backend._build_sg_mail(mail)

        # Check for propper assembly
        self.assertEqual(
            prepared_mail, {
                'from': {
                    'email': '*****@*****.**'
                },
                'subject':
                'Your subject',
                'personalizations': [{
                    'to': [{
                        'email': '*****@*****.**'
                    }],
                    'subject':
                    'Your subject'
                }],
                'content': [{
                    'type': 'text/plain',
                    'value': 'Simple text body'
                }],
                'reply_to': {
                    'email': '*****@*****.**'
                }
            })

        # Send to SendGrid
        response = backend.sg.client.mail.send.post(request_body=prepared_mail)
        self.assertEqual(response.status_code, 202)
    def prepare_message(self, contact):

        from emencia.utils.tokens import tokenize
        from emencia.utils.newsletter import fix_tinymce_links

        uidb36, token = tokenize(contact)

        base_url = self.base_url

        context = Context({
            'contact':
            contact,
            'base_url':
            base_url,
            'newsletter':
            self,
            'tracking_image_format':
            TRACKING_IMAGE_FORMAT,
            'uidb36':
            uidb36,
            'token':
            token,
            'UNIQUE_KEY':
            ''.join(sample(UNIQUE_KEY_CHAR_SET, UNIQUE_KEY_LENGTH))
        })

        message = EmailMultiAlternatives()
        message.from_email = smart_str(self.header_sender)
        message.extra_headers = {'Reply-to': smart_str(self.header_reply)}
        message.to = [contact.mail_format()]

        # Render only the message provided by the user with the WYSIWYG editor
        message_template = Template(fix_tinymce_links(self.content))
        message_content = message_template.render(context)

        context.update({'message': message_content})

        # link_site_exist = False
        link_site = render_to_string('newsletter/newsletter_link_site.html',
                                     context)
        context.update({'link_site': link_site})

        if INCLUDE_UNSUBSCRIPTION:
            unsubscription = render_to_string(
                'newsletter/newsletter_link_unsubscribe.html', context)
            context.update({'unsubscription': unsubscription})

        if TRACKING_IMAGE:
            image_tracking = render_to_string(
                'newsletter/newsletter_image_tracking.html', context)
            context.update({'image_tracking': image_tracking})

        content_template = get_template('mailtemplates/{0}/{1}'.format(
            self.template, 'index.html'))
        content = content_template.render(context)

        if TRACKING_LINKS:
            from emencia.utils.newsletter import track_links
            content = track_links(content, context)

        content = smart_unicode(content)

        p = Premailer(content, base_url=base_url, preserve_internal_links=True)
        content = p.transform()

        # newsletter_template = Template(self.content)

        message.body = html2text(content)
        message.attach_alternative(smart_str(content), "text/html")

        title_template = Template(self.title)
        title = title_template.render(context)
        message.subject = title

        for attachment in self.attachments:
            message.attach(attachment)

        return message
    def prepare_message(self, contact):

        from emencia.utils.tokens import tokenize
        from emencia.utils.newsletter import fix_tinymce_links

        uidb36, token = tokenize(contact)

        base_url = self.base_url

        context = Context({
            'contact': contact,
            'base_url': base_url,
            'newsletter': self,
            'tracking_image_format': TRACKING_IMAGE_FORMAT,
            'uidb36': uidb36,
            'token': token,
            'UNIQUE_KEY': ''.join(sample(UNIQUE_KEY_CHAR_SET, UNIQUE_KEY_LENGTH))
        })

        message = EmailMultiAlternatives()
        message.from_email = smart_str(self.header_sender)
        message.extra_headers = {'Reply-to': smart_str(self.header_reply)}
        message.to = [contact.mail_format()]

        # Render only the message provided by the user with the WYSIWYG editor
        message_template = Template(fix_tinymce_links(self.content))
        message_content = message_template.render(context)

        context.update({'message': message_content})

        # link_site_exist = False
        link_site = render_to_string('newsletter/newsletter_link_site.html', context)
        context.update({'link_site': link_site})

        if INCLUDE_UNSUBSCRIPTION:
            unsubscription = render_to_string('newsletter/newsletter_link_unsubscribe.html', context)
            context.update({'unsubscription': unsubscription})

        if TRACKING_IMAGE:
            image_tracking = render_to_string('newsletter/newsletter_image_tracking.html', context)
            context.update({'image_tracking': image_tracking})

        content_template = get_template('mailtemplates/{0}/{1}'.format(self.template, 'index.html'))
        content = content_template.render(context)

        if TRACKING_LINKS:
            from emencia.utils.newsletter import track_links
            content = track_links(content, context)

        content = smart_unicode(content)

        p = Premailer(content, base_url=base_url, preserve_internal_links=True)
        content = p.transform()

        # newsletter_template = Template(self.content) 

        message.body = html2text(content)
        message.attach_alternative(smart_str(content), "text/html")
        
        title_template = Template(self.title)
        title = title_template.render(context)
        message.subject = title
        
        for attachment in self.attachments:
            message.attach(attachment)

        return message