001/*
002 * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Alexandre Russel
016 *
017 * $Id$
018 */
019
020package org.nuxeo.ecm.platform.mail.action;
021
022import javax.mail.Address;
023import javax.mail.Message;
024import javax.mail.MessagingException;
025import javax.mail.Session;
026import javax.mail.Transport;
027import javax.mail.internet.MimeMessage;
028
029import org.apache.commons.logging.Log;
030import org.apache.commons.logging.LogFactory;
031
032/**
033 * Action to answer the mail. It expects the text of the answer to be in the context under the "message" key.
034 *
035 * @author Alexandre Russel
036 */
037public class SendMailAction implements MessageAction {
038
039    private static final Log log = LogFactory.getLog(SendMailAction.class);
040
041    protected final Session session;
042
043    protected final String textMessage;
044
045    public SendMailAction(Session session, String textMessage) {
046        this.session = session;
047        this.textMessage = textMessage;
048    }
049
050    public boolean execute(ExecutionContext context) throws MessagingException {
051        Message message = context.getMessage();
052        if (log.isDebugEnabled()) {
053            log.debug("Sending mail because of message: " + message.getSubject());
054        }
055        Message sentMessage = new MimeMessage(session);
056        if (message.getReplyTo() == null || message.getReplyTo().length == 0) {
057            return true;
058        }
059        Address address = message.getReplyTo()[0];
060        sentMessage.setRecipient(Message.RecipientType.TO, address);
061        message.setText(textMessage);
062        Transport.send(sentMessage);
063        return true;
064    }
065
066    public void reset(ExecutionContext context) {
067        // do nothing
068    }
069
070}