forked from thymeleaf/thymeleaf.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
springmail.html
executable file
·433 lines (363 loc) · 18 KB
/
springmail.html
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rich HTML email in Spring with Thymeleaf - Thymeleaf: java XML/XHTML/HTML5 template engine</title>
<link rel="stylesheet" type="text/css" media="all" href="css/thymeleaf.css" />
<link rel="shortcut icon" href="http://www.thymeleaf.org/favicon.ico" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1276954-9']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="sh/scripts/shCore.js"></script>
<script type="text/javascript" src="sh/scripts/shBrushXml.js"></script>
<script type="text/javascript" src="sh/scripts/shBrushJava.js"></script>
<link href="sh/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="sh/styles/shThemeThymeleaf.css" rel="stylesheet" type="text/css" />
</head>
<body lang="en" dir="ltr">
<div id="page">
<div id="menu">
<ul>
<li><a href="index.html" title="Home">Home</a></li>
<li><a href="features.html" title="Features">Features</a></li>
<li><a href="download.html" title="Download">Download</a></li>
<li><a href="documentation.html" title="Documentation">Documentation</a></li>
<li><a href="ecosystem.html" title="Ecosystem">Ecosystem</a></li>
<li><a href="http://forum.thymeleaf.org" title="User Forum">User Forum</a></li>
<li><a href="issuetracking.html" title="Issue Tracking">Issue Tracking</a></li>
</ul>
</div>
<div id="header">
<a href="index.html" title="Thymeleaf home"><img src="images/thymeleaflogonameverysmall.png" class="logo" alt="Thymeleaf Template Engine"/></a>
</div>
<div id="breadcrumb">
<a href="index.html">thymeleaf</a>
::
<a href="documentation.html">documentation</a>
::
articles
::
<span class="current">rich html email in spring with thymeleaf</span>
</div>
<div id="content">
<h1>Rich HTML email in Spring with Thymeleaf</h1>
<p id="author">
<i>By José Miguel Samper <jmiguelsamper AT users.sourceforge.net></i>
</p>
<p>
In this article we will show how to use Thymeleaf templates for composing email messages of
several kinds, and we will integrate this with Spring's email utilities in order to configure a
simple but powerful email system.
</p>
<p>
Note that, although this article —and the corresponding example app— uses the
Spring Framework, Thymeleaf can also be used for processing email templates in an application
without Spring.
</p>
<h2>Prerequisites</h2>
<p>
This article assumes you are familiar with both Thymeleaf and Spring 3.
We will not dive into Spring Mail details, for further information please take a look at the
<a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mail.html">Email
chapter at the Spring Documentation</a>.
</p>
<h2>Example application</h2>
<p>
All the code in this article comes from a working example application you can download from
the <a href="documentation.html">documentation page</a>. Downloading this application, executing
it and exploring its source code is highly recommended <i>(note that you will have to configure your
SMTP user name and password at <kbd>configuration.properties</kbd>)</i>.
</p>
<h2>Sending email with Spring</h2>
<p>
First, you need to configure a <b>Mail Sender</b> object in your Spring configuration, as in the
following XML (your specific configuration needs might differ):
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.server.host}" />
<property name="port" value="${mail.server.port}" />
<property name="protocol" value="${mail.server.protocol}" />
<property name="username" value="${mail.server.username}" />
<property name="password" value="${mail.server.password}" />
<property name="javaMailProperties">
<util:properties location="classpath:javamail.properties" />
</property>
</bean>
]]></script>
<p>
Spring provides a class called <kbd>MimeMessageHelper</kbd> to ease the creation of email messages.
Let's see how to use it together with our <kbd>mailSender</kbd>.
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setFrom("[email protected]");
message.setTo("[email protected]");
message.setSubject("This is the message subject");
message.setText("This is the message body");
this.mailSender.send(mimeMessage);
]]></script>
<h2>Thymeleaf HTML email templates</h2>
<p>
Using Thymeleaf for processing our email templates would allow us to use
some interesting features:
</p>
<ul>
<li><b>Expressions</b> in Spring EL.</li>
<li>Flow control: <b>iterations</b>, <b>conditionals</b>, ...</li>
<li><b>Utility functions</b>: date/number formatting, dealing with lists, arrays...</li>
<li>Easy <b>i18n</b>, integrated with our application's Spring internationalization infrastructure.</li>
<li><b>Natural templating</b>: our email templates can be static prototypes, written by UI designers.</li>
<li>etc...</li>
</ul>
<p>
Also, given the fact that Thymeleaf has no dependencies on the servlet API, there would be <b>no need at all
to create or send this HTML email from a web application</b>. The techniques explained here could be used with little
or no change in a standalone application with no web UI.
</p>
<h3>Our goals</h3>
<p>
Our example application will be sending three types of emails:
</p>
<ol>
<li>Simple HTML (with internationalized greeting).</li>
<li>HTML text with an attachment.</li>
<li>HTML text witn an inline image.</li>
</ol>
<h3>Spring configuration</h3>
<p>
In order to process our templates, we will need to configure our <kbd>TemplateEngine</kbd> at
<kbd>spring-servlet.xml</kbd>:
</p>
<script type="syntaxhighlighter" class="brush:xml"><![CDATA[
<!-- THYMELEAF: Template Resolver for email templates -->
<bean id="emailTemplateResolver" class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="prefix" value="mail/" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
<property name="order" value="1" />
</bean>
<!-- THYMELEAF: Template Resolver for webapp pages -->
<!-- (we would not need this if our app was not web) -->
<bean id="webTemplateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
<property name="order" value="2" />
</bean>
<!-- THYMELEAF: Template Engine (Spring3-specific version) -->
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="emailTemplateResolver" />
<ref bean="webTemplateResolver" />
</set>
</property>
</bean>
<!-- THYMELEAF: View Resolver - implementation of Spring's ViewResolver interface -->
<!-- (we would not need this if our app was not web) -->
<bean id="viewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8" />
</bean>
]]></script>
<p>
Note that we have configured two <i>template resolvers</i> for our engine: one for the email templates
—which come from our resources directory and therefore are loaded by a <kbd>ClassLoaderTemplateResolver</kbd>—
and another one for the web templates that support the example application itself —which loads its
templates from the <i>servlet context</i>, as most Spring web applications do.
</p>
<p>
Of course, if we were creating a non-web application, we would not need either the <kbd>webTemplateResolver</kbd>
or the <kbd>viewResolver</kbd> beans at all.
</p>
<h3>Executing the Template Engine</h3>
<p>
At some point in our code, we will need to execute our template engine in order to create the text
of our messages. We have chosen to do this in an <kbd>EmailService</kbd> class, so that it stays
clear that we consider this a responsibility of our <i>business layer</i> (and not the <i>web layer</i>).
</p>
<p>
As usual in Thymeleaf, before executing we will need to populate a <i>context</i> containing
all the variables we want to use during template execution. Given the fact that our email processing
is not web-dependent, an instance of <kbd>Context</kbd> will do:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
final Context ctx = new Context(locale);
ctx.setVariable("name", recipientName);
ctx.setVariable("subscriptionDate", new Date());
ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML
final String htmlContent = this.templateEngine.process("email-inlineimage.html", ctx);
]]></script>
<p>
Our <kbd>email-inlineimage.html</kbd> is the template file we will use for sending emails
with an inlined image, and it looks like:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:remove="all">Template for HTML email with inline image</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="#{greeting(${name})}">
Hello, Peter Static!
</p>
<p th:if="${name.length() > 10}">
Wow! You've got a long name (more than 10 chars)!
</p>
<p>
You have been successfully subscribed to the <b>Fake newsletter</b> on
<span th:text="${#dates.format(subscriptionDate)}">28-12-2012</span>
</p>
<p>Your hobbies are:</p>
<ul th:remove="all-but-first">
<li th:each="hobby : ${hobbies}" th:text="${hobby}">Reading</li>
<li>Writing</li>
<li>Bowling</li>
</ul>
<p>
You can find <b>your inlined image</b> just below this text.
</p>
<p>
<img src="sample.png" th:src="'cid:' + ${imageResourceName}" />
</p>
<p>
Regards, <br />
  <em>The Thymeleaf Team</em>
</p>
</body>
</html>
]]></script>
<p>
Let's remark some points:
</p>
<ul>
<li>
The former template is fully WYSIWYG; you can check how it looks just by opening it with your browser. That's much better than sending an email
to see the result, isn't it?
</li>
</ul>
<div class="caption">
<img src="images/springmail_inline.png" />
</div>
<ul>
<li>
We can use all Thymeleaf features. Here for example we have used i18n with a
parameterized <kbd>#{...}</kbd> expression, <kbd>th:each</kbd> to iterate over a list,
<kbd>#dates</kbd> to format a date...
</li>
<li>
The <kbd>img</kbd> element has a hardcoded <kbd>src</kbd> value —nice for prototyping—, which will be substituted at runtime by something like
<kbd>cid:image.jpg</kbd> matching the attached image filename.
</li>
</ul>
<h2>Putting it all together</h2>
<h3>The service class</h3>
<p>
Finally, let's see how the method executing this email template at our <kbd>EmailService</kbd> service class
would look like:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
public void sendMailWithInline(
final String recipientName, final String recipientEmail, final String imageResourceName,
final byte[] imageBytes, final String imageContentType, final Locale locale)
throws MessagingException {
// Prepare the evaluation context
final Context ctx = new Context(locale);
ctx.setVariable("name", recipientName);
ctx.setVariable("subscriptionDate", new Date());
ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
message.setSubject("Example HTML email with inline image");
message.setFrom("[email protected]");
message.setTo(recipientEmail);
// Create the HTML body using Thymeleaf
final String htmlContent = this.templateEngine.process("email-inlineimage.html", ctx);
message.setText(htmlContent, true); // true = isHtml
// Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
message.addInline(imageResourceName, imageSource, imageContentType);
// Send mail
this.mailSender.send(mimeMessage);
}
]]></script>
<p>
Note that we have used an <kbd>org.springframework.core.io.ByteArrayResource</kbd> object to
attach the image uploaded by the user, which we previously converted into a <kbd>byte[]</kbd>.
</p>
<p>
You could also make use of <kbd>FileSystemResource</kbd> to attach a file directly from the
filesystem —thus avoiding loading it into memory—,
or <kbd>UrlResource</kbd> to attach a remote file.
</p>
<h3>The controller</h3>
<p>
Now for the controller method that calls our service:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
/*
* Send HTML mail with inline image
*/
@RequestMapping(value = "/sendMailWithInlineImage", method = RequestMethod.POST)
public String sendMailWithInline(
@RequestParam("recipientName") final String recipientName,
@RequestParam("recipientEmail") final String recipientEmail,
@RequestParam("image") final MultipartFile image,
final Locale locale)
throws MessagingException, IOException {
this.emailService.sendMailWithInline(
recipientName, recipientEmail, image.getName(),
image.getBytes(), image.getContentType(), locale);
return "redirect:sent.html";
}
]]></script>
<p>
Cannot be easier. Note how we use a Spring MVC <kbd>MultipartFile</kbd> object to model the
uploaded file and pass its contents on to the service.
</p>
<h2>More examples</h2>
<p>
For the sake of brevity, we have only detailed one of the three types of email we want
our application to send. However, you can see the source code required for creating all three
types of emails at the <kbd>springmail</kbd> example application you can download from the
<a href="documentation.html">documentation page</a>.
</p>
</div>
<div id="footer">
<div id="googleplus">
<div id="plusone-div" class="plusone"></div>
<script type="text/javascript">
gapi.plusone.render('plusone-div',{"size": "small", "count": "true", "href": "http://www.thymeleaf.org"});
</script>
</div>
<div id="twitter">
<a href="http://twitter.com/thymeleaf" class="twitter-follow-button" data-show-count="false">Follow @thymeleaf</a>
<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
</div>
<div id="copy">
Copyright © The <a href="team.html">THYMELEAF Team</a>. See <a href="documentation.html">applicable licenses</a>.
</div>
</div>
</div>
<script type="text/javascript">
SyntaxHighlighter.all();
</script>
</body>
</html>