简体   繁体   中英

How to use Google Analytics to the Mandrill Python API

I have not been able to successfully setup email tracking with Google Analytics campaigns through the Mandrill Python API. I currently have the below code, but is there something that I am missing? On the Google Analytics side, I just added the domain only to my Google Analytics account.

Here is my Mandrill API call code:

Thank you in advance.

import os
import mandrill

MANDRILL_CLIENT = mandrill.Mandrill(os.environ['MANDRILL_API_KEY'])
DEFAULT_FROM_EMAIL = 'from@example.com'  #purposely anonymize
DEFAULT_FROM_NAME = 'Aaron'

# HTML / TEXT - fields may be variable
DATA_FILE = 'data.csv'
HTML = 'variable.html'
TEXT = 'variable.txt'

def send(email):
    """
    `email` is an object with attr:
        to - email address to send to
        name - name of person
    """
    with open(HTML,'r') as html:
        with open(TEXT, 'r') as text:
            try:
                message = {'attachments': [],
                 'auto_html': None,
                 'auto_text': None,
                 'bcc_address': None,
                 'from_email': DEFAULT_FROM_EMAIL,
                 'from_name': DEFAULT_FROM_NAME,
                 'global_merge_vars': email.merge_vars(),
                 'merge_vars': [],
                 'google_analytics_domains': ['http://www.example.com'],  # purposely anonymize as example.com
                 'google_analytics_campaign': 'my_email',
                 'headers': {'Reply-To': DEFAULT_FROM_EMAIL},
                 'html': str(html.read()),
                 'images': [],
                 'important': False,
                 'inline_css': None,
                 'merge': True,
                 'merge_language': 'mailchimp',
                 'metadata': {'website': 'hardrockhotel.com'},
                 'preserve_recipients': None,
                 'recipient_metadata': [],
                 'return_path_domain': None,
                 'signing_domain': None,
                 'subaccount': None,
                 'subject': 'example subject',
                 'tags': ['password-resets'],
                 'text': str(text.read()),
                 'to': [{'email': email.to,
                         'name': email.name,
                         'type': 'to'}],
                 'track_clicks': True,
                 'track_opens': True,
                 'tracking_domain': True,
                 'url_strip_qs': None,
                 'view_content_link': None}
                result = MANDRILL_CLIENT.messages.send(message=message, async=False, ip_pool='Main Pool')

            except mandrill.Error, e:
                # Mandrill errors are thrown as exceptions
                print 'A mandrill error occurred: %s - %s' % (e.__class__, e)
                # A mandrill error occurred: <class 'mandrill.UnknownSubaccountError'> - No subaccount exists with the id 'customer-123'    
                raise


def get_record_as_dict(zipped):
    return {k:v for k,v in zipped}


class EmailRcpt(object):
    """ Email Recipient Object for each record being read in from the DATA_FILE. """
    def __init__(self, zipped):
        for k, v in zipped:
            setattr(self, k, v)

    def merge_vars(self):
        return [{'name': k, 'content': v} for k,v in self.__dict__.iteritems()]


def main():
    with open(DATA_FILE,'r') as data:
        header = data.readline().replace('\n', '').split(',')

        for row in data:
            row = row.split(',')
            zipped = zip(header, row)
            email_rcpt = EmailRcpt(zipped)
            send(email_rcpt)

if __name__ == '__main__':
    main()

Edit:

I have added this code:

<img src="http://www.google-analytics.com/collect?v=1&amp;tid=UA-57258906-1&amp;cid=CLIENT_ID_NUMBER&amp;t=event&amp;ec=email&amp;ea=open&amp;el=recipient_id&amp;cs=newsletter&amp;cm=email&amp;cn=Campaign_image1" >

Based on this article:

http://dyn.com/blog/tracking-email-opens-via-google-analytics/

To the bottom of my Mandrill Email, but I am still having issues, and don't see anything coming up under my Google Analytics account. Is there something else I am doing wrong?

Thank you

As a starting point, do you see the Google parameters being added to the links in your Mandrill emails? You can send yourself a test with a link to your domain, and then see if the redirect/link takes you to yourdomain.com?utm_campaign... type of link with Google Analytics parameters appended. That will confirm whether the issue is with your API call/Mandrill code or with the tracking.

Looking at the API call, you're passing more than a domain in the google_analytics_domains parameter - it also has the protocol, which should be omitted. So the resulting domain portion should look something like this:

... 'google_analytics_domains': ['www.example.com'], # purposely anonymize as example.com ...

You'll want to be sure to include any/all subdomains, too, that you're linking to in your email, because Mandrill narrowly applies the GA parameters since sites/pages without GA tracking code on them can break if they don't know what to do with the query strings.

Once you confirm that the links have the parameters added properly, make sure you have the GA tracking code on the page(s) that you're linking to, so Google can track it. Google does sometimes have a delay in tracking/showing the data, so if you've confirmed the parameters are there, and that the page is configured to track them, you may also want to give it a little time to show up in the GA dashboard/data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM