001    package org.hackystat.sensorbase.mailer;
002    
003    import java.util.Date;
004    import java.util.Properties;
005    import java.util.logging.LogManager;
006    import java.util.logging.Logger;
007    
008    import javax.mail.Message;
009    import javax.mail.MessagingException;
010    import javax.mail.Session;
011    import javax.mail.Transport;
012    import javax.mail.internet.InternetAddress;
013    import javax.mail.internet.MimeMessage;
014    
015    import static org.hackystat.sensorbase.server.ServerProperties.SMTP_HOST_KEY;
016    import static org.hackystat.sensorbase.server.ServerProperties.ADMIN_EMAIL_KEY;
017    import static org.hackystat.sensorbase.server.ServerProperties.SMTP_SERVER_USER;
018    import static org.hackystat.sensorbase.server.ServerProperties.TEST_INSTALL_KEY;
019    import static org.hackystat.sensorbase.server.ServerProperties.TEST_DOMAIN_KEY;
020    
021    /**
022     * Provides a wrapper for SensorBase email services. Use the singleton instance
023     * to send emails: Mailer.getInstance().send(). To aid in testing, no emails are
024     * sent if the Hackystat server is a test installation, or the user email is in
025     * hackystat test domain.
026     * 
027     * @author Philip M. Johnson
028     */
029    public class Mailer {
030    
031        /** Administrator's email. */
032        private String adminEmail;
033    
034        /**
035         * If this SensorBase exists purely for testing, should be 'true' or
036         * 'false'.
037         */
038        private String testInstall;
039    
040        /** The domain for test users, such as "hackystat.org". */
041        private String testDomain;
042    
043        /** Session object. */
044        private Session session;
045    
046        /** Mailer object. */
047        private static Mailer mailer;
048    
049        /** The singleton instance maintaining an Email session. */
050        private Mailer() {
051            Properties props = new Properties();
052            props.put("mail.smtp.host", System.getProperty(SMTP_HOST_KEY));
053    
054            /* If a username / password combination is defined for the smtp server,
055             * let's create the authenticator object
056             */
057            String smtpServerUser =  System.getProperty(SMTP_SERVER_USER);
058            if (smtpServerUser == null
059                    || "".equals(smtpServerUser)) {
060                props.put("mail.smtp.auth", "false");
061                this.session = Session.getInstance(props);
062            } 
063            else {
064                // set the corresponding property to TRUE, otherwise, authentication
065                // is not used
066                props.put("mail.smtp.auth", "true");
067                
068                // quem estiver utilizando um 
069                //SERVIDOR PROXY descomente 
070                //essa parte e atribua as propriedades 
071                //do SERVIDOR PROXY utilizado   
072                      
073                    props.setProperty("proxySet","true");  
074                    props.setProperty("socksProxyHost","proxy.pucpr.br"); // IP do Servidor Proxy  
075                    props.setProperty("socksProxyPort","3128");  // Porta do servidor Proxy  
076                      
077      
078            props.put("mail.transport.protocol", "smtp"); //define protocolo de envio como SMTP   
079            props.put("mail.smtp.starttls.enable","true");   
080            props.put("mail.smtp.host", System.getProperty(SMTP_HOST_KEY)); //server SMTP do GMAIL   
081            //props.put
082            //("mail.smtp.auth", "true");
083            //ativa autenticacao 
084            //usuario ou seja, a conta que esta 
085            //enviando o email (tem que ser do GMAIL)  
086            props.put("mail.smtp.user", System.getProperty(SMTP_SERVER_USER));    
087            props.put("mail.debug", "true");   
088            props.put("mail.smtp.port", "465"); //porta para enviar emails do gmail (465)  
089            props.put("mail.smtp.socketFactory.port", "465"); //mesma porta para o socket   
090            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");   
091            props.put("mail.smtp.socketFactory.fallback", "false");
092                
093                
094                
095                SmtpAuthenticator smtpAuthenticator = new SmtpAuthenticator();
096                this.session = Session.getInstance(props, smtpAuthenticator);
097            }
098            this.adminEmail = "Projeto MODUS-SD <"
099                    + System.getProperty(ADMIN_EMAIL_KEY) + ">";
100            this.testInstall = System.getProperty(TEST_INSTALL_KEY).toLowerCase();
101            this.testDomain = System.getProperty(TEST_DOMAIN_KEY);
102        }
103    
104        /**
105         * Returns the singleton instance of Mailer, creating it if necesssary.
106         * 
107         * @return The singleton Mailer instance.
108         */
109        public static Mailer getInstance() {
110            if (mailer == null) {
111                Mailer.mailer = new Mailer();
112            }
113            return Mailer.mailer;
114        }
115    
116        /**
117         * Attempts to send an email. To aid in testing, no emails are sent if the
118         * Hackystat server is a test installation, or the user email is in
119         * hackystat test domain. Returns false if the send fails.
120         * 
121         * @param fromAddr
122         *            The email address from
123         * @param toAddr
124         *            The email address to send to.
125         * @param subject
126         *            The subject of the email.
127         * @param body
128         *            The email body.
129         * @return True if no error occurred during send, false otherwise
130         */
131        public boolean send(String fromAddr, String toAddr, String subject,
132                String body) {
133            if (this.testInstall.equals("true") || toAddr.endsWith(this.testDomain)) {
134                return true;
135            }
136            try {
137                Message msg = new MimeMessage(this.session);
138                InternetAddress adminAddress = new InternetAddress(fromAddr);
139                InternetAddress[] adminAddressArray = { adminAddress };
140                InternetAddress userAddress = new InternetAddress(toAddr);
141    
142                msg.setFrom(adminAddress);
143                msg.setReplyTo(adminAddressArray);
144                msg.setRecipient(Message.RecipientType.TO, userAddress);
145                msg.setSubject(subject);
146                msg.setSentDate(new Date());
147                msg.setText(body);
148    
149                
150                //Objeto encarregado de enviar os dados para o email   
151            Transport tr;   
152            try {   
153                tr = session.getTransport("smtp"); //define smtp para transporte   
154                /*  
155                 *  1 - define o servidor smtp  
156                 *  2 - seu nome de usuario do gmail  
157                 *  3 - sua senha do gmail  
158                 */   
159                tr.connect("smtp.gmail.com", "modussdproj@gmail.com", "projeto01");   
160                msg.saveChanges(); 
161                //envio da mensagem   
162                tr.sendMessage(msg, msg.getAllRecipients());   
163                tr.close(); 
164            }
165    catch (Exception e) {
166    // TODO Auto-generated catch block   
167                System.out.println(">> Erro: Envio Mensagem");   
168                e.printStackTrace();   
169            } 
170                //Transport.send(msg);
171                return true;
172            }
173            catch (MessagingException mex) {
174                Logger logger = LogManager.getLogManager().getLogger(
175                        "org.hackystat.sensorbase");
176                logger.warning("Mail failure to: " + toAddr + "\n" + mex);
177                return false;
178            }
179    
180        }
181    
182        /**
183         * Attempts to send an email. To aid in testing, no emails are sent if the
184         * Hackystat server is a test installation, or the user email is in
185         * hackystat test domain. Returns false if the send fails.
186         * 
187         * @param toAddr
188         *            The email address to send to.
189         * @param subject
190         *            The subject of the email.
191         * @param body
192         *            The email body.
193         * @return True if no error occurred during send, false otherwise
194         */
195        public boolean send(String toAddr, String subject, String body) {
196            return this.send(this.adminEmail, toAddr, subject, body);
197        }
198    }