示例#1
0
def build_header_json(notification):
    # build the header containing any relevant metadata
    # this is sent back to us by SendGrid via webhook events
    header_json = None
    if notification.metadata is not None:
        metadata = notification.metadata
        if 'bkrnd_nid' not in metadata:
            metadata['bkrnd_nid'] = notification.id
        header = SMTPAPIHeader()
        header.set_unique_args(metadata)
        header_json = {'X-SMTPAPI': header.json_string()}
    return header_json
示例#2
0
def send_template_email(
        to_email, subject, template, context, sent_by=None, hours=None):
    body = render_to_string(template, context)
    if hours and sent_by:
        header = SMTPAPIHeader()
        delay = datetime.timedelta(hours=hours)
        send_at = timezone.now() + delay
        header.set_send_at(int(send_at.timestamp()))
        email = EmailMultiAlternatives(
            subject,
            body,
            sent_by,
            to=[to_email],
            headers={"X-SMTPAPI": header.json_string()},
        )
    elif hours:
        header = SMTPAPIHeader()
        delay = datetime.timedelta(hours=hours)
        send_at = timezone.now() + delay
        header.set_send_at(int(send_at.timestamp()))
        email = EmailMultiAlternatives(
            subject,
            body,
            to=[to_email],
            headers={"X-SMTPAPI": header.json_string()},
        )
    elif sent_by:
        email = EmailMultiAlternatives(
            subject,
            body,
            sent_by,
            to=[to_email],
        )
    else:
        email = EmailMultiAlternatives(
            subject,
            body,
            to=[to_email],
        )

    email.attach_alternative(body, "text/html")
    email.send()
示例#3
0
    def create_message(self, subscription, **kwargs) -> Message:
        """
        Create the basic Message with the proper headers.

        Uses the SendGrid SMTPAPI.
        """

        headers = SMTPAPIHeader()
        headers.set_unique_args({
            "project_id": str(self.project_id),
            "subscription_id": str(subscription.id),
        })

        unsubscribe_group = self.get_unsubscribe_group(subscription)
        if unsubscribe_group:
            headers.set_asm_group_id(int(unsubscribe_group))

        return Message(recipients=[subscription.recipient],
                       extra_headers={"X-SMTPAPI": headers.json_string()},
                       **kwargs)
示例#4
0
    def __init__(self, **opts):
        """
        Constructs SendGrid Message object.

        Args:
            to: Recipient
            to_name: Recipient name
            from_email: Sender email
            from_name: Sender name
            subject: Email title
            text: Email body
            html: Email body
            bcc: Recipient
            reply_to: Reply address
            date: Set date
            headers: Set headers
            files: Attachments
        """
        self.to = []
        self.to_name = []
        self.cc = []
        self.add_to(opts.get('to', []))
        self.add_to_name(opts.get('to_name', []))
        self.add_cc(opts.get('cc', []))
        self.from_email = opts.get('from_email', '')
        self.from_name = opts.get('from_name', '')
        self.subject = opts.get('subject', '')
        self.text = opts.get('text', '')
        self.html = opts.get('html', '')
        self.bcc = []
        self.add_bcc(opts.get('bcc', []))
        self.reply_to = opts.get('reply_to', '')
        self.files = opts.get('files', {})
        self.set_headers(opts.get('headers', ''))
        self.date = opts.get('date', rfc822.formatdate())
        self.content = opts.get('content', {})
        self.smtpapi = opts.get('smtpapi', SMTPAPIHeader())
示例#5
0
 def test_drop_empty(self):
     header = SMTPAPIHeader()
     header.set_tos([])
     header.set_substitutions({
         "subKey": ["subValue"],
         "decimalKey": [decimal.Decimal("1.23456789")]
     })
     header.set_sections(json.loads('{}'))
     header.set_categories([])
     header.set_unique_args(json.loads('{"testUnique":"uniqueValue"}'))
     header.set_asm_group_id(None)
     header.set_send_each_at([])
     header.set_ip_pool(None)
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.dropsHeader, json.loads(header.json_string()))
示例#6
0
 def test_set(self):
     header = SMTPAPIHeader()
     header.set_tos(
         ["*****@*****.**", "*****@*****.**", "*****@*****.**"])
     header.set_substitutions({
         "subKey": ["subValue"],
         "decimalKey": [decimal.Decimal("1.23456789")]
     })
     header.set_sections(json.loads('{"testSection":"sectionValue"}'))
     header.set_categories(["testCategory"])
     header.set_unique_args(json.loads('{"testUnique":"uniqueValue"}'))
     header.set_asm_group_id(42)
     header.set_send_each_at([1409348513, 1409348514])
     header.set_send_at(1409348515)
     header.set_ip_pool('testPool')
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.validHeader, json.loads(header.json_string()))
示例#7
0
 def test_add(self):
     header = SMTPAPIHeader()
     header.add_to('*****@*****.**')
     header.add_to(['*****@*****.**', '*****@*****.**'])
     header.add_substitution('subKey', 'subValue')
     header.add_substitution('decimalKey', decimal.Decimal("1.23456789"))
     header.add_section('testSection', 'sectionValue')
     header.add_category('testCategory')
     header.add_unique_arg('testUnique', 'uniqueValue')
     header.set_asm_group_id(42)
     header.add_send_each_at(1409348513)
     header.add_send_each_at(1409348514)
     header.set_send_at(1409348515)
     header.set_ip_pool('testPool')
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.validHeader, json.loads(header.json_string()))
示例#8
0
# Python 2/3 compatible codebase
from __future__ import absolute_import, division, print_function

import time

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from smtpapi import SMTPAPIHeader

from smtpapi import SMTPAPIHeader
header = SMTPAPIHeader()

# [To](http://sendgrid.com/docs/API_Reference/SMTP_API/index.html)
#header.add_to('*****@*****.**')
header.set_tos(['*****@*****.**', '*****@*****.**'])

# [Substitutions](http://sendgrid.com/docs/API_Reference/SMTP_API/substitution_tags.html)
#header.add_substitution('key', 'value')
header.set_substitutions({'key': ['value1', 'value2']})

# [Unique Arguments](http://sendgrid.com/docs/API_Reference/SMTP_API/unique_arguments.html)
#header.add_unique_arg('key', 'value')
header.set_unique_args({'key':'value'})

# [Categories](http://sendgrid.com/docs/API_Reference/SMTP_API/categories.html)
#header.add_category('category')
header.set_categories(['category1', 'category2'])

# [Sections](http://sendgrid.com/docs/API_Reference/SMTP_API/section_tags.html)
#header.add_section('key', 'section')
示例#9
0
 def test_drop_empty(self):
     header = SMTPAPIHeader()
     header.set_tos([])
     header.set_substitutions(json.loads('{"subKey":["subValue"]}'))
     header.set_sections(json.loads('{}'))
     header.set_categories([])
     header.set_unique_args(json.loads('{"testUnique":"uniqueValue"}'))
     header.set_asm_group_id(None)
     header.set_send_each_at([])
     header.set_ip_pool(None)
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.dropsHeader, json.loads(header.json_string()))
示例#10
0
 def test_set(self):
     header = SMTPAPIHeader()
     header.set_tos(["*****@*****.**", "*****@*****.**", "*****@*****.**"])
     header.set_substitutions(json.loads('{"subKey":["subValue"]}'))
     header.set_sections(json.loads('{"testSection":"sectionValue"}'))
     header.set_categories(["testCategory"])
     header.set_unique_args(json.loads('{"testUnique":"uniqueValue"}'))
     header.set_asm_group_id(42)
     header.set_send_each_at([1409348513, 1409348514])
     header.set_send_at(1409348515)
     header.set_ip_pool('testPool')
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.validHeader, json.loads(header.json_string()))
示例#11
0
 def test_add(self):
     header = SMTPAPIHeader()
     header.add_to('*****@*****.**')
     header.add_to(['*****@*****.**', '*****@*****.**'])
     header.add_substitution('subKey', 'subValue')
     header.add_section('testSection', 'sectionValue')
     header.add_category('testCategory')
     header.add_unique_arg('testUnique', 'uniqueValue')
     header.set_asm_group_id(42)
     header.add_send_each_at(1409348513)
     header.add_send_each_at(1409348514)
     header.set_send_at(1409348515)
     header.set_ip_pool('testPool')
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.validHeader, json.loads(header.json_string()))
示例#12
0
 def test_drop_empty(self):
     header = SMTPAPIHeader()
     header.set_tos([])
     header.set_substitutions(json.loads('{"subKey":["subValue"]}'))
     header.set_sections(json.loads('{}'))
     header.set_categories([])
     header.set_unique_args(json.loads('{"testUnique":"uniqueValue"}'))
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.dropsHeader, json.loads(header.json_string()))
示例#13
0
 def test_set(self):
     header = SMTPAPIHeader()
     header.set_tos(["*****@*****.**"])
     header.set_substitutions(json.loads('{"subKey":["subValue"]}'))
     header.set_sections(json.loads('{"testSection":"sectionValue"}'))
     header.set_categories(["testCategory"])
     header.set_unique_args(json.loads('{"testUnique":"uniqueValue"}'))
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.validHeader, json.loads(header.json_string()))
示例#14
0
 def test_add(self):
     header = SMTPAPIHeader()
     header.add_to('*****@*****.**')
     header.add_substitution('subKey', 'subValue')
     header.add_section('testSection', 'sectionValue')
     header.add_category('testCategory')
     header.add_unique_arg('testUnique', 'uniqueValue')
     header.add_filter('testFilter', 'filter', 'filterValue')
     self.assertEqual(self.validHeader, json.loads(header.json_string()))
示例#15
0
    def _prepare_payload(self, recipients=None):
        def namestr(rec):
            if not rec.get('name'):
                return rec.get('email')

            return '"{}" <{}>'.format(rec['name'].replace('"', ''), rec['email'].replace(',', ''))

        if not recipients:
            recipients = self.solidify_recipients()

        num_rec = len(recipients)

        payload = SMTPAPIHeader()

        merge_vars = {}

        for key, val in self.global_merge_vars.items():
            keystr = ':{}'.format(key)

            new_key = '{1}{0}{2}'.format(key, *self.delimiters)

            merge_vars[new_key] = [keystr] * num_rec

            payload.add_section(keystr, val)

        for index, recip in enumerate(recipients):
            payload.add_to(recip if isinstance(recip, str) else namestr(recip))

            for rkey, rvalue in recip.get('merge_vars', {}).items():
                new_key = '{1}{0}{2}'.format(rkey, *self.delimiters)

                if not merge_vars.get(new_key):
                    merge_vars[new_key] = [None] * num_rec

                merge_vars[new_key][index] = rvalue

        if self.webhook_data:
            payload.set_unique_args(self.webhook_data)

        if self.ip_pool:
            payload.set_ip_pool(self.ip_pool)

        if self.template_name:
            payload.add_filter('templates', 'enabled', 1)
            payload.add_filter('templates', 'template_id', self.template_name)

        payload.set_substitutions(merge_vars)

        payload.add_filter('clicktrack', 'enable', self.track_clicks and 1 or 0)
        payload.add_filter('opentrack', 'enable', self.track_opens and 1 or 0)

        payload.set_categories(self.tags)

        return payload
示例#16
0
# Python 2/3 compatible codebase
from __future__ import absolute_import, division, print_function
from smtpapi import SMTPAPIHeader

import time

if __name__ == '__main__' and __package__ is None:
    from os import sys, path

    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from smtpapi import SMTPAPIHeader

header = SMTPAPIHeader()

# [To](http://sendgrid.com/docs/API_Reference/SMTP_API/index.html)
# header.add_to('*****@*****.**')
header.set_tos(['*****@*****.**', '*****@*****.**'])

# [Substitutions](http://sendgrid.com/docs/API_Reference/SMTP_API/substitution_tags.html)
# header.add_substitution('key', 'value')
header.set_substitutions({'key': ['value1', 'value2']})

# [Unique Arguments](http://sendgrid.com/docs/API_Reference/SMTP_API/unique_arguments.html)
# header.add_unique_arg('key', 'value')
header.set_unique_args({'key': 'value'})

# [Categories](http://sendgrid.com/docs/API_Reference/SMTP_API/categories.html)
# header.add_category('category')
header.set_categories(['category1', 'category2'])

# [Sections](http://sendgrid.com/docs/API_Reference/SMTP_API/section_tags.html)