001/*
002 * (C) Copyright 2019 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 *
016 *  Contributors:
017 *      Kevin Leturc <kleturc@nuxeo.com>
018 */
019
020package org.nuxeo.mail;
021
022import java.util.Properties;
023
024import javax.mail.Authenticator;
025import javax.mail.PasswordAuthentication;
026
027/**
028 * @since 11.1
029 */
030public class MailAuthenticator extends Authenticator {
031
032    protected final Properties properties;
033
034    public MailAuthenticator(Properties properties) {
035        this.properties = properties;
036    }
037
038    @Override
039    protected PasswordAuthentication getPasswordAuthentication() {
040        String user = protocolValue("user");
041        if (user == null) {
042            return null;
043        }
044        String password = protocolValue("password");
045        if (password == null) {
046            return null;
047        }
048        return new PasswordAuthentication(user, password);
049    }
050
051    protected String protocolValue(String name) {
052        String key = String.format("mail.%s.%s", getRequestingProtocol(), name);
053        return properties.getProperty(key);
054    }
055
056}