はじめに
ローカルでsmpメールをテストする方法を紹介致します。
docker
docker run -p 80:80 -p 25:25 maildev/maildev
build.gradle
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-mail'
}
test {
...
String activeProfile = System.properties['spring.profiles.active']
println "zone: $activeProfile"
systemProperty "spring.profiles.active", activeProfile
}
config
@Slf4j
@Configuration
public class CoreConfigration {
@Value("${projects.properties.email-host}")
String emailHost;
@Value("${projects.properties.email-protocal}")
String emailProtocal;
@Value("${projects.properties.email-port}")
int emailPort;
@Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol(emailProtocal);
javaMailSender.setHost(emailHost);
javaMailSender.setPort(emailPort);
return javaMailSender;
}
...
}
yaml
spring:
profiles: local
projects:
properties:
email-host: localhost
email-port: 25
email-protocal: smtp
email-from: serviceteam@company.com
mailservice
@Service
public class MailService {
@Autowired
@Qualifier("mailSender")
JavaMailSenderImpl javaMailSender;
@Value("${projects.properties.email-from}")
String from;
public void sendHtml(String to, String subject, String content) throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject(subject);
messageHelper.setText(content, true);
javaMailSender.send(mimeMessage);
}}
test
@SpringBootTest(classes = {ServiceMonitorApplication.class, MailService.class, JavaMailSenderImpl.class, ProjectProperties.class}, webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Slf4j
class MailServiceTest {
@Autowired
MailService mailService;
@Autowired
ProjectProperties projectProperties;
@Test
public void test() throws MessagingException {
mailService.sendHtml(
"asd@asd.net",
"こんにちは",
"<b>Asdasd</b> <a href='http://google.con'> google</a>"
);
}
}
実行
spring test start
-Dspring.profiles.active=local
gradle :test --tests "com.....MailServiceTest.test" -Dspring.profiles.active=local'