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 = [
        [ "", "Wapptastic" ],
        [ "", "Example mail" ]

    # Info Callback
    def callback(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")

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

    ## 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):

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

def connect(message):

def reconnect(message):

def disconnect(message):

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

When both the and 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.