the question I am asking is from a code-architecture point of view. I am preparing a report in php which is built with a string $message and then send via a php mail function.
For example the report is built in the php file like that(basically concatenates strings):
$message .= <<<HTML
</td>
</tr>
</tbody>
</table>
HTML;
Further, I would like to include a chart. However, trying the following example and sending it per mail I get no chart and an empty <div style="width:900px;min-height:500px"></div> ==$0 value.
$message.=<<<HTML
<tr valign="top" align="center">
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333', ],
['Silver', 10.49, 'silver'],
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ]
]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
bar: {groupWidth: '95%'},
legend: 'none',
};
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div.innerHTML);
});
chart.draw(data, options);
}
</script>
<div id='chart_div'></div>
</tr>
HTML;
My guess is that javascript is not accepted by f.ex. GMail. Hence, I am trying to create a png beforehand which is then included in the report.
My preferred way of doing this would be the google charts library, however, it has no support for php and is entirely based on JavaScript.
Hence, my questions are:
I appreciate if you could provide an example!
Thx in advance!
Email clients strip Javascript, SVG, and other formats, so you can't use a chart library directly in email.
Your options include:
QuickChart in particular is built on Chart.js, so you'd have to create a Chart.js chart definition as a string:
$chartConfig = "{
type: 'bar',
data: {
labels: ['Copper', 'Silver', 'Gold', 'Platinum'],
datasets: [{
data: [8.94, 10.49, 19.30, 21.45],
backgroundColor: ['#b87333', 'silver', 'gold', '#e5e4e2'],
}]
},
options: {
title: {
display: true,
text: 'Density of Precious Metals, in g/cm^3',
},
legend: {
display: false
}
}
}";
I've used a static string to match your example, but you can include dynamic variables like in any other PHP string.
Then encode this string into a URL:
$chartUrl = 'https://quickchart.io/chart?c=' . urlencode($chartConfig);
This URL returns a chart that looks like this:

Finally, add the chart to your email body as an HTML image tag:
$message .= "<img src=\"$chartUrl\"/>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With