001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (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 *     Alexandre Russel
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.mail.action;
023
024import javax.mail.Address;
025import javax.mail.Message;
026import javax.mail.MessagingException;
027import javax.mail.Session;
028import javax.mail.Transport;
029import javax.mail.internet.MimeMessage;
030
031import org.apache.commons.logging.Log;
032import org.apache.commons.logging.LogFactory;
033
034/**
035 * Action to answer the mail. It expects the text of the answer to be in the context under the "message" key.
036 *
037 * @author Alexandre Russel
038 */
039public class SendMailAction implements MessageAction {
040
041    private static final Log log = LogFactory.getLog(SendMailAction.class);
042
043    protected final Session session;
044
045    protected final String textMessage;
046
047    public SendMailAction(Session session, String textMessage) {
048        this.session = session;
049        this.textMessage = textMessage;
050    }
051
052    @Override
053    public boolean execute(ExecutionContext context) throws MessagingException {
054        Message message = context.getMessage();
055        if (log.isDebugEnabled()) {
056            log.debug("Sending mail because of message: " + message.getSubject());
057        }
058        Message sentMessage = new MimeMessage(session);
059        if (message.getReplyTo() == null || message.getReplyTo().length == 0) {
060            return true;
061        }
062        Address address = message.getReplyTo()[0];
063        sentMessage.setRecipient(Message.RecipientType.TO, address);
064        message.setText(textMessage);
065        Transport.send(sentMessage);
066        return true;
067    }
068
069    @Override
070    public void reset(ExecutionContext context) {
071        // do nothing
072    }
073
074}