Configure an email service ready for sending emails. Supporting templating with thymeleaf.
Edit pom.xml
, add the starter:
<dependency>
<groupId>io.57blocks</groupId>
<artifactId>email-spring-boot-starter</artifactId>
<version>${io.57blocks.email.version}</version>
</dependency>
By default, this starter can benefit from spring-boot-starter-mail
by using SMTP
protocol
or JNDI
to sending out emails, without other dependencies.
Edit application.yml
, add the following properties:
spring.mail:
host: email-smtp.us-west-2.amazonaws.com
username: username
password: password
properties:
mail.transport.protocol: smtp
mail.smtp.port: 25
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.starttls.required: true
If you want to use AWS SES sdk to send email via http(s)
protocol, you need to import some additional
dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-ses</artifactId>
<version>1.11.415</version>
</dependency>
</dependencies>
Then update the configuration by removing spring.mail
and adding AWS cloud basic configuration:
cloud:
aws:
region:
static: us-east-2
credentials:
accessKey: accessKey
secretKey: secretKey
Default layout in /src/main/resources
:
email/
text/
greeting.txt
html/
greeting.html
subject/
greeting.txt
messages.properties
messages_zh.properties
To configure template file layout, edit application.yml
:
io.57blocks.email:
enabled: true
template:
prefix: /email/
message_base_name: messages
html:
pattern: html/*
suffix: .html
character_encoding: UTF-8
cacheable: false
text:
pattern: text/*
suffix: .txt
character_encoding: UTF-8
cacheable: false
subject:
pattern: subject/*
suffix: .txt
character_encoding: UTF-8
cacheable: false
To send email, inject EmailService
into the bean.
public class GreetingService {
@Autowired
private EmailService emailService;
public void sendEmail() {
try {
Map<String, Object> ctx = ImmutableMap.of("name", "Mr. Smith");
emailService.sendHtmlMail("Sender <[email protected]>", "greeting", Locale.CHINESE, ctx, "Mr. Smith <[email protected]>");
} catch (MessagingException e) {
// ignored
}
}
public void sendEmailByMessageFormat() {
try {
Map<String, Object> ctx = ImmutableMap.of("name", "Mr. Smith");
Message message = new MessageBuilder()
.from("Sender <[email protected]>")
.template("greeting")
.locale(Locale.CHINESE)
.context(ctx)
.recipients(Arrays.asList("Mr. Smith <[email protected]>"))
.build();
emailService.sendHtmlMail(message);
} catch (MessagingException e) {
// ignored
}
}
}
- spring-mail-example: build on
spring-boot-starter-mail
. - aws-ses-example: build on
spring-cloud-aws-starter
andaws-sdk-java-ses
.