Working with Email Services
1. Configuring JavaMailSender Properties (SMTP)
Example: SMTP mail server configuration
spring:
mail:
host: smtp.gmail.com
port: 587
username: ${MAIL_USER}
password: ${MAIL_PASS}
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.connectiontimeout: 5000
mail.smtp.timeout: 5000
2. Sending Simple Text Emails
Example: Send plain text email
@Service
public class MailService {
private final JavaMailSender sender;
public MailService(JavaMailSender sender) { this.sender = sender; }
public void sendText(String to, String subject, String body) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(to); msg.setSubject(subject); msg.setText(body);
msg.setFrom("no-reply@example.com");
sender.send(msg);
}
}
3. Sending HTML Emails (MimeMessage)
Example: Send HTML email with MimeMessage
public void sendHtml(String to, String subject, String html) throws MessagingException {
MimeMessage mm = sender.createMimeMessage();
MimeMessageHelper h = new MimeMessageHelper(mm, true, "UTF-8");
h.setTo(to); h.setSubject(subject); h.setText(html, true);
h.setFrom("no-reply@example.com");
sender.send(mm);
}
4. Using Thymeleaf for Email Templates
Example: Render Thymeleaf email template
private final TemplateEngine engine;
public void sendWelcome(User u) throws MessagingException {
Context ctx = new Context();
ctx.setVariables(Map.of("name", u.name(), "url", "https://app/verify/" + u.token()));
String html = engine.process("emails/welcome", ctx);
sendHtml(u.email(), "Welcome", html);
}
5. Adding Email Attachments
Example: Email attachment and inline image
MimeMessageHelper h = new MimeMessageHelper(mm, true);
h.addAttachment("invoice.pdf", new FileSystemResource(path.toFile()));
h.addInline("logo", new ClassPathResource("static/logo.png"), "image/png");
// In HTML: <img src="cid:logo"/>
6. Sending Emails Asynchronously (@Async)
Example: Send email asynchronously
@Async("emailExecutor")
public CompletableFuture<Void> sendAsync(String to, String subj, String body) {
sendText(to, subj, body);
return CompletableFuture.completedFuture(null);
}
7. Configuring Email Authentication
| Property | Description |
|---|---|
mail.smtp.auth |
Enable SMTP AUTH |
mail.smtp.starttls.enable |
STARTTLS upgrade (port 587) |
mail.smtp.ssl.enable |
Implicit TLS (port 465) |
mail.smtp.ssl.trust |
Hosts to trust |
8. Using Gmail SMTP Server
| Setting | Value |
|---|---|
| Host | smtp.gmail.com |
| Port | 587 (STARTTLS) or 465 (SSL) |
| Auth | App password (2FA required) |
| From | Must match Gmail address |
9. Handling Email Sending Exceptions
Example: Handle mail send exceptions
try { sender.send(mm); }
catch (MailAuthenticationException e) { /* bad creds */ }
catch (MailSendException e) { e.getFailedMessages().forEach(/*…*/); }
catch (MailException e) { /* generic */ }
10. Testing Email Functionality (GreenMail)
Example: Test email sending with GreenMail
@SpringBootTest
class MailServiceTests {
static GreenMail green;
@BeforeAll static void up() {
green = new GreenMail(ServerSetupTest.SMTP);
green.start();
green.setUser("user", "pass");
}
@AfterAll static void down() { green.stop(); }
@Autowired MailService svc;
@Test void sends() throws Exception {
svc.sendText("to@x", "subj", "body");
assertTrue(green.waitForIncomingEmail(5000, 1));
}
}