SmtpApiHeader.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/python
# Version 1.0
# Last Updated 6/22/2009
import json
import re
import textwrap

class SmtpApiHeader:

    def __init__(self):
        self.data = {}

    def addTo(self, to):
        if not self.data.has_key('to'):
            self.data['to'] = []
        if type(to) is str:
            self.data['to'] += [to]
        else:
            self.data['to'] += to

    def addSubVal(self, var, val):
        if not self.data.has_key('sub'):
            self.data['sub'] = {}
        if type(val) is str:
            self.data['sub'][var] = [val]
        else:
            self.data['sub'][var] = val

    def setUniqueArgs(self, val):
        if type(val) is dict:
            self.data['unique_args'] = val

    def setCategory(self, cat):

        self.data['category'] = cat

    def addFilterSetting(self, fltr, setting, val):
        if not self.data.has_key('filters'):
            self.data['filters'] = {}
        if not self.data['filters'].has_key(fltr):
            self.data['filters'][fltr] = {}
        if not self.data['filters'][fltr].has_key('settings'):
                self.data['filters'][fltr]['settings'] = {}
        self.data['filters'][fltr]['settings'][setting] = val

    def asJSON(self):
        j = json.dumps(self.data)
        return re.compile('(["\]}])([,:])(["\[{])').sub('\1\2 \3', j)

    def as_string(self):
        j = self.asJSON()
        str = 'X-SMTPAPI: %s' % textwrap.fill(j, subsequent_indent = '  ', width = 72)
        return str

Example Python Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python
import SmtpApiHeader
import json

hdr = SmtpApiHeader.SmtpApiHeader()
receiver = ['kyle@somewhere.com','bob@someplace.net','someguy@googlemailz.coms']
times = ['1pm', '2pm', '3pm']
names = ['kyle', 'bob', 'someguy']

hdr.addTo(receiver)
hdr.addSubVal('-time-', times)
hdr.addSubVal('-name-', names)
hdr.addFilterSetting('subscriptiontrack', 'enable', 1)
hdr.addFilterSetting('twitter', 'enable', 1) #please check the apps available for your current package at www.sendgrid.com/pricing.html ?
hdr.setUniqueArgs({'test':1, 'foo':2})
a = hdr.asJSON()
a = hdr.as_string()
print a

Using SmtpApiHeader.py with Django

First start by adding the following to settings.py.

1
2
3
4
5
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'sendgrid_username'
EMAIL_HOST_PASSWORD = 'sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

Then to send email using SMTPAPI, you can do the following:

1
2
3
4
5
6
7
8
from django.core import mail
connection=mail.get_connection()
connection.open()

email = mail.EmailMessage('Subject here', 'Here is the message.', 'testing@sendgrid.net', ['sendgrid@hotmail.com'], headers={"X-SMTPAPI": "{\"to\": [ \"firstaddress@domain1.com\",\"secondaddress@domain2.com\" ], \"category\": \"DJANGOTEST\"}"}, connection=connection)

email.send()
connection.close()

Then use the SmtpApiHeader, like in the example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import SmtpApiHeader
import json
from django.core.mail import EmailMultiAlternatives

hdr = SmtpApiHeader.SmtpApiHeader()
# The list of addresses this message will be sent to
receiver = ['isaac@example.com', 'tim@example.com', 'jose@example.com']

# The names of the recipients
times = ['1pm', '2pm', '3pm']

# Another subsitution variable
names = ['Isaac', 'Tim', 'Jose']

# Set all of the above variables
hdr.addTo(receiver)
hdr.addSubVal('-time-', times)
hdr.addSubVal('-name-', names)

# Specify that this is an initial contact message
hdr.setCategory("initial")

# Enable a text footer and set it
hdr.addFilterSetting('footer', 'enable', 1)
hdr.addFilterSetting('footer', "text/plain", "Thank you for your business")

# fromEmail is your email
# toEmail is recipient's email address
# For multiple recipient e-mails, the 'toEmail' address is irrelivant
fromEmail =  'testing@sendgrid.net'
toEmail = 'sendgrid@hotmail.com'

# Create message container - the correct MIME type is multipart/alternative.
# Using Django's 'EmailMultiAlternatives' class in this case to create and send.
# Create the body of the message (a plain-text and an HTML version).
# text is your plain-text email
# html is your html version of the email
# if the reciever is able to view html emails then only the html
# email will be displayed
subject = 'Contact Response for <-name-> at <-time->'
text_content = 'Hi -name-!\nHow are you?\n'
html = """\
<html>
  <head></head>
  <body>
    <p>Hi! -name-<br>
       How are you?<br>
    </p>
  </body>
</html>
"""
msg = EmailMultiAlternatives(subject, text_content, fromEmail, [toEmail], headers={"X-SMTPAPI": hdr.asJSON()})
msg.attach_alternative(html, "text/html")
msg.send()