Send Text, HTML, and Attachment Emails with Spring Boot
· One min read
Add the Spring Boot mail starter and configure the provider's SMTP host, port, authentication, and TLS mode. Store credentials in environment variables or a secret manager.
Plain text:
SimpleMailMessage message = new SimpleMailMessage();
message.setTo("receiver@example.com");
message.setSubject("Hello");
message.setText("Plain-text message");
mailSender.send(message);
HTML and attachments:
MimeMessage mime = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mime, true, "UTF-8");
helper.setTo("receiver@example.com");
helper.setSubject("Report");
helper.setText("<h1>Report</h1>", true);
helper.addAttachment("report.pdf", new File("/safe/path/report.pdf"));
mailSender.send(mime);
Do not insert untrusted HTML without sanitization. Validate attachment paths and sizes, set connection and write timeouts, log provider response identifiers rather than message contents, and use asynchronous delivery or a queue when email should not delay an HTTP request.