package kz.cafe.utils;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.commons.logging.*;
import kz.cafe.constants.*;



public class Mailer{
   private static Log log = LogFactory.getLog(Mailer.class);

   private static final String LOG = "[MAIL] ";
   

   public static void sendMail(final String sFrom, final String sTo, final String sSubject, final String sMessage){
      
      Thread th = new Thread(){
         public void run(){
            log.debug(LOG + "from=" + sFrom + " to=" + sTo + " " + sSubject + " " + sMessage);
            
            // Get system properties
            Properties properties = new Properties();

            // Setup mail server
            properties.put("mail.smtp.host", ServerConstants.getEmailSmtpServer());
            properties.put("mail.user",      ServerConstants.getEmailSmtpUser());
            properties.put("mail.password",  ServerConstants.getEmailSmtpPassword());
            properties.put("mail.smtp.auth", "true");      

            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(properties, auth);      

            try{
               // Create a default MimeMessage object.
               MimeMessage message = new MimeMessage(session);

               // Set From: header field of the header.
               message.setFrom(new InternetAddress(sFrom));

               // Set To: header field of the header.
               message.addRecipient(Message.RecipientType.TO, new InternetAddress(sTo));

               // Set Subject: header field
               message.setSubject(sSubject);

               // Now set the actual message
               message.setText(sMessage);

               // Send message
               Transport.send(message);
            }
            catch (MessagingException mex){
               mex.printStackTrace();
            }
         }
      };
      
      th.start();
   }
   
   
   private static class SMTPAuthenticator extends javax.mail.Authenticator {
      public PasswordAuthentication getPasswordAuthentication() {
         String username = ServerConstants.getEmailSmtpUser();
         String password = ServerConstants.getEmailSmtpPassword();
         return new PasswordAuthentication(username, password);
      }
  }   
}
