ACSSendMailConfiguration.java

package com.sintia.ffl.admin.optique.catalogue.util.mail;

import com.azure.communication.email.EmailClient;
import com.azure.communication.email.EmailClientBuilder;
import com.azure.core.http.HttpClient;
import com.azure.core.http.ProxyOptions;
import com.azure.core.util.HttpClientOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;

@Configuration
@Profile("!smtp")
@Slf4j
public class ACSSendMailConfiguration {

    @Value("${ffl.mail.acs.resource-name:}")
    private String acsResourceName;

    @Value("${ffl.mail.acs.access-key:}")
    private String acsAccessKey;

    @Value("${ffl.mail.acs.proxyHost:}")
    private String httpsProxyHost;

    @Value("${ffl.mail.acs.proxyPort:}")
    private Integer httpsProxyPort;

    @Bean
    public EmailClient emailClient(){

        if(org.apache.commons.lang3.StringUtils.isBlank(this.acsResourceName)){
            throw new IllegalStateException("La propriété ffl.mail.acs.resource-name n'est pas définie.");
        }
        if(org.apache.commons.lang3.StringUtils.isBlank(this.acsAccessKey)){
            throw new IllegalStateException("La propriété ffl.mail.acs.access-key n'est pas définie.");
        }

        String connectionString = String.format(
                "endpoint=https://%1$s.communication.azure.com/;accesskey=%2$s",
                this.acsResourceName,
                this.acsAccessKey
        );

        HttpClientOptions httpClientOptions = new HttpClientOptions();

        ProxyOptions proxyOptions = null;
        if(StringUtils.hasText(this.httpsProxyHost) && this.httpsProxyPort != null) {
            proxyOptions = new ProxyOptions(
                    ProxyOptions.Type.HTTP,
                    new InetSocketAddress(this.httpsProxyHost, this.httpsProxyPort)
            );
        } else {
            log.info("Informations concernant le proxy HTTPS indéfinies ou incomplète, l'envoi de mails via Azure Communication Services n'utilisera pas de proxy.");
        }

        httpClientOptions.setProxyOptions(proxyOptions);
        HttpClient httpClient = HttpClient.createDefault(httpClientOptions);

        return new EmailClientBuilder()
                .connectionString(connectionString)
                .httpClient(httpClient)
                .buildClient();
    }


}