Tracking pixel in HTML email not triggering API endpoint when opened

43 Views Asked by At

I am currently working on implementing a tracking system for emails, where I embed a tracking pixel in the HTML content of the email. The issue I am facing is that while the tracking pixel is getting rendered in the HTML, the associated API endpoint is not getting triggered when the email is opened.

Here's an overview of my setup:

Endpoint Code:

@app.get("/track_open/{unique_id}")
def track_open(request: Request, unique_id: str, db: Session = Depends(get_db)):
    pixel = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
    try:
        tracking_unique_id = get_tracking_unique_id(db, unique_id)
        print(request.headers)
        if not tracking_unique_id.opened_at:
            tracking_unique_id.opened_at = datetime.datetime.now()
            db.add(tracking_unique_id)
            db.commit()
            return PlainTextResponse(content=pixel, media_type="image/gif")
        else:
            print("Already opened")
    except Exception as e:
        print(f"No Tracking record found: {str(e)}")
        return {"status": "error", "message": str(e)}

Tracking URL Snippet:

base_url = "http://127.0.0.1:8000"
# Generate the tracking pixel url
click_tracking_url = f"{base_url}/track_click/{unique_id}"
open_tracking_url = f"{base_url}/track_open/{unique_id}"

# Search for the links in the email body
soup = BeautifulSoup(content, "html.parser")
urls = [a["href"] for a in soup.find_all("a", href=True)]

# If there are links or urls in the email body, inject our click tracking url to that original link
if urls:
    for url in urls:
        # make the final tracking url
        tracking_url = f"{click_tracking_url}?url={url}"
        new_message = new_message.replace(f"{url}", f"{tracking_url}")

else:
    print("No URLs found in the email content")

# Create the email content with tracking pixel image
open_tracking_img = (
    f"<img src='{open_tracking_url}' width='1' height='1' border='0'>"
)

new_message += open_tracking_img

Message:

<h1> Weekly News  <a href="https://www.w3schools.com">Visit W3Schools.com!</a> </h1>

I have tested the endpoint by creating a local HTML file, and it successfully triggers the API endpoint when I open the file in a web browser. However, when I send the same HTML content as an email, the endpoint is not being hit.

Any suggestions on why the endpoint might not be triggered when the email is opened? Are there specific considerations when dealing with tracking pixels in HTML emails?

0

There are 0 best solutions below