Getting Started with PubNub and Sendgrid

By | 18/12/2014

Inspired by my first experience with PubNub I took it a small step further. While publishing some messages, I also wanted to send an email along using the Sendgrid service. Below is the code for this:

from Pubnub import Pubnub
import sendgrid 
import json

publish_key = ''
subscribe_key = ''
channel = 'wapptastic'
message = 'Hello Wapptastic'

def publish( channel, message ):
    # Email List
    recipients = [
        [ "info@wapptastic.com", "Wapptastic" ],
        [ "test@example.com", "Example mail" ]
    ]

    # Info Callback
    def callback(info): 
        print(info)

    # Connection to SendGrid
    emailer = sendgrid.SendGridClient( '', '')
    pubnub = Pubnub( publish_key=publish_key, subscribe_key=subscribe_key)

    # PubNub Publish
    pubnub.publish( channel, message, callback=callback, error=callback )

    # Email Message Payload
    email = sendgrid.Mail()
    email.set_from("Wim Wauters ")
    email.set_subject("PubNub Message")
    email.set_html(json.dumps(message))
    email.set_text(json.dumps(message))

    ## Add Email Recipients
    for recipient in recipients:
        email.add_to("%s <%s>" % (recipient[1], recipient[0]))

    ## Send Email
    emailer.send(email)
publish('wapptastic', 'Email Test')

And a subscriber, similar to the one from the previous blog post on PubNub:

import datetime
from Pubnub import Pubnub

publish_key = ''
subscribe_key = ''
channel = 'wapptastic'

pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key)

def callback(message, channel):
    print(message)


def error(message):
    print("ERROR : " + str(message))


def connect(message):
    print("CONNECTED")


def reconnect(message):
    print("RECONNECTED")


def disconnect(message):
    print("DISCONNECTED")


pubnub.subscribe(channel, callback=callback, error=callback,
                 connect=connect, reconnect=reconnect, disconnect=disconnect)

When both the publisher.py and subscriber.py are run using Python, you will see that the subscriber gets all messages directly from the publisher service, but also an email is sent along to the email recipients.