Dispatching emails via the baseline JavaMail API demands preliminary configuraton: activating POP3/SMTP protocols on the provider dashboard and acquiring an application-specific authorization token for third-party authentication.
public void dispatchNativeEmail() {
String senderAddress = "admin@example.com";
String authCode = "GENERATED_APP_TOKEN";
String targetRecipient = "client@domain.com";
Properties smtpConfig = new Properties();
smtpConfig.setProperty("mail.transport.protocol", "smtp");
smtpConfig.setProperty("mail.smtp.host", "smtp.example.com");
smtpConfig.setProperty("mail.smtp.port", "465");
smtpConfig.setProperty("mail.smtp.auth", "true");
smtpConfig.setProperty("mail.smtp.ssl.enable", "true");
smtpConfig.setProperty("mail.debug", "true");
Session mailSession = Session.getDefaultInstance(smtpConfig);
try {
MimeMessage emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(senderAddress));
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(targetRecipient));
emailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(senderAddress));
emailMessage.setSubject("Critical System Alert");
emailMessage.setText("Anomaly detected in processing pipeline.");
Transport deliveryAgent = mailSession.getTransport();
deliveryAgent.connect(senderAddress, authCode);
deliveryAgent.sendMessage(emailMessage, emailMessage.getAllRecipients());
deliveryAgent.close();
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
In enterprise aplications, leveraging the Spring Boot Mail starter is recommended to minimize boilerplate logic. Include the dependency in your project build file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Connection parameter are then defined declaratively within the application configuration, superseding manual property instantiation:
spring:
mail:
protocol: smtp
host: smtp.example.com
port: 465
username: admin@example.com
password: GENERATED_APP_TOKEN
properties:
mail:
smtp:
auth: true
ssl:
enable: true