0
# Mail Integration
1
2
Spring Context Support provides complete mail functionality from simple text messages to complex MIME messages with attachments. It offers an abstraction layer over JavaMail with Spring-friendly configuration, error handling, and both synchronous and asynchronous message sending capabilities.
3
4
## Capabilities
5
6
### Core Mail Interfaces
7
8
Primary interfaces for mail sending operations, providing abstraction over different mail implementations.
9
10
```java { .api }
11
/**
12
* Core interface for mail sending operations
13
*/
14
public interface MailSender {
15
/**
16
* Send a simple mail message
17
* @param simpleMessage the message to send
18
* @throws MailException if sending fails
19
*/
20
void send(SimpleMailMessage simpleMessage) throws MailException;
21
22
/**
23
* Send multiple simple mail messages
24
* @param simpleMessages the messages to send
25
* @throws MailException if sending fails
26
*/
27
void send(SimpleMailMessage... simpleMessages) throws MailException;
28
}
29
30
/**
31
* Extended interface for MIME message support and advanced mail operations
32
*/
33
public interface JavaMailSender extends MailSender {
34
/**
35
* Create a new MimeMessage instance
36
* @return a new MimeMessage instance
37
*/
38
MimeMessage createMimeMessage();
39
40
/**
41
* Create a new MimeMessage instance from an InputStream
42
* @param contentStream the content stream to read from
43
* @return a new MimeMessage instance
44
* @throws MailException if message creation fails
45
*/
46
MimeMessage createMimeMessage(InputStream contentStream) throws MailException;
47
48
/**
49
* Send a MIME message
50
* @param mimeMessage the message to send
51
* @throws MailException if sending fails
52
*/
53
void send(MimeMessage mimeMessage) throws MailException;
54
55
/**
56
* Send multiple MIME messages
57
* @param mimeMessages the messages to send
58
* @throws MailException if sending fails
59
*/
60
void send(MimeMessage... mimeMessages) throws MailException;
61
62
/**
63
* Send a message using a preparator callback
64
* @param mimeMessagePreparator callback for message preparation
65
* @throws MailException if sending fails
66
*/
67
void send(MimeMessagePreparator mimeMessagePreparator) throws MailException;
68
69
/**
70
* Send multiple messages using preparator callbacks
71
* @param mimeMessagePreparators callbacks for message preparation
72
* @throws MailException if sending fails
73
*/
74
void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException;
75
}
76
```
77
78
### JavaMail Implementation
79
80
Concrete implementation of JavaMailSender with full SMTP configuration and connection management.
81
82
```java { .api }
83
/**
84
* Production implementation of JavaMailSender with SMTP support
85
*/
86
public class JavaMailSenderImpl implements JavaMailSender {
87
/**
88
* Create a new JavaMailSenderImpl instance
89
*/
90
public JavaMailSenderImpl();
91
92
/**
93
* Set additional JavaMail properties
94
* @param javaMailProperties additional properties
95
*/
96
public void setJavaMailProperties(Properties javaMailProperties);
97
98
/**
99
* Get the JavaMail properties
100
* @return the JavaMail properties
101
*/
102
public Properties getJavaMailProperties();
103
104
/**
105
* Set the JavaMail Session to use
106
* @param session the JavaMail Session
107
*/
108
public void setSession(Session session);
109
110
/**
111
* Get the JavaMail Session
112
* @return the JavaMail Session
113
*/
114
public Session getSession();
115
116
/**
117
* Set the protocol to use (default is "smtp")
118
* @param protocol the mail protocol
119
*/
120
public void setProtocol(String protocol);
121
122
/**
123
* Get the mail protocol
124
* @return the mail protocol
125
*/
126
public String getProtocol();
127
128
/**
129
* Set the SMTP server host
130
* @param host the SMTP host
131
*/
132
public void setHost(String host);
133
134
/**
135
* Get the SMTP server host
136
* @return the SMTP host
137
*/
138
public String getHost();
139
140
/**
141
* Set the SMTP server port
142
* @param port the SMTP port
143
*/
144
public void setPort(int port);
145
146
/**
147
* Get the SMTP server port
148
* @return the SMTP port
149
*/
150
public int getPort();
151
152
/**
153
* Set the username for SMTP authentication
154
* @param username the username
155
*/
156
public void setUsername(String username);
157
158
/**
159
* Get the username for SMTP authentication
160
* @return the username
161
*/
162
public String getUsername();
163
164
/**
165
* Set the password for SMTP authentication
166
* @param password the password
167
*/
168
public void setPassword(String password);
169
170
/**
171
* Get the password for SMTP authentication
172
* @return the password
173
*/
174
public String getPassword();
175
176
/**
177
* Set the default message encoding
178
* @param defaultEncoding the default encoding
179
*/
180
public void setDefaultEncoding(String defaultEncoding);
181
182
/**
183
* Get the default message encoding
184
* @return the default encoding
185
*/
186
public String getDefaultEncoding();
187
188
/**
189
* Set the default FileTypeMap for MIME messages
190
* @param defaultFileTypeMap the FileTypeMap to use
191
*/
192
public void setDefaultFileTypeMap(FileTypeMap defaultFileTypeMap);
193
194
/**
195
* Get the default FileTypeMap for MIME messages
196
* @return the default FileTypeMap
197
*/
198
public FileTypeMap getDefaultFileTypeMap();
199
200
/**
201
* Test the mail server connection
202
* @throws MessagingException if connection fails
203
*/
204
public void testConnection() throws MessagingException;
205
}
206
```
207
208
**Usage Examples:**
209
210
```java
211
@Configuration
212
public class MailConfig {
213
214
@Bean
215
public JavaMailSender javaMailSender() {
216
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
217
mailSender.setHost("smtp.gmail.com");
218
mailSender.setPort(587);
219
mailSender.setUsername("username@gmail.com");
220
mailSender.setPassword("password");
221
222
Properties props = mailSender.getJavaMailProperties();
223
props.put("mail.transport.protocol", "smtp");
224
props.put("mail.smtp.auth", "true");
225
props.put("mail.smtp.starttls.enable", "true");
226
props.put("mail.debug", "true");
227
228
return mailSender;
229
}
230
}
231
232
@Service
233
public class EmailService {
234
235
@Autowired
236
private JavaMailSender mailSender;
237
238
public void sendSimpleEmail(String to, String subject, String text) {
239
SimpleMailMessage message = new SimpleMailMessage();
240
message.setFrom("noreply@example.com");
241
message.setTo(to);
242
message.setSubject(subject);
243
message.setText(text);
244
mailSender.send(message);
245
}
246
}
247
```
248
249
### Simple Mail Message
250
251
Basic mail message implementation for simple text-based emails.
252
253
```java { .api }
254
/**
255
* Simple mail message implementation for text-based emails
256
*/
257
public class SimpleMailMessage implements MailMessage, Serializable {
258
/**
259
* Default constructor
260
*/
261
public SimpleMailMessage();
262
263
/**
264
* Copy constructor
265
* @param original the message to copy
266
*/
267
public SimpleMailMessage(SimpleMailMessage original);
268
269
/**
270
* Set the From field
271
* @param from the sender address
272
*/
273
public void setFrom(String from);
274
275
/**
276
* Get the From field
277
* @return the sender address
278
*/
279
public String getFrom();
280
281
/**
282
* Set the Reply-To field
283
* @param replyTo the reply-to address
284
*/
285
public void setReplyTo(String replyTo);
286
287
/**
288
* Get the Reply-To field
289
* @return the reply-to address
290
*/
291
public String getReplyTo();
292
293
/**
294
* Set the To field (single recipient)
295
* @param to the recipient address
296
*/
297
public void setTo(String to);
298
299
/**
300
* Set the To field (multiple recipients)
301
* @param to array of recipient addresses
302
*/
303
public void setTo(String... to);
304
305
/**
306
* Get the To field
307
* @return array of recipient addresses
308
*/
309
public String[] getTo();
310
311
/**
312
* Set the CC field (single recipient)
313
* @param cc the CC address
314
*/
315
public void setCc(String cc);
316
317
/**
318
* Set the CC field (multiple recipients)
319
* @param cc array of CC addresses
320
*/
321
public void setCc(String... cc);
322
323
/**
324
* Get the CC field
325
* @return array of CC addresses
326
*/
327
public String[] getCc();
328
329
/**
330
* Set the BCC field (single recipient)
331
* @param bcc the BCC address
332
*/
333
public void setBcc(String bcc);
334
335
/**
336
* Set the BCC field (multiple recipients)
337
* @param bcc array of BCC addresses
338
*/
339
public void setBcc(String... bcc);
340
341
/**
342
* Get the BCC field
343
* @return array of BCC addresses
344
*/
345
public String[] getBcc();
346
347
/**
348
* Set the subject
349
* @param subject the message subject
350
*/
351
public void setSubject(String subject);
352
353
/**
354
* Get the subject
355
* @return the message subject
356
*/
357
public String getSubject();
358
359
/**
360
* Set the message text
361
* @param text the message text
362
*/
363
public void setText(String text);
364
365
/**
366
* Get the message text
367
* @return the message text
368
*/
369
public String getText();
370
371
/**
372
* Set the sent date
373
* @param sentDate the sent date
374
*/
375
public void setSentDate(Date sentDate);
376
377
/**
378
* Get the sent date
379
* @return the sent date
380
*/
381
public Date getSentDate();
382
383
/**
384
* Copy this message to another SimpleMailMessage
385
* @param target the target message to copy to
386
*/
387
public void copyTo(SimpleMailMessage target);
388
}
389
```
390
391
### MIME Message Support
392
393
Advanced message creation and handling for complex email scenarios.
394
395
```java { .api }
396
/**
397
* Helper class for easy creation of MIME messages
398
*/
399
public class MimeMessageHelper {
400
/**
401
* Create a MimeMessageHelper for the given MimeMessage
402
* @param mimeMessage the MimeMessage to work with
403
*/
404
public MimeMessageHelper(MimeMessage mimeMessage);
405
406
/**
407
* Create a MimeMessageHelper with multipart support
408
* @param mimeMessage the MimeMessage to work with
409
* @param multipart whether to create a multipart message
410
*/
411
public MimeMessageHelper(MimeMessage mimeMessage, boolean multipart);
412
413
/**
414
* Create a MimeMessageHelper with multipart and encoding support
415
* @param mimeMessage the MimeMessage to work with
416
* @param multipart whether to create a multipart message
417
* @param encoding the character encoding to use
418
*/
419
public MimeMessageHelper(MimeMessage mimeMessage, boolean multipart, String encoding);
420
421
/**
422
* Set the From field
423
* @param from the sender address
424
* @throws jakarta.mail.jakarta.mail.MessagingException if setting fails
425
*/
426
public void setFrom(String from) throws jakarta.mail.jakarta.mail.MessagingException;
427
428
/**
429
* Set the From field with personal name
430
* @param from the sender address
431
* @param personal the personal name
432
* @throws jakarta.mail.MessagingException if setting fails
433
*/
434
public void setFrom(String from, String personal) throws jakarta.mail.MessagingException;
435
436
/**
437
* Set the To field (single recipient)
438
* @param to the recipient address
439
* @throws jakarta.mail.MessagingException if setting fails
440
*/
441
public void setTo(String to) throws jakarta.mail.MessagingException;
442
443
/**
444
* Set the To field (multiple recipients)
445
* @param to array of recipient addresses
446
* @throws jakarta.mail.MessagingException if setting fails
447
*/
448
public void setTo(String... to) throws jakarta.mail.MessagingException;
449
450
/**
451
* Set the subject
452
* @param subject the message subject
453
* @throws jakarta.mail.MessagingException if setting fails
454
*/
455
public void setSubject(String subject) throws jakarta.mail.MessagingException;
456
457
/**
458
* Set the message text (plain text)
459
* @param text the message text
460
* @throws jakarta.mail.MessagingException if setting fails
461
*/
462
public void setText(String text) throws jakarta.mail.MessagingException;
463
464
/**
465
* Set the message text with HTML support
466
* @param text the message text
467
* @param html whether the text is HTML
468
* @throws jakarta.mail.MessagingException if setting fails
469
*/
470
public void setText(String text, boolean html) throws jakarta.mail.MessagingException;
471
472
/**
473
* Add an attachment
474
* @param attachmentFilename the attachment filename
475
* @param dataSource the attachment data source
476
* @throws jakarta.mail.MessagingException if adding fails
477
*/
478
public void addAttachment(String attachmentFilename, DataSource dataSource) throws jakarta.mail.MessagingException;
479
480
/**
481
* Add an attachment from a file
482
* @param attachmentFilename the attachment filename
483
* @param file the file to attach
484
* @throws jakarta.mail.MessagingException if adding fails
485
*/
486
public void addAttachment(String attachmentFilename, File file) throws jakarta.mail.MessagingException;
487
488
/**
489
* Add an inline resource
490
* @param contentId the content ID for referencing in HTML
491
* @param dataSource the resource data source
492
* @throws jakarta.mail.MessagingException if adding fails
493
*/
494
public void addInline(String contentId, DataSource dataSource) throws jakarta.mail.MessagingException;
495
496
/**
497
* Add an inline resource from a file
498
* @param contentId the content ID for referencing in HTML
499
* @param file the file to inline
500
* @throws jakarta.mail.MessagingException if adding fails
501
*/
502
public void addInline(String contentId, File file) throws jakarta.mail.MessagingException;
503
}
504
505
/**
506
* Callback interface for preparing MIME messages
507
*/
508
@FunctionalInterface
509
public interface MimeMessagePreparator {
510
/**
511
* Prepare the given MimeMessage
512
* @param mimeMessage the message to prepare
513
* @throws Exception if preparation fails
514
*/
515
void prepare(MimeMessage mimeMessage) throws Exception;
516
}
517
```
518
519
**Usage Examples:**
520
521
```java
522
@Service
523
public class AdvancedEmailService {
524
525
@Autowired
526
private JavaMailSender mailSender;
527
528
public void sendHtmlEmailWithAttachment(String to, String subject, String htmlBody, File attachment) {
529
mailSender.send(mimeMessage -> {
530
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
531
helper.setFrom("noreply@example.com");
532
helper.setTo(to);
533
helper.setSubject(subject);
534
helper.setText(htmlBody, true); // true = HTML
535
helper.addAttachment("document.pdf", attachment);
536
});
537
}
538
539
public void sendEmailWithInlineImage(String to, String subject) {
540
mailSender.send(mimeMessage -> {
541
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
542
helper.setTo(to);
543
helper.setSubject(subject);
544
545
String htmlMsg = "<h3>Hello World!</h3><img src='cid:logo'>";
546
helper.setText(htmlMsg, true);
547
548
ClassPathResource logo = new ClassPathResource("logo.png");
549
helper.addInline("logo", logo);
550
});
551
}
552
}
553
```
554
555
### Mail Message Interfaces
556
557
Common interfaces for mail message implementations.
558
559
```java { .api }
560
/**
561
* Common interface for mail message implementations
562
*/
563
public interface MailMessage {
564
void setFrom(String from) throws MailParseException;
565
void setReplyTo(String replyTo) throws MailParseException;
566
void setTo(String... to) throws MailParseException;
567
void setCc(String... cc) throws MailParseException;
568
void setBcc(String... bcc) throws MailParseException;
569
void setSubject(String subject);
570
void setText(String text);
571
}
572
573
/**
574
* MIME message adapter implementing MailMessage interface
575
*/
576
public class MimeMailMessage implements MailMessage {
577
/**
578
* Create a MimeMailMessage for the given MimeMessage
579
* @param mimeMessage the underlying MimeMessage
580
*/
581
public MimeMailMessage(MimeMessage mimeMessage);
582
583
/**
584
* Create a MimeMailMessage with a MimeMessageHelper
585
* @param mimeMessageHelper the helper to use
586
*/
587
public MimeMailMessage(MimeMessageHelper mimeMessageHelper);
588
589
/**
590
* Get the underlying MimeMessage
591
* @return the MimeMessage
592
*/
593
public final MimeMessage getMimeMessage();
594
595
/**
596
* Get the MimeMessageHelper if available
597
* @return the MimeMessageHelper, or null
598
*/
599
public final MimeMessageHelper getMimeMessageHelper();
600
}
601
```
602
603
### Exception Hierarchy
604
605
Comprehensive exception hierarchy for mail operation failures.
606
607
```java { .api }
608
/**
609
* Base class for all mail-related exceptions
610
*/
611
public abstract class MailException extends NestedRuntimeException {
612
public MailException(String msg);
613
public MailException(String msg, Throwable cause);
614
}
615
616
/**
617
* Exception thrown on mail authentication failures
618
*/
619
public class MailAuthenticationException extends MailException {
620
public MailAuthenticationException(String msg);
621
public MailAuthenticationException(String msg, Throwable cause);
622
}
623
624
/**
625
* Exception thrown when mail sending fails
626
*/
627
public class MailSendException extends MailException {
628
public MailSendException(String msg);
629
public MailSendException(String msg, Throwable cause);
630
public MailSendException(String msg, Throwable cause, Map<Object, Exception> failedMessages);
631
632
/**
633
* Get the failed messages and their exceptions
634
* @return map of failed messages to exceptions
635
*/
636
public final Map<Object, Exception> getFailedMessages();
637
}
638
639
/**
640
* Exception thrown when mail message parsing fails
641
*/
642
public class MailParseException extends MailException {
643
public MailParseException(String msg);
644
public MailParseException(String msg, Throwable cause);
645
}
646
647
/**
648
* Exception thrown during mail message preparation
649
*/
650
public class MailPreparationException extends MailException {
651
public MailPreparationException(String msg);
652
public MailPreparationException(String msg, Throwable cause);
653
}
654
```
655
656
### Utility Classes
657
658
Additional utility classes for mail configuration and processing.
659
660
```java { .api }
661
/**
662
* Configurable MIME type mapping for file attachments
663
*/
664
public class ConfigurableMimeFileTypeMap extends MimetypesFileTypeMap {
665
/**
666
* Set additional MIME type mappings
667
* @param mappings array of "extension=mimetype" mappings
668
*/
669
public void setMappings(String... mappings);
670
671
/**
672
* Set the location of a mime.types file
673
* @param mappingLocation the resource location
674
*/
675
public void setMappingLocation(Resource mappingLocation);
676
}
677
678
/**
679
* PropertyEditor for InternetAddress objects
680
*/
681
public class InternetAddressEditor extends PropertyEditorSupport {
682
@Override
683
public void setAsText(String text) throws IllegalArgumentException;
684
685
@Override
686
public String getAsText();
687
}
688
```