Search code examples
springimageemailvelocityemail-attachments

How to Send image using org.apache.velocity.VelocityContext for email


MimeMessagePreparator mimeMessagePreparator=new MimeMessagePreparator() {

@Override
public void prepare(MimeMessage mimeMessage) throws Exception {

MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage);
                    mimeMessageHelper.setTo(requestQuotationPojo.getEmailId().toString());
                    mimeMessageHelper.setFrom("vikasglobaljapan@gmail.com");
                    mimeMessageHelper.setText("Your Request Quotation Number"+requestQuotationPojo.getRfqId());
                    mimeMessageHelper.setSubject("Request Quotation Details");
    VelocityContext velocityContext = new VelocityContext();

    requestQuotationPojo.setImage(new StringBuffer(application_url.concat(requestQuotationPojo.getImage().toString())));
    requestQuotationPojo.setRfqId(new StringBuffer(rfqId));

    velocityContext.put("image", requestQuotationPojo.getImage());
    velocityContext.put("rfqDetails", requestQuotationPojo);
                    velocityContext.put("image",application_url.concat(requestQuotationPojo.getImage().toString()));

   StringWriter stringWriter = new StringWriter();
   velocityEngine.mergeTemplate("com/gjcp/dao/daoImpl/customer/templateName.vm", "UTF-8", velocityContext, stringWriter);
                    mimeMessageHelper.setText(stringWriter.toString(), true);
                }

template.vm

<!doctype html>
<html lang="en">
 <head>
 <style>
table, th, td {
    border: 1px solid black;
}
</style>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
 <table style="width:100%">
  <tr>
    <th>Product Name</th>
    <th>Quote Number</th>
    <th>Image</th>
    <th>Quantity</th>
  </tr>
  <tr>
    <td>${rfqDetails.productName}</td>
    <td> ${rfqDetails.rfqId}</td>
    <td><img src="${rfqDetails.image}" border="0" width="50" height="50"></td>
    <td>${rfqDetails.quantity}</td>
  </tr>

</table>


 </body>
</html>

Solution

    • I suppose that your image is a byte array. So you should add image to velocity context as base64 string.

      velocityContext.put("image", Base64.encode(requestQuotationPojo.getImage()));

    • And use this img tag in your template file.

      <img src="data:image/jpg;base64,${image}" border="0" width="50" height="50"/>