ChloeCheerUp
ChloeCheerUp

Reputation: 3

How to upgrade SMTP to OAUTH for Spring Boot email send function?

I designed and deployed a Spring Boot web application for my company. Users fill in online forms and click the "Send" button to send an email to designated recipients using SMTP through Office 365. However, I was informed that effective 9/25/2025, Microsoft will require OAuth to connect for sending emails, replacing smtp.office365.com.

I’ve done extensive research and tried various methods, but I haven’t been able to find a solution. Could anyone provide instructions or insights on how to make this change? Below are my current properties settings:

spring.mail.transport.protocol=smtp
spring.mail.host=smtp.office365.com
spring.mail.port=587
[email protected]

# Use the OAuth2 access token here
spring.mail.properties.mail.smtp.sasl.enable=true
spring.mail.properties.mail.smtp.sasl.mechanisms=XOAUTH2
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

# This is the authorization token you will get from the OAuth flow (OAuth2 token):
spring.mail.properties.mail.smtp.auth.token=YOUR_ACCESS_TOKEN

EmailService is pretty simple with SMTP, does it need a change to switch to OAuth?

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender emailSender;

    @Async
    @Override
    public void send(Map<String, File> fileMap, List<String> to) throws MessagingException {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom("[email protected]");
        // helper.setTo(to);


        helper.setTo(to.toArray(new String[0]));

        Set<String> keySet = fileMap.keySet();
        for (String filename : keySet) {
            File file = fileMap.get(filename);
            if (file.exists()) {
                FileSystemResource fileSystemResource = new FileSystemResource(file);

                // Add logging to check the file information
                System.out.println("Attaching file: " + filename);

                // Use ByteArrayResource to add attachments
                helper.addAttachment(filename, fileSystemResource);
            }
        }
        helper.setText(
                "<b>DO NOT REPLY</b><br>" +
                    "confirmation email message typed here", true);

        helper.setSubject("Application Received - Thank you for your Interest.");
        emailSender.send(message);
    }
}

Upvotes: 0

Views: 74

Answers (0)

Related Questions