Skip to content

Instantly share code, notes, and snippets.

@thetekst
Forked from javiyt/build.gradle
Created June 18, 2018 15:03
Show Gist options
  • Save thetekst/77caf27d2decfc6f5f796755b8a93b03 to your computer and use it in GitHub Desktop.
Save thetekst/77caf27d2decfc6f5f796755b8a93b03 to your computer and use it in GitHub Desktop.
Send Mail using spring boot, based on http://www.baeldung.com/spring-email
dependencies {
compile 'org.springframework.boot:spring-boot-starter-mail:1.5.7.RELEASE'
}
@Configuration
public class MailConfiguration {
@Bean
public JavaMailSender getJavaMailSender(MailProperties mailProperties) {
JavaMailSender mailSender = new JavaMailSenderImpl();
mailSender.setHost(mailProperties.getHost());
mailSender.setPort(mailProperties.getPort());
mailSender.setUsername(mailProperties.getUsername());
mailSender.setPassword(mailProperties.getPassword());
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
@Bean
public SimpleMailMessage templateSimpleMessage() {
SimpleMailMessage message = new SimpleMailMessage();
message.setText("This is the test email template for your email:\n%s\n");
return message;
}
}
public interface EmailService {
void sendSimpleMessage(String to, String subject, String text);
void sendMessageWithAttachment(String to, String subject, String text, String pathToAttachment);
}
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
@Override
public void sendSimpleMessage(String to, String subject, String text) {
...
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
...
}
@Override
public void sendMessageWithAttachment(
String to, String subject, String text, String pathToAttachment) {
// ...
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file
= new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
emailSender.send(message);
// ...
}
}
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login user to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment