68. Test email notification (#7)

This commit is contained in:
Art
2021-09-08 21:12:28 +03:00
parent 36662c8eaf
commit f39c32e2c2
2 changed files with 21 additions and 3 deletions

View File

@ -1,6 +1,8 @@
package net.shyshkin.study.fullstack.supportportal.backend.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import javax.mail.Message;
@ -16,12 +18,19 @@ import static net.shyshkin.study.fullstack.supportportal.backend.constant.EmailC
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {
private final Environment environment;
public void sendNewPasswordEmail(String firstName, String password, String email) throws MessagingException {
Message message = createEmail(firstName, password, email);
Transport transport = getEmailSession().getTransport(SIMPLE_MAIL_TRANSFER_PROTOCOL);
transport.connect(GMAIL_SMTP_SERVER, USERNAME, PASSWORD);
String mailUsername = environment.getProperty("PORTAL_MAIL_USERNAME", USERNAME);
String mailPassword = environment.getProperty("PORTAL_MAIL_PASSWORD", PASSWORD);
transport.connect(GMAIL_SMTP_SERVER, mailUsername, mailPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}

View File

@ -17,6 +17,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.mail.MessagingException;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@ -37,6 +38,7 @@ public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final LoginAttemptService loginAttemptService;
private final EmailService emailService;
@Override
@Transactional
@ -68,7 +70,6 @@ public class UserServiceImpl implements UserService {
String rawPassword = generatePassword();
String encodedPassword = passwordEncoder.encode(rawPassword);
log.debug("Raw password: {}. Encoded password: {}", rawPassword, encodedPassword);
User newUser = User.builder()
.email(email)
@ -86,7 +87,15 @@ public class UserServiceImpl implements UserService {
.role(defaultRole.name())
.authorities(defaultRole.getAuthorities())
.build();
return userRepository.save(newUser);
userRepository.save(newUser);
try {
emailService.sendNewPasswordEmail(newUser.getFirstName(), rawPassword, newUser.getEmail());
} catch (MessagingException exception) {
log.error("Can't send message", exception);
}
return newUser;
}
private String getTemporaryProfileImageUrl() {