Total Pageviews

2016/04/10

[Java Mail] Embed Images into Email

Requirement
If we would like embed a image file into Email as bellows:

How to do it?

How-To
In the velocity template file, we define a image tag and define a cid (content id):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<html>
   <body>
      <p>親愛的保戶您好</p>
      <p>     </p>
      <p>感謝您對xxxx的支持,您在網路上申請的旅平險保單已投保完成,以下是您的投保明細,供您參考。</p>
      <p>【投保內容】</p>
      <p>保單號碼: ${customer.policyNumber}</p>
      <p>被保險人: ${customer.name}</p>
      <p>申請日期: ${customer.applyDate}</p>
      <p>保險期間: ${customer.fromDate} ~ ${customer.toDate}</p>
      <p>旅遊地點: ${customer.place}</p>
      <p></p>
      <p>※保險單及保險費送金單將於近日內寄至要保人所指定之聯絡地址。</p>
      <p></p>
      <p>                     敬祝  闔家平安 </p>
      <p><img src="cid:panda"></p>
   </body>
</html>

Here is code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
 public static void main(String[] args) throws IOException, MessagingException {

  ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
  VelocityEngine velocityEngine = (VelocityEngine) context.getBean("velocityEngine");

  // set value to template
  Customer customer = new Customer();
  customer.setPolicyNumber("12345678");
  customer.setName("測試");
  customer.setApplyDate("20160325");
  customer.setFromDate("20160401");
  customer.setToDate("20160410");
  customer.setPlace("日本關西");

  // set customer to map for velocity email template
  Map<String, Object> model = new HashMap<String, Object>();
  model.put("customer", customer);

  // get email content from velocity email template
  String mailTemplate = "albert/practice/mail/templates/insurance.vm";
  String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailTemplate, "UTF-8", model);

  // set file attachments
  File pdfFile = new File("/Users/albert/Dropbox/Getting Started.pdf");
  File mindmapFile = new File("/Users/albert/Dropbox/eBooks//The Intelligent Investor.png");

  List<File> attachments = new ArrayList<File>();
  attachments.add(pdfFile);
  attachments.add(mindmapFile);

  // set email parameters
  EmailParams params = new EmailParams();
  params.setReceiverEmail("junyuo@gmail.com");
  params.setSubject("網路投保完成通知");
  params.setContent(content);
  params.setAttachments(attachments);

  new MailTest().sendMail(params);
 }

 public void sendMail(EmailParams params) {

  JavaMailSenderImpl sender = getJavaMailSender();
  MimeMessage message = sender.createMimeMessage();

  List<File> attachemtns = null;

  try {
   MimeMessageHelper helper = new MimeMessageHelper(message, true);
   helper.setTo(params.getReceiverEmail());
   helper.setSubject(params.getSubject());
   helper.setText(params.getContent(), true);

   // add attachment(s)
   if (params.getAttachments() != null && params.getAttachments().size() > 0) {
    attachemtns = params.getAttachments();
    for (int i = 0; i < attachemtns.size(); i++) {
     FileSystemResource attachment = new FileSystemResource(attachemtns.get(i));
     helper.addAttachment(attachemtns.get(i).getName(), attachment);
    }
   }

   // embed image in email
   InputStreamSource logo = new ByteArrayResource(
     IOUtils.toByteArray(getClass().getResourceAsStream("img/panda.png")));
   helper.addInline("panda", logo, "image/png");

  } catch (MessagingException e) {
   throw new RuntimeException(e);
  } catch (IOException e) {
   throw new RuntimeException(e);
  }
  sender.send(message);
  System.out.println("mail sent..");
 }

 

 private JavaMailSenderImpl getJavaMailSender() {
  // enable starttls
  Properties props = new Properties();
  props.put("mail.smtp.starttls.enable", "true");

  // mail server configuration
  String host = "smtp.gmail.com";
  int port = 587;
  String userName = "xxxx";
  String password = "xxxx";

  JavaMailSenderImpl sender = new JavaMailSenderImpl();
  sender.setJavaMailProperties(props);
  sender.setHost(host);
  sender.setPort(port);
  sender.setUsername(userName);
  sender.setPassword(password);
  sender.setDefaultEncoding("UTF-8");

  return sender;
 }

Remember to update your maven dependency:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 <!-- email -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jaf</groupId>
            <artifactId>activation</artifactId>
            <version>1.0.2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mail</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <!-- velocity -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>2.0</version>
        </dependency>


Reference
[1] http://www.rgagnon.com/javadetails/java-0504.html

No comments: