All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.googlecode.jpattern.service.mail.MailSender Maven / Gradle / Ivy

package com.googlecode.jpattern.service.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 * @author Claudio Quaresima - [email protected] - 01/set/09 20:30:57
 * @version $Id$
 */
public class MailSender implements IMailSender{

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Properties _serverproperties;

    private MailRecipients _recipients;

	private MailSenderAuthenticator authenticator;

    public MailSender(IMailConfig aMailConfig) {

        _serverproperties = new Properties();
        _serverproperties.put("mail.smtp.host", aMailConfig.getStmphost());
        _serverproperties.put("mail.smtp.port", aMailConfig.getStmpport());
        
        if (aMailConfig.isRequiredAuthentication()) {
        	authenticator = new MailSenderAuthenticator(aMailConfig.getUsername(), aMailConfig.getPassword());
			_serverproperties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        	_serverproperties.setProperty("mail.smtp.auth", "true");
        }
    }

    public void recipients(MailRecipients aRecipients) {
        _recipients = aRecipients;

    }

    public boolean send(TransportMailMessage aMessage) {
        try {
            
        	Session session = Session.getInstance(_serverproperties, authenticator);
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setSubject(aMessage.subject().content());
            mimeMessage.setSentDate(new Date());
            
            MailMessageAddress mailMessageAddress = new MailMessageAddress(mimeMessage);
            _recipients.writeOnMessage(mailMessageAddress);
          
            if (!mailMessageAddress.valid()) {
                return false;
            }
            mimeMessage.setContent(aMessage.asMultipart());
          
            Transport.send(mimeMessage);
          
            return true;            
        }
        catch (Exception e) {
        	e.printStackTrace();
        	return false;
        }

        
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy