Skip to content

Commit

Permalink
fix(email): ensure consistent FROM address to match SMTP username (
Browse files Browse the repository at this point in the history
…#290)

Set the `FROM` address explicitly in the email-sending logic to match the configured `SMTP` username. This resolves issues where emails could be rejected by some mail servers due to a mismatch between the `FROM` address and the SMTP authenticated user.
  • Loading branch information
MDeLuise authored Aug 22, 2024
1 parent f7eaca4 commit 20106d7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class EmailService implements NotificationDispatcher {
private final TemporaryPasswordService temporaryPasswordService;
private final String contactEmail;
private final boolean enabled;
private final String from;
private final Logger logger = LoggerFactory.getLogger(EmailService.class);


Expand All @@ -39,13 +40,15 @@ public class EmailService implements NotificationDispatcher {
public EmailService(JavaMailSender emailSender, SpringTemplateEngine templateEngine, OtpService otpService,
TemporaryPasswordService temporaryPasswordService,
@Value("${server.owner.contact}") String contactEmail,
@Value("${spring.mail.host}") String smtpHost) throws EmailException {
@Value("${spring.mail.host}") String smtpHost,
@Value("${spring.mail.username}") String from) throws EmailException {
this.emailSender = emailSender;
this.templateEngine = templateEngine;
this.otpService = otpService;
this.temporaryPasswordService = temporaryPasswordService;
this.contactEmail = contactEmail;
this.enabled = Strings.isNotEmpty(smtpHost);
this.from = from;
if (isEnabled()) {
checkConnection();
}
Expand Down Expand Up @@ -230,6 +233,7 @@ private MimeMessageHelper createMessageHelper(MimeMessage mimeMessage, String to
helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setFrom(from);
} catch (MessagingException e) {
logger.error("Error while setting mail to send", e);
throw new EmailException(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class EmailServiceUnitTests {
private Transport transport;
@Mock
private MimeMessage mimeMessage;
private final String from = "test@test.com";
private EmailService emailService;


Expand All @@ -41,7 +42,7 @@ void setup() throws EmailException, NoSuchProviderException {
//Mockito.when(session.getTransport("smtp")).thenReturn(transport);
Mockito.when(emailSender.createMimeMessage()).thenReturn(mimeMessage);
emailService =
new EmailService(emailSender, templateEngine, otpService, temporaryPasswordService, "contact", "smtp");
new EmailService(emailSender, templateEngine, otpService, temporaryPasswordService, "contact", "smtp", from);
}


Expand Down

0 comments on commit 20106d7

Please sign in to comment.