Spring Framework integration support for caching (Caffeine, JCache), mail (JavaMail), scheduling (Quartz), and template engines (FreeMarker)
—
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.
Primary interfaces for mail sending operations, providing abstraction over different mail implementations.
/**
* Core interface for mail sending operations
*/
public interface MailSender {
/**
* Send a simple mail message
* @param simpleMessage the message to send
* @throws MailException if sending fails
*/
void send(SimpleMailMessage simpleMessage) throws MailException;
/**
* Send multiple simple mail messages
* @param simpleMessages the messages to send
* @throws MailException if sending fails
*/
void send(SimpleMailMessage... simpleMessages) throws MailException;
}
/**
* Extended interface for MIME message support and advanced mail operations
*/
public interface JavaMailSender extends MailSender {
/**
* Create a new MimeMessage instance
* @return a new MimeMessage instance
*/
MimeMessage createMimeMessage();
/**
* Create a new MimeMessage instance from an InputStream
* @param contentStream the content stream to read from
* @return a new MimeMessage instance
* @throws MailException if message creation fails
*/
MimeMessage createMimeMessage(InputStream contentStream) throws MailException;
/**
* Send a MIME message
* @param mimeMessage the message to send
* @throws MailException if sending fails
*/
void send(MimeMessage mimeMessage) throws MailException;
/**
* Send multiple MIME messages
* @param mimeMessages the messages to send
* @throws MailException if sending fails
*/
void send(MimeMessage... mimeMessages) throws MailException;
/**
* Send a message using a preparator callback
* @param mimeMessagePreparator callback for message preparation
* @throws MailException if sending fails
*/
void send(MimeMessagePreparator mimeMessagePreparator) throws MailException;
/**
* Send multiple messages using preparator callbacks
* @param mimeMessagePreparators callbacks for message preparation
* @throws MailException if sending fails
*/
void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException;
}Concrete implementation of JavaMailSender with full SMTP configuration and connection management.
/**
* Production implementation of JavaMailSender with SMTP support
*/
public class JavaMailSenderImpl implements JavaMailSender {
/**
* Create a new JavaMailSenderImpl instance
*/
public JavaMailSenderImpl();
/**
* Set additional JavaMail properties
* @param javaMailProperties additional properties
*/
public void setJavaMailProperties(Properties javaMailProperties);
/**
* Get the JavaMail properties
* @return the JavaMail properties
*/
public Properties getJavaMailProperties();
/**
* Set the JavaMail Session to use
* @param session the JavaMail Session
*/
public void setSession(Session session);
/**
* Get the JavaMail Session
* @return the JavaMail Session
*/
public Session getSession();
/**
* Set the protocol to use (default is "smtp")
* @param protocol the mail protocol
*/
public void setProtocol(String protocol);
/**
* Get the mail protocol
* @return the mail protocol
*/
public String getProtocol();
/**
* Set the SMTP server host
* @param host the SMTP host
*/
public void setHost(String host);
/**
* Get the SMTP server host
* @return the SMTP host
*/
public String getHost();
/**
* Set the SMTP server port
* @param port the SMTP port
*/
public void setPort(int port);
/**
* Get the SMTP server port
* @return the SMTP port
*/
public int getPort();
/**
* Set the username for SMTP authentication
* @param username the username
*/
public void setUsername(String username);
/**
* Get the username for SMTP authentication
* @return the username
*/
public String getUsername();
/**
* Set the password for SMTP authentication
* @param password the password
*/
public void setPassword(String password);
/**
* Get the password for SMTP authentication
* @return the password
*/
public String getPassword();
/**
* Set the default message encoding
* @param defaultEncoding the default encoding
*/
public void setDefaultEncoding(String defaultEncoding);
/**
* Get the default message encoding
* @return the default encoding
*/
public String getDefaultEncoding();
/**
* Set the default FileTypeMap for MIME messages
* @param defaultFileTypeMap the FileTypeMap to use
*/
public void setDefaultFileTypeMap(FileTypeMap defaultFileTypeMap);
/**
* Get the default FileTypeMap for MIME messages
* @return the default FileTypeMap
*/
public FileTypeMap getDefaultFileTypeMap();
/**
* Test the mail server connection
* @throws MessagingException if connection fails
*/
public void testConnection() throws MessagingException;
}Usage Examples:
@Configuration
public class MailConfig {
@Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("username@gmail.com");
mailSender.setPassword("password");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
}
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendSimpleEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("noreply@example.com");
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}Basic mail message implementation for simple text-based emails.
/**
* Simple mail message implementation for text-based emails
*/
public class SimpleMailMessage implements MailMessage, Serializable {
/**
* Default constructor
*/
public SimpleMailMessage();
/**
* Copy constructor
* @param original the message to copy
*/
public SimpleMailMessage(SimpleMailMessage original);
/**
* Set the From field
* @param from the sender address
*/
public void setFrom(String from);
/**
* Get the From field
* @return the sender address
*/
public String getFrom();
/**
* Set the Reply-To field
* @param replyTo the reply-to address
*/
public void setReplyTo(String replyTo);
/**
* Get the Reply-To field
* @return the reply-to address
*/
public String getReplyTo();
/**
* Set the To field (single recipient)
* @param to the recipient address
*/
public void setTo(String to);
/**
* Set the To field (multiple recipients)
* @param to array of recipient addresses
*/
public void setTo(String... to);
/**
* Get the To field
* @return array of recipient addresses
*/
public String[] getTo();
/**
* Set the CC field (single recipient)
* @param cc the CC address
*/
public void setCc(String cc);
/**
* Set the CC field (multiple recipients)
* @param cc array of CC addresses
*/
public void setCc(String... cc);
/**
* Get the CC field
* @return array of CC addresses
*/
public String[] getCc();
/**
* Set the BCC field (single recipient)
* @param bcc the BCC address
*/
public void setBcc(String bcc);
/**
* Set the BCC field (multiple recipients)
* @param bcc array of BCC addresses
*/
public void setBcc(String... bcc);
/**
* Get the BCC field
* @return array of BCC addresses
*/
public String[] getBcc();
/**
* Set the subject
* @param subject the message subject
*/
public void setSubject(String subject);
/**
* Get the subject
* @return the message subject
*/
public String getSubject();
/**
* Set the message text
* @param text the message text
*/
public void setText(String text);
/**
* Get the message text
* @return the message text
*/
public String getText();
/**
* Set the sent date
* @param sentDate the sent date
*/
public void setSentDate(Date sentDate);
/**
* Get the sent date
* @return the sent date
*/
public Date getSentDate();
/**
* Copy this message to another SimpleMailMessage
* @param target the target message to copy to
*/
public void copyTo(SimpleMailMessage target);
}Advanced message creation and handling for complex email scenarios.
/**
* Helper class for easy creation of MIME messages
*/
public class MimeMessageHelper {
/**
* Create a MimeMessageHelper for the given MimeMessage
* @param mimeMessage the MimeMessage to work with
*/
public MimeMessageHelper(MimeMessage mimeMessage);
/**
* Create a MimeMessageHelper with multipart support
* @param mimeMessage the MimeMessage to work with
* @param multipart whether to create a multipart message
*/
public MimeMessageHelper(MimeMessage mimeMessage, boolean multipart);
/**
* Create a MimeMessageHelper with multipart and encoding support
* @param mimeMessage the MimeMessage to work with
* @param multipart whether to create a multipart message
* @param encoding the character encoding to use
*/
public MimeMessageHelper(MimeMessage mimeMessage, boolean multipart, String encoding);
/**
* Set the From field
* @param from the sender address
* @throws jakarta.mail.jakarta.mail.MessagingException if setting fails
*/
public void setFrom(String from) throws jakarta.mail.jakarta.mail.MessagingException;
/**
* Set the From field with personal name
* @param from the sender address
* @param personal the personal name
* @throws jakarta.mail.MessagingException if setting fails
*/
public void setFrom(String from, String personal) throws jakarta.mail.MessagingException;
/**
* Set the To field (single recipient)
* @param to the recipient address
* @throws jakarta.mail.MessagingException if setting fails
*/
public void setTo(String to) throws jakarta.mail.MessagingException;
/**
* Set the To field (multiple recipients)
* @param to array of recipient addresses
* @throws jakarta.mail.MessagingException if setting fails
*/
public void setTo(String... to) throws jakarta.mail.MessagingException;
/**
* Set the subject
* @param subject the message subject
* @throws jakarta.mail.MessagingException if setting fails
*/
public void setSubject(String subject) throws jakarta.mail.MessagingException;
/**
* Set the message text (plain text)
* @param text the message text
* @throws jakarta.mail.MessagingException if setting fails
*/
public void setText(String text) throws jakarta.mail.MessagingException;
/**
* Set the message text with HTML support
* @param text the message text
* @param html whether the text is HTML
* @throws jakarta.mail.MessagingException if setting fails
*/
public void setText(String text, boolean html) throws jakarta.mail.MessagingException;
/**
* Add an attachment
* @param attachmentFilename the attachment filename
* @param dataSource the attachment data source
* @throws jakarta.mail.MessagingException if adding fails
*/
public void addAttachment(String attachmentFilename, DataSource dataSource) throws jakarta.mail.MessagingException;
/**
* Add an attachment from a file
* @param attachmentFilename the attachment filename
* @param file the file to attach
* @throws jakarta.mail.MessagingException if adding fails
*/
public void addAttachment(String attachmentFilename, File file) throws jakarta.mail.MessagingException;
/**
* Add an inline resource
* @param contentId the content ID for referencing in HTML
* @param dataSource the resource data source
* @throws jakarta.mail.MessagingException if adding fails
*/
public void addInline(String contentId, DataSource dataSource) throws jakarta.mail.MessagingException;
/**
* Add an inline resource from a file
* @param contentId the content ID for referencing in HTML
* @param file the file to inline
* @throws jakarta.mail.MessagingException if adding fails
*/
public void addInline(String contentId, File file) throws jakarta.mail.MessagingException;
}
/**
* Callback interface for preparing MIME messages
*/
@FunctionalInterface
public interface MimeMessagePreparator {
/**
* Prepare the given MimeMessage
* @param mimeMessage the message to prepare
* @throws Exception if preparation fails
*/
void prepare(MimeMessage mimeMessage) throws Exception;
}Usage Examples:
@Service
public class AdvancedEmailService {
@Autowired
private JavaMailSender mailSender;
public void sendHtmlEmailWithAttachment(String to, String subject, String htmlBody, File attachment) {
mailSender.send(mimeMessage -> {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("noreply@example.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlBody, true); // true = HTML
helper.addAttachment("document.pdf", attachment);
});
}
public void sendEmailWithInlineImage(String to, String subject) {
mailSender.send(mimeMessage -> {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setSubject(subject);
String htmlMsg = "<h3>Hello World!</h3><img src='cid:logo'>";
helper.setText(htmlMsg, true);
ClassPathResource logo = new ClassPathResource("logo.png");
helper.addInline("logo", logo);
});
}
}Common interfaces for mail message implementations.
/**
* Common interface for mail message implementations
*/
public interface MailMessage {
void setFrom(String from) throws MailParseException;
void setReplyTo(String replyTo) throws MailParseException;
void setTo(String... to) throws MailParseException;
void setCc(String... cc) throws MailParseException;
void setBcc(String... bcc) throws MailParseException;
void setSubject(String subject);
void setText(String text);
}
/**
* MIME message adapter implementing MailMessage interface
*/
public class MimeMailMessage implements MailMessage {
/**
* Create a MimeMailMessage for the given MimeMessage
* @param mimeMessage the underlying MimeMessage
*/
public MimeMailMessage(MimeMessage mimeMessage);
/**
* Create a MimeMailMessage with a MimeMessageHelper
* @param mimeMessageHelper the helper to use
*/
public MimeMailMessage(MimeMessageHelper mimeMessageHelper);
/**
* Get the underlying MimeMessage
* @return the MimeMessage
*/
public final MimeMessage getMimeMessage();
/**
* Get the MimeMessageHelper if available
* @return the MimeMessageHelper, or null
*/
public final MimeMessageHelper getMimeMessageHelper();
}Comprehensive exception hierarchy for mail operation failures.
/**
* Base class for all mail-related exceptions
*/
public abstract class MailException extends NestedRuntimeException {
public MailException(String msg);
public MailException(String msg, Throwable cause);
}
/**
* Exception thrown on mail authentication failures
*/
public class MailAuthenticationException extends MailException {
public MailAuthenticationException(String msg);
public MailAuthenticationException(String msg, Throwable cause);
}
/**
* Exception thrown when mail sending fails
*/
public class MailSendException extends MailException {
public MailSendException(String msg);
public MailSendException(String msg, Throwable cause);
public MailSendException(String msg, Throwable cause, Map<Object, Exception> failedMessages);
/**
* Get the failed messages and their exceptions
* @return map of failed messages to exceptions
*/
public final Map<Object, Exception> getFailedMessages();
}
/**
* Exception thrown when mail message parsing fails
*/
public class MailParseException extends MailException {
public MailParseException(String msg);
public MailParseException(String msg, Throwable cause);
}
/**
* Exception thrown during mail message preparation
*/
public class MailPreparationException extends MailException {
public MailPreparationException(String msg);
public MailPreparationException(String msg, Throwable cause);
}Additional utility classes for mail configuration and processing.
/**
* Configurable MIME type mapping for file attachments
*/
public class ConfigurableMimeFileTypeMap extends MimetypesFileTypeMap {
/**
* Set additional MIME type mappings
* @param mappings array of "extension=mimetype" mappings
*/
public void setMappings(String... mappings);
/**
* Set the location of a mime.types file
* @param mappingLocation the resource location
*/
public void setMappingLocation(Resource mappingLocation);
}
/**
* PropertyEditor for InternetAddress objects
*/
public class InternetAddressEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException;
@Override
public String getAsText();
}Install with Tessl CLI
npx tessl i tessl/maven-org-springframework--spring-context-support