Skip to main content

Dynamic charts & graphs in email with Mailgun

Email is a ubiquitous format, but it comes with limitations. In order to embed a chart or graph directly in email, you must render it as an image.

Rendering dynamic charts can be an arduous process that requires a server render farm, headless browsers, and other configuration. The QuickChart service allows you to do this rendering easily in your existing programming environment.

This post outlines how to send charts that show up in emails, pictured above.
This post outlines how to send charts that show up in emails, pictured above.

Building the chart

If you're already showing these charts on a web frontend, your work here might already be done because QuickChart is built on top of the frontend Chart.js library. You can use your existing Chart.js config, but for the purposes of this example we'll construct a new Chart.js config.

For example, imagine we have the following data:

LabelRetweetsLikes
Week 11280
Week 2542
Week 340215
Week 4530

First create a JSON object to define your chart using the Chart.js format:

{
"type": "bar",
"data": {
"labels": ["Week 1", "Week 2", "Week 3", "Week 4"],
"datasets": [
{
"label": "Retweets",
"data": [12, 5, 40, 5]
},
{
"label": "Likes",
"data": [80, 42, 215, 30]
}
]
}
}

Now send that JSON to the QuickChart endpoint at https://quickchart.io/chart:

https://quickchart.io/chart?c={"type":"bar","data":{"labels":["Week 1","Week 2","Week 3","Week 4"],"datasets":[{"label":"Retweets","data":[12,5,40,5]},{"label":"Likes","data":[80,42,215,30]}]}}

When you render the above URL in an image tag, you'll see the image below:

<img src="https://quickchart.io/chart?c=..." />
Chart with retweets and likes

This image can be directly embedded in an email using a standard <img> tag.

tip

It's usually best to URL encode your JSON parameter. Nearly every programming language has a built-in function to do this. URL encoding your JSON will avoid problems with more complex chart specifications.

If you're looking for shorter URLs, check out the URL shortener documentation.

Sending the chart with Mailgun

Because the chart is just a normal image, you don't have to do anything out of the ordinary here. Construct your Mailgun email like you normally would and include the image tag as part of your HTML email.

Here's an example using the mailgun node.js library:

const mailgunGenerator = require('mailgun-js');
const mailgun = mailgunGenerator({
apiKey: 'abc123',
domain: 'xyz.com',
});

const chartConfig = encodeURIComponent(
JSON.stringify({
type: 'bar',
data: {
labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
datasets: [
{
label: 'Retweets',
data: [12, 5, 40, 5],
},
{
label: 'Likes',
data: [80, 42, 215, 30],
},
],
},
}),
);

const message = `Hello, please see the chart below:
<br><br>
<img src="https://quickchart.io/chart?c=${chartConfig}" />
`;

const data = {
from: '[email protected]',
to: '[email protected]',
subject: 'Updated Chart Report',
html: message,
};

mailgun.messages().send(data, (err, body) => {
console.log(body);
});

Here's an equivalent example that sends charts via Mailgun in Python 3, using the requests library.

import json
from urllib.parse import quote

import requests

API_KEY = "abc123"
DOMAIN = "xyz.com"

chart_config = quote(json.dumps({
"type": "bar",
"data": {
"labels": ["Week 1", "Week 2", "Week 3", "Week 4"],
"datasets": [{
"label": "Retweets",
"data": [12, 5, 40, 5]
}, {
"label": "Likes",
"data": [80, 42, 215, 30]
}]
}
}))

message = f"""Hello, please see the chart below:
<br><br>
<img src="https://quickchart.io/chart?c={chart_config}" />
"""

request_url = f"https://api.mailgun.net/v2/{DOMAIN}/messages"
request = requests.post(request_url, auth=("api", API_KEY), data={
"from": "[email protected]",
"to": "[email protected]",
"subject": "Updated Chart Report",
"html": message,
})

print(f"Status: {request.status_code}")
print(f"Body: {request.text}")

Further reading

The look and feel of the chart is completely customizable using the Chart.js documentation. You should also see the QuickChart documentation for more information on shortcuts and plugins.

The Mailgun API documentation will be useful for more advanced email sending and mailing list use cases. However, the general process outlined in this post for generating static charts and embedding them in your emails will remain the same.

QuickChart is open source for individuals and organizations that wish to self-host. Or, you can sign up for QuickChart in order to generate charts on our infrastructure. Feel free to reach out with any questions!


Ian Webster

About the author

Ian Webster is a software engineer and former Googler based in San Mateo, California. He has helped Google, NASA, and governments around the world improve their data pipelines and visualizations. In 2018, Ian created QuickChart, a collection of open-source APIs that support data visualization efforts.

Email · LinkedIn · Twitter