如何导出Highcharts图表并通过邮件发送?求示例
Highcharts图表截图并通过PHPMailer发送邮件解决方案
前端代码修改
移除按钮的跳转链接避免干扰,在sendChart函数中利用Highcharts API生成Base64格式的图表图片,再通过AJAX提交到PHP后端。
完整前端代码:
<script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <button class="send-chart" onclick="sendChart()">Send chart by e-mail</button> <div id="container"></div> <h2>Exported image below</h2> <img id="image" /> <script> var options = { chart: {}, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: 'column' }] } var chart = Highcharts.chart('container', options); function sendChart() { console.log('Send chart button clicked !'); // 生成图表的PNG格式Base64图片 chart.exportChartLocal({ type: 'png' }, function (dataUrl) { // 显示预览图(可选) document.getElementById('image').src = dataUrl; // 提交到后端 $.ajax({ url: 'sendGraphByMail.php', method: 'POST', data: { chartImage: dataUrl }, success: function() { alert('邮件发送成功!'); }, error: function() { alert('邮件发送失败,请重试!'); } }); }); } </script>
后端sendGraphByMail.php代码修改
接收前端传来的Base64图片,解码后生成临时文件,通过PHPMailer添加为附件发送,最后删除临时文件。
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // 引入PHPMailer文件(根据你的实际路径调整) require 'path/to/PHPMailer/src/Exception.php'; require 'path/to/PHPMailer/src/PHPMailer.php'; require 'path/to/PHPMailer/src/SMTP.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['chartImage'])) { $dataUrl = $_POST['chartImage']; // 移除Base64前缀,解码图片内容 $imageData = str_replace('data:image/png;base64,', '', $dataUrl); $imageData = str_replace(' ', '+', $imageData); $imageContent = base64_decode($imageData); // 创建临时文件 $tempFile = tempnam(sys_get_temp_dir(), 'chart_') . '.png'; file_put_contents($tempFile, $imageContent); // 初始化PHPMailer(保留你已有的配置) $mail = new PHPMailer(true); try { // SMTP配置(替换为你的实际信息) $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'your-email@example.com'; $mail->Password = 'your-email-password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465; // 收件人设置 $mail->setFrom('your-email@example.com', 'Your Name'); $mail->addAddress('target@example.com', 'Recipient'); // 替换为目标邮箱 // 邮件内容 $mail->isHTML(true); $mail->Subject = 'Highcharts图表截图'; $mail->Body = '附件为生成的图表截图'; $mail->AltBody = '附件为生成的图表截图'; // 添加图表附件 $mail->addAttachment($tempFile, 'chart.png'); $mail->send(); echo '邮件已发送'; } catch (Exception $e) { echo "发送失败: {$mail->ErrorInfo}"; } finally { // 删除临时文件 unlink($tempFile); } } else { echo '无效请求'; } ?>
注意事项
- 确保服务器具备GD库(一般默认已安装)
- 临时文件目录需有写入权限,
sys_get_temp_dir()为服务器默认临时目录,权限通常没问题 - 若不用jQuery,可替换为原生
fetchAPI实现AJAX请求 - 保留你原有可正常运行的PHPMailer SMTP配置
内容的提问来源于stack exchange,提问作者Wahid
相关产品推荐
相关产品推荐

