如何使用Java发送含饼图的自动化测试结果邮件
Hey there! I’ve been in your shoes before—spending half a day trying to get automated test reports with pie charts into emails can feel like hitting a wall. Let me share a practical, working solution I’ve used for similar tasks in Java.
核心思路
We need two key pieces: generating a pie chart from your test results, then embedding that chart directly into an HTML email (so recipients see it right in the message, not as an attachment). We’ll use JFreeChart for chart generation and the JavaMail API for sending emails.
Step 1: Add Dependencies
First, add these dependencies to your project (if using Maven):
<!-- JavaMail API for sending emails --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> <!-- JFreeChart for pie chart generation --> <dependency> <groupId>org.jfree</groupId> <artifactId>jfreechart</artifactId> <version>1.5.3</version> </dependency>
Step 2: Generate the Test Result Pie Chart
Create a helper method to turn your test stats (passed, failed, skipped) into a PNG pie chart, stored as a byte array (perfect for embedding):
import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtils; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.awt.Color; public class TestChartGenerator { public static byte[] generateTestPieChart(long passed, long failed, long skipped) throws IOException { // Populate pie chart data DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("Passed", passed); dataset.setValue("Failed", failed); dataset.setValue("Skipped", skipped); // Create the pie chart with custom styling JFreeChart pieChart = ChartFactory.createPieChart( "Automated Test Results", dataset, true, // Show legend true, false ); // Customize colors for better readability pieChart.getPlot().setSectionPaint("Passed", new Color(34, 139, 34)); // Forest green pieChart.getPlot().setSectionPaint("Failed", new Color(220, 20, 60)); // Crimson pieChart.getPlot().setSectionPaint("Skipped", new Color(255, 165, 0)); // Orange // Convert chart to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ChartUtils.writeChartAsPNG(baos, pieChart, 450, 350); // 450x350 resolution return baos.toByteArray(); } }
Step 3: Send the Email with Embedded Chart
Use JavaMail to craft an HTML email, embed the pie chart as an inline resource, and send it:
import javax.mail.*; import javax.mail.internet.*; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.ByteArrayDataSource; import java.util.Properties; public class TestResultMailer { public static void sendTestReport(String smtpHost, int smtpPort, String senderEmail, String senderPassword, String recipientEmail, long passed, long failed, long skipped) throws Exception { // Configure mail server properties Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // Enable TLS for secure connection // Create authenticated session Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail, senderPassword); } }); // Build the email message Message message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail)); message.setSubject(String.format("Automated Test Results - %s", java.time.LocalDate.now())); // Create multi-part content (HTML + embedded image) Multipart multipart = new MimeMultipart(); // 1. HTML body section BodyPart htmlBody = new MimeBodyPart(); long totalTests = passed + failed + skipped; String htmlContent = String.format(""" <h2>📊 Automated Test Execution Summary</h2> <p><strong>Total Tests Run:</strong> %d</p> <ul> <li>✅ Passed: %d (%.1f%%)</li> <li>❌ Failed: %d (%.1f%%)</li> <li>⏭️ Skipped: %d (%.1f%%)</li> </ul> <p>Test Result Breakdown:</p> <p><img src="cid:testChart" alt="Test Result Pie Chart"></p> """, totalTests, passed, (passed*100.0/totalTests), failed, (failed*100.0/totalTests), skipped, (skipped*100.0/totalTests)); htmlBody.setContent(htmlContent, "text/html; charset=utf-8"); multipart.addBodyPart(htmlBody); // 2. Embedded pie chart section BodyPart chartPart = new MimeBodyPart(); byte[] chartBytes = TestChartGenerator.generateTestPieChart(passed, failed, skipped); DataSource dataSource = new ByteArrayDataSource(chartBytes, "image/png"); chartPart.setDataHandler(new DataHandler(dataSource)); chartPart.setHeader("Content-ID", "<testChart>"); // Matches the cid in HTML multipart.addBodyPart(chartPart); // Set the email content and send message.setContent(multipart); Transport.send(message); System.out.println("Test result email sent successfully!"); } // Test the mailer with your own credentials public static void main(String[] args) { try { sendTestReport( "smtp.your-provider.com", // e.g., smtp.gmail.com for Gmail 587, "your-email@domain.com", "your-app-password", // Use app-specific password for Gmail/Outlook "team@yourcompany.com", 92, // Replace with actual passed count 5, // Failed count 3 // Skipped count ); } catch (Exception e) { System.err.println("Failed to send email: " + e.getMessage()); e.printStackTrace(); } } }
Key Notes to Avoid Headaches
- Mail Server Credentials: For services like Gmail, you’ll need to use an app-specific password (not your regular password) if 2FA is enabled. For Outlook/Office 365, check their official SMTP settings.
- Chart Customization: Tweak the JFreeChart code to adjust colors, slice labels, or chart size—JFreeChart has tons of built-in customization options to match your team’s branding.
- Error Handling: In production, add retry logic for email failures, and validate test data (ensure total tests aren’t zero) before generating the chart.
内容的提问来源于stack exchange,提问作者Thangaraj

