protected Session getEmailSession()

in manager/general/src/main/java/org/apache/doris/stack/component/MailComponent.java [335:384]


    protected Session getEmailSession(EmailInfo emailInfo) {
        try {
            log.info("Get email session by email info.");

            Properties props = new Properties();
            props.put("mail.transport.protocol", ConfigConstant.EMAIL_PROTOCOL_KEY);
            props.put("mail.smtp.host", emailInfo.getSmtpHost());
            props.put("mail.smtp.port", emailInfo.getSmtpPort());
            EmailInfo.SmtpSecurity smtpSecurity = EmailInfo.SmtpSecurity.valueOf(emailInfo.getSmtpSecurity());
            switch (smtpSecurity) {
                case ssl:
                    props.put("mail.smtp.auth", true);
                    props.put("mail.smtp.ssl.enable", true);
                    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    break;
                case tls:
                    props.put("mail.smtp.starttls.enable", true);
                    break;
                case starttls:
                    props.put("mail.smtp.auth", false);
                    props.put("mail.smtp.socketFactory.port", emailInfo.getSmtpHost());
                    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    props.put("mail.smtp.socketFactory.fallback", false);
                    props.put("mail.smtp.starttls.enable", true);
                    break;
                case none:
                    props.put("mail.smtp.auth", false);
                    break;
                default:
                    break;
            }

            Session session = null;
            if (smtpSecurity == EmailInfo.SmtpSecurity.none) {
                // getDefaultInstance is singleton mode
                session = Session.getInstance(props);
            } else {
                Authenticator auth = new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailInfo.getSmtpUsername(), emailInfo.getSmtpPassword());
                    }
                };
                session = Session.getInstance(props, auth);
            }
            return session;
        } catch (Exception e) {
            log.error("Get Email session exception", e);
            return null;
        }
    }