Header Ads Widget

Responsive Advertisement

Sending mail With custom pie chart image


To send an email with a custom pie chart image in Java, you'll typically need to generate the pie chart, save it as an image file, and then attach it to the email. Below is a step-by-step guide that includes generating a pie chart using JFreeChart, saving it as an image, and then sending an email with that image as an attachment.To display a custom image in an email using Java, you need to create a MIME (Multipurpose Internet Mail Extensions) message that includes both HTML content and the image as an embedded resource. You can use JavaMail API to achieve this. Here’s a step-by-step guide:

1. Set Up JavaMail API

Make sure you have JavaMail API in your project. If you’re using Maven, include the following dependency in your pom.xml:

xml

<dependency>

    <groupId>com.sun.mail</groupId>

    <artifactId>javax.mail</artifactId>

    <version>1.6.2</version>

</dependency>

 xml

<dependency>

    <groupId>org.jfree</groupId>

    <artifactId>jfreechart</artifactId>

    <version>1.5.3</version> <!-- check for the latest version -->

</dependency>

2. Prepare the Email with Embedded Image

Here’s a Java example to create and send an email with an embedded image:

java

package com.kartik.pie;

import java.awt.BasicStroke;

import java.awt.Color;

import java.awt.Font;

import java.awt.GradientPaint;

import java.awt.Point;

import java.awt.geom.Rectangle2D;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.DecimalFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import org.jfree.chart.ChartUtilities;

import org.jfree.chart.JFreeChart;

import org.jfree.chart.labels.PieSectionLabelGenerator;

import org.jfree.chart.labels.StandardPieSectionLabelGenerator;

import org.jfree.chart.plot.RingPlot;

import org.jfree.chart.title.LegendTitle;

import org.jfree.data.general.DefaultPieDataset;

import org.jfree.data.general.PieDataset;

import org.jfree.ui.ApplicationFrame;

import org.jfree.ui.RectangleEdge;

import org.jfree.ui.RectangleInsets;

import org.jfree.util.Rotation;

/**

 * A simple demonstration application showing how to create a pie chart using

 * data from a {@link DefaultPieDataset}.

 */

public class CutomFileWithPieChart extends ApplicationFrame {

 private static int totalAmount = 0;

 /**

  *

  */

 private static final long serialVersionUID = 1L;

 private static int maxSize = 0;

 /**

  * Default constructor.

  *

  * @param title

  *            the frame title.

  */

 public CutomFileWithPieChart(String title) {

  super(title);

  File file = null;

  Date date = new Date();

  try {

   file = File.createTempFile(date.getTime() + "_Pie", ".png");

  } catch (IOException e) {

   e.printStackTrace();

  }

  StringBuffer sb = createHtmlData();

  sendEmailToRecepint(file, sb);

 }

 private StringBuffer createHtmlData() {

  StringBuffer sb = new StringBuffer();

  sb.append("<html><head></head><body><table><tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr><tr>");

  sb.append("<td rowspan=");

  sb.append(10);

  sb.append('"');

  sb.append(" colspan=");

  sb.append(3);

  sb.append('"');

  sb.append('>');

  sb.append("<img src=");

  sb.append("'");

  sb.append("cid:ea-image");

  sb.append("'");

  sb.append("width=");

  sb.append('"');

  sb.append(200);

  sb.append('"');

  sb.append("height=");

  sb.append('"');

  sb.append(200);

  sb.append('"');

  sb.append('/');

  sb.append('>');

  sb.append("</td><th></th><th></th><th></th></tr></body></html>");

  return sb;

  /**

   * <td rowspan="10" colspan="3">

    <img src='cid:ea-image'

    style="display: block; margin-left: auto; margin-right: auto;"

    width="200" height="200"/>

    </td>

   */

 }

 /**

  *

  *

  * @return A sample dataset.

  */

 private static PieDataset createDataset() {

  DefaultPieDataset dataset = new DefaultPieDataset();

  List<DemoData> data = setData();

  totalAmount = sumOfValue(data);

  dataset = getdata(data);

  return dataset;

 }

 private static DefaultPieDataset getdata(List<DemoData> data) {

  DefaultPieDataset dataSet = new DefaultPieDataset();

  for (DemoData demoData : data) {

   dataSet.setValue(demoData.getName(), demoData.getData());

  }

  return dataSet;

 }

 private static int sumOfValue(List<DemoData> data) {

  int sum = 0;

  for (DemoData demoData : data) {

   sum += demoData.getData();

  }

  return sum;

 }

 private static List<DemoData> setData() {

  List<DemoData> list = new ArrayList<DemoData>();

  DemoData one = new DemoData();

  one.setName("ONE");

  one.setData(new Double(43.2));

  list.add(one);

  DemoData two = new DemoData();

  two.setName("TWO");

  two.setData(new Double(10.0));

  list.add(two);

  DemoData three = new DemoData();

  three.setName("THREE");

  three.setData(new Double(27.5));

  list.add(three);

  DemoData four = new DemoData();

  four.setName("FOUR");

  four.setData(new Double(17.5));

  list.add(four);

  DemoData five = new DemoData();

  five.setName("FIVE");

  five.setData(new Double(11.0));

  list.add(five);

  DemoData six = new DemoData();

  six.setName("SIX");

  six.setData(new Double(19.4));

  list.add(six);

  DemoData seven = new DemoData();

  seven.setName("SEVEN");

  seven.setData(new Double(9.2));

  list.add(seven);

  DemoData twenty = new DemoData();

  twenty.setName("twentyOne");

  twenty.setData(new Double(65.0));

  list.add(twenty);

  return list;

 }

 private void sendEmailToRecepint(File file, StringBuffer sb) {

  // Recipient's email ID needs to be mentioned.

  String to = "kmandal@kcm.com";

  // String to = "kartik.cse43@gmail.com";

  // Sender's email ID needs to be mentioned

  String from = "kmandal@kcm.com";

  final String username = "kmandal";// change accordingly

  final String password = "abc@1234";// change accordingly

  // Assuming you are sending email through relay.jangosmtp.net

  String host = "blr-kcm-01.corp.kcm.com";

  Properties props = new Properties();

  props.put("mail.smtp.auth", "true");

  props.put("mail.smtp.starttls.enable", "true");

  props.put("mail.smtp.host", host);

  props.put("mail.smtp.port", "25");

  Session session = Session.getInstance(props,

    new javax.mail.Authenticator() {

     protected PasswordAuthentication getPasswordAuthentication() {

      return new PasswordAuthentication(username, password);

     }

    });

  try {

   // Create a default MimeMessage object.

   Message message = new MimeMessage(session);

   // Set From: header field of the header.

   message.setFrom(new InternetAddress(from));

   // Set To: header field of the header.

   message.setRecipients(Message.RecipientType.TO,

     InternetAddress.parse(to));

   // Set Subject: header field

   message.setSubject("Demo snapshot");

   MimeMultipart multipart = new MimeMultipart();

   BodyPart messageBodyPart = new MimeBodyPart();

   messageBodyPart.setContent(sb.toString(), "text/HTML");

   multipart.addBodyPart(messageBodyPart);

   messageBodyPart = new MimeBodyPart();

   createDemoPanel(file);

   DataSource fds = new FileDataSource(file);

   messageBodyPart.setDataHandler(new DataHandler(fds));

   //ea-image is image file name

   messageBodyPart.setHeader("Content-ID", "<ea-image>");

   // add image to the multipart

   multipart.addBodyPart(messageBodyPart);

   // put everything together

   message.setContent(multipart);

   Transport.send(message);

  } catch (Exception e) {

   System.out.println("Error of file");

  }

 }

 

 private static JFreeChart createChart(PieDataset dataset) {

  RingPlot plot = null;

  plot = new CustomRingPlot((PieDataset) dataset, new Font(

    Font.SANS_SERIF, Font.BOLD, 13), Color.BLUE, totalAmount);

  JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT,

    plot, true);

  chart.setBackgroundPaint(new GradientPaint(new Point(100, 100),

    Color.WHITE, new Point(100, 100), Color.WHITE));

  plot.setNoDataMessage("No data available");

  plot.setDirection(Rotation.ANTICLOCKWISE);

  plot.setSectionDepth(0.50D); // this is required for circle radios

  plot.setBaseSectionOutlineStroke(new BasicStroke(0.5f));

  plot.setCircular(true);

  plot.setSeparatorsVisible(false); // this is required otherwise inside

           // circle lot of straight line will

           // come

  plot.setForegroundAlpha(1.0f); // this is required to display deep color

          // inside pie chart

  plot.setOutlinePaint(null); // this is required for circle border if

         // comment this line

  plot.setShadowPaint(null);

  plot.setOuterSeparatorExtension(50);

  plot.setInnerSeparatorExtension(50);

  plot = setSectionPaintColors(plot);

  LegendTitle legend = chart.getLegend();

  legend.setPosition(RectangleEdge.RIGHT);// this is also required to

            // display legend label

  // legend.setFrame(BlockBorder.NONE); //this is required legend border

  // if you need otherwise comments this line

  Rectangle2D r2DD = new Rectangle2D.Double(0, 0, 5, 15);

  plot.setLegendItemShape(r2DD);

  @SuppressWarnings("unchecked")

  List<String> key = dataset.getKeys();

  for (String string : key) {

   if (string.length() > maxSize) {

    maxSize = string.length();

   }

  }

  PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator(

    "{2}{1}{0}", new DecimalFormat("0.00"), new DecimalFormat("0%")) {

   private static final long serialVersionUID = 1L;

   @SuppressWarnings("rawtypes")

   @Override

   protected Object[] createItemArray(PieDataset dataset,

     Comparable key) {

    Object[] array = super.createItemArray(dataset, key);

    Object[] array1 = new Object[array.length];

    int count = 0;

    for (Object object : array) {

     StringBuffer sss = new StringBuffer();

     if (count == 1) {

      sss.append(object.toString());

      sss = charSpace(sss, object.toString().length(), 9);

     } else if (count == 2) {

      sss = charDigit(sss, object.toString().length(), 5);

      sss.append(object.toString());

      if (object.toString().length() == 2) {

       sss = charSpaceDigit(sss, object.toString()

         .length() + 1, 6);

      } else {

       sss = charSpace(sss, object.toString().length(), 6);

      }

     } else if (count == 0) {

      sss.append(object.toString().substring(0, 1)

        .toUpperCase()

        + object.toString()

          .substring(1,

            object.toString().length())

          .toLowerCase());

     } else {

      sss.append(object.toString());

     }

     array1[count] = sss.toString();

     count++;

    }

    return array1;

   }

  };

  plot.setLabelGenerator(null);

  // plot.setLabelGenerator(labelGenerator); //this is required if you

  // need display inside circle your description otherwise put null

  plot.setLegendLabelGenerator(labelGenerator); // this is required to

              // display legend label

  chart.setPadding(new RectangleInsets(-6, 0, 0, 20)); // this is required

                // for right

                // side of

                // legend space

  chart.setBorderVisible(true);

  chart.setBorderPaint(Color.WHITE);

  chart.setBorderStroke(new BasicStroke(0.3f));

  return chart;

 }

 /**

  * Creates a panel for the demo (used by SuperDemo.java).

  *

  * @return A panel.

  */

 public static JFreeChart createDemoPanel(File file) {

  JFreeChart chart = createChart(createDataset());

  try {

   ChartUtilities.writeChartAsPNG(new FileOutputStream(file), chart,

     400, 300);

  } catch (FileNotFoundException e) {

   e.printStackTrace();

  } catch (IOException e) {

   e.printStackTrace();

  }

  return chart;

 }

 private static RingPlot setSectionPaintColors(RingPlot plot) {

  List<?> listOfData = plot.getDataset().getKeys();

  String[] color = getColors();

  if (color != null && color.length > 0) {

   int count = 0;

   for (Object string : listOfData) {

    plot.setSectionPaint((String) string,

      Color.decode(color[count]));

    count++;

   }

  }

  return plot;

 }

 private static String[] getColors() {

  String[] colors = { "#41f46e", "#f47f41", "#5b2a44", "#DF0096",

    "#CF0096", "#EE0096", "#BBCCCC", "#4286f4" };

  return colors;

 }

 private static StringBuffer charSpace(StringBuffer sb, int datalength,

   int MaxSize) {

  if (datalength == MaxSize) {

   sb.append("  ");

   return sb;

  } else {

   sb.append("  ");

   return charSpace(sb, datalength + 1, MaxSize);

  }

 }

 private static StringBuffer charSpaceDigit(StringBuffer sb, int datalength,

   int MaxSize) {

  if (datalength == MaxSize) {

   sb.append("  ");

   return sb;

  } else {

   sb.append("  ");

   return charSpaceDigit(sb, datalength + 1, MaxSize);

  }

 }

 private static StringBuffer charDigit(StringBuffer sb, int datalength,

   int MaxSize) {

  if (datalength == 2) {

   sb.append("  ");

   return sb;

  }

  return sb;

 }

 /**

  * Starting point for the demonstration application.

  *

  * @param args

  *            ignored.

  */

 public static void main(String[] args) {

  CutomFileWithPieChart demo = new CutomFileWithPieChart(

    "Pie Chart Demo with mail send in html");

 }

}

 

 

Explanation

  1. Set Up Properties: Configure the SMTP server details, including host, port, and authentication properties.
  2. Create Session: Establish a session with the email server using the properties and authentication details.
  3. Create MimeMessage: Construct a new MimeMessage object.
  4. Set From, To, and Subject: Define the sender, recipient, and subject of the email.
  5. Create HTML Part: Create a MimeBodyPart to hold the HTML content, embedding the image using the cid (Content-ID) reference.
  6. Attach Image: Create another MimeBodyPart for the image, set its data handler, and reference it with the same cid.
  7. Combine Parts: Add both parts to a Multipart object and set it as the content of the MimeMessage.
  8. Send Email: Use the Transport.send method to send the email.

Conclusion

This code example demonstrates how to send an email with an embedded image using JavaMail API. Make sure to replace the placeholders (e.g., SMTP server details, email addresses, image path) with your actual values. This will ensure the image is displayed correctly in the recipient’s mailbox.







Sending mail With custom image
Sending mail With custom image

Post a Comment

0 Comments