PageRenderTime 227ms CodeModel.GetById 100ms app.highlight 77ms RepoModel.GetById 44ms app.codeStats 0ms

/src/mpv5/mail/SimpleMail.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 530 lines | 323 code | 60 blank | 147 comment | 26 complexity | 15a2e6ecb54a5d363271044ffb8d187b MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.mail;
 18
 19import com.sun.mail.smtp.SMTPSSLTransport;
 20import java.io.File;
 21import java.util.ArrayList;
 22import java.util.List;
 23import java.util.Properties;
 24
 25import javax.activation.DataHandler;
 26import javax.activation.DataSource;
 27import javax.activation.FileDataSource;
 28import javax.mail.Authenticator;
 29import javax.mail.Message;
 30import javax.mail.MessagingException;
 31import javax.mail.Multipart;
 32import javax.mail.NoSuchProviderException;
 33import javax.mail.PasswordAuthentication;
 34import javax.mail.Session;
 35import javax.mail.Transport;
 36import javax.mail.internet.InternetAddress;
 37import javax.mail.internet.MimeBodyPart;
 38import javax.mail.internet.MimeMessage;
 39import javax.mail.internet.MimeMultipart;
 40import mpv5.globals.Messages;
 41import mpv5.logging.Log;
 42import mpv5.ui.dialogs.Notificator;
 43import mpv5.ui.dialogs.Popup;
 44import mpv5.utils.export.Export;
 45import mpv5.utils.jobs.Waiter;
 46
 47/**
 48 * A simple mail implementation, taken from
 49 * http://www.tutorials.de/forum/java/255387-email-mit-javamail-versenden.html
 50 *
 51 */
 52public class SimpleMail implements Waiter {
 53
 54    private String smtpHost = "";
 55    private String username = "";
 56    private String password = "";
 57    private String senderAddress = "";
 58    private String recipientsAddress = "";
 59    private String subject = "";
 60    private String text = "";
 61    private String bccAddress = null;
 62    private List<String> cc = new ArrayList<String>();
 63    private List<String> bcc = new ArrayList<String>();
 64    private List<String> rec = new ArrayList<String>();
 65    private boolean useTls;
 66    private boolean useSmtps;
 67    private File attachment;
 68    private String ccAddress;
 69
 70    /**
 71     *
 72     * @param smtpHost
 73     * @param username
 74     * @param password
 75     * @param senderAddress
 76     * @param recipientsAddress
 77     * @param subject
 78     * @param text
 79     * @throws MessagingException
 80     */
 81    public SimpleMail(String smtpHost, String username, String password, String senderAddress, String recipientsAddress, String subject, String text) throws MessagingException {
 82        this.smtpHost = smtpHost;
 83        this.username = username;
 84        this.password = password;
 85        this.senderAddress = senderAddress;
 86        this.recipientsAddress = recipientsAddress;
 87        this.subject = subject;
 88        this.text = text;
 89    }
 90
 91    public SimpleMail() {
 92    }
 93
 94    /**
 95     * @author Sateesh Rudrangi
 96     * @param smtpHost
 97     * @param username
 98     * @param password
 99     * @param from
100     * @param recipientsAddress
101     * @param subject
102     * @param text
103     * @param attachment
104     * @throws MessagingException
105     */
106    private void sendMail() {
107        Runnable runnable = new Runnable() {
108
109            @Override
110            public void run() {
111
112                if (!useSmtps) {
113                    try {
114                        sendSmptmail();
115                    } catch (MessagingException ex) {
116                        Log.Debug(ex);
117                    }
118                } else {
119                    try {
120                        sendSmptsMail();
121                    } catch (NoSuchProviderException ex) {
122                        Log.Debug(ex);
123                    } catch (MessagingException ex) {
124                        Log.Debug(ex);
125                    }
126                }
127
128            }
129        };
130        new Thread(runnable).start();
131    }
132
133    @Override
134    public void set(Object object, Exception exception) throws Exception {
135        if (exception == null) {
136            try {
137                if (object instanceof Export) {
138                    setAttachment(((Export) object).getTargetFile());
139                    sendMail();
140                } else {
141                    setAttachment((File) object);
142                    sendMail();
143                }
144            } catch (Exception e) {
145                throw e;
146            } finally {
147            }
148        } else {
149            throw exception;
150        }
151    }
152
153    /**
154     * Set the configuration for mails
155     * @param c
156     * @throws UnsupportedOperationException
157     */
158    public void setMailConfiguration(MailConfiguration c) throws UnsupportedOperationException {
159        if (c != null) {
160            setPassword(c.getPassword());
161            setSenderAddress(c.getSenderAddress());
162            setSmtpHost(c.getSmtpHost());
163            setUsername(c.getUsername());
164            setUseTls(c.isUseTls());
165            setUseSmtps(c.isUseSmtps());
166        } else {
167            throw new UnsupportedOperationException("MailConfig cannot be null!");
168        }
169    }
170
171    /**
172     * @return the smtpHost
173     */
174    public String getSmtpHost() {
175        return smtpHost;
176    }
177
178    /**
179     * @param smtpHost the smtpHost to set
180     */
181    public void setSmtpHost(String smtpHost) {
182        this.smtpHost = smtpHost;
183    }
184
185    /**
186     * @return the username
187     */
188    public String getUsername() {
189        return username;
190    }
191
192    /**
193     * @param username the username to set
194     */
195    public void setUsername(String username) {
196        this.username = username;
197    }
198
199    /**
200     * @return the password
201     */
202    public String getPassword() {
203        return password;
204    }
205
206    /**
207     * @param password the password to set
208     */
209    public void setPassword(String password) {
210        this.password = password;
211    }
212
213    /**
214     * @return the senderAddress
215     */
216    public String getSenderAddress() {
217        return senderAddress;
218    }
219
220    /**
221     * @param senderAddress the senderAddress to set
222     */
223    public void setSenderAddress(String senderAddress) {
224        this.senderAddress = senderAddress;
225    }
226
227    /**
228     * @return the recipientsAddress
229     */
230    public String getRecipientsAddress() {
231        return recipientsAddress;
232    }
233
234    /**
235     * @param recipientsAddress the recipientsAddress to set
236     */
237    public void setRecipientsAddress(String recipientsAddress) {
238        this.recipientsAddress = recipientsAddress;
239        String[] ccs = recipientsAddress.split(";");
240        for (int i = 0; i < ccs.length; i++) {
241            String ccc = ccs[i];
242            addAddress(ccc);
243        }
244    }
245
246    /**
247     * @return the subject
248     */
249    public String getSubject() {
250        return subject;
251    }
252
253    /**
254     * @param subject the subject to set
255     */
256    public void setSubject(String subject) {
257        this.subject = subject;
258    }
259
260    /**
261     * @return the text
262     */
263    public String getText() {
264        return text;
265    }
266
267    /**
268     * @param text the text to set
269     */
270    public void setText(String text) {
271        this.text = text;
272    }
273
274    /**
275     * @return the attachment
276     */
277    public File getAttachment() {
278        return attachment;
279    }
280
281    /**
282     * @param attachment the attachment to set
283     */
284    public void setAttachment(File attachment) {
285        this.attachment = attachment;
286    }
287
288    /**
289     * @return the useTls
290     */
291    public boolean isUseTls() {
292        return useTls;
293    }
294
295    /**
296     * @param useTls the useTls to set
297     */
298    public void setUseTls(boolean useTls) {
299        this.useTls = useTls;
300    }
301
302    /**
303     * @return the useSmtps
304     */
305    public boolean isUseSmtps() {
306        return useSmtps;
307    }
308
309    /**
310     * @param useSmtps the useSmtps to set
311     */
312    public void setUseSmtps(boolean useSmtps) {
313        this.useSmtps = useSmtps;
314    }
315
316    private void sendSmptmail() throws MessagingException {
317        Log.Debug(this, "Sending mail via SMTP");
318        mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(true);
319        MailAuthenticator auth = new MailAuthenticator(username, password);
320
321        Properties properties = null;
322        Session session = null;
323        properties = new Properties();
324        properties.put("mail.smtp.host", smtpHost);
325        if (username != null) {
326            properties.put("mail.smtp.auth", "true");
327        }
328        if (useTls) {
329            properties.put("mail.smtp.starttls.enable", "true");
330        }
331
332        session = Session.getDefaultInstance(properties, auth);
333
334        // Define message
335        MimeMessage message = new MimeMessage(session);
336        message.setFrom(new InternetAddress(senderAddress));
337        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientsAddress));
338        if (getBccAddress() != null) {
339            message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bccAddress));
340        }
341        message.setSubject(subject);
342
343        // create the message part
344        MimeBodyPart messageBodyPart = new MimeBodyPart();
345
346        //fill message
347        messageBodyPart.setText(text);
348        Multipart multipart = new MimeMultipart();
349        multipart.addBodyPart(messageBodyPart);
350
351        if (attachment != null) {
352            // Part two is attachment
353            messageBodyPart = new MimeBodyPart();
354            DataSource source = new FileDataSource(attachment);
355            messageBodyPart.setDataHandler(new DataHandler(source));
356            messageBodyPart.setFileName(attachment.getName());
357            multipart.addBodyPart(messageBodyPart);
358        }
359
360        // Put parts in message
361        message.setContent(multipart);
362        try {
363            // Send the message
364            Transport.send(message);
365            mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(false);
366            Log.Debug(this, "Mail sent: " + message);
367            Popup.notice(Messages.MAIL_SENT + " " + recipientsAddress);
368        } catch (MessagingException messagingException) {
369            Popup.error(messagingException);
370            Log.Debug(this, messagingException.getLocalizedMessage());
371        } finally {
372// close the connection
373        }
374    }
375
376    /**
377     * From http://www.nepherte.be/send-mail-over-smtps-in-java/
378     * @throws NoSuchProviderException
379     * @throws MessagingException
380     */
381    private void sendSmptsMail() throws NoSuchProviderException, MessagingException {
382        mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(true);
383        Log.Debug(this, "Sending mail via SMTPS");
384        // create properties
385        Properties props = System.getProperties();
386        MailAuthenticator auth = new MailAuthenticator(username, password);
387
388        props.put("mail.smtps.auth", Boolean.toString(username != null));
389        props.put("mail.smtps.starttls.enable", Boolean.toString(useTls));
390// < -- it is important you use the correct port. smtp uses 25, smtps 465 -->
391        props.put("mail.smtps.port", "465");
392// < -- put the smtps server host address here -->
393        props.put("mail.smtps.host", smtpHost);
394
395//
396//        props.put("mail.smtp.port", "587");
397//        props.put("mail.smtp.auth", (username != null));
398//        props.put("mail.smtp.starttls.enable", useTls);
399
400// create session
401        Session session = Session.getDefaultInstance(props, auth);
402//        session.setDebug(true);
403
404        // Define message
405        MimeMessage message = new MimeMessage(session);
406        message.setFrom(new InternetAddress(senderAddress));
407        for (int i = 0; i < rec.size(); i++) {
408            String recc = rec.get(i);
409            try {
410                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recc));
411            } catch (MessagingException messagingException) {
412                Notificator.raiseNotification(messagingException);
413            }
414        }
415        for (int i = 0; i < bcc.size(); i++) {
416            String bbc = bcc.get(i);
417            try {
418                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bbc));
419            } catch (MessagingException messagingException) {
420                Notificator.raiseNotification(messagingException);
421            }
422        }
423        for (int i = 0; i < cc.size(); i++) {
424            String ccc = cc.get(i);
425            try {
426                message.addRecipient(Message.RecipientType.CC, new InternetAddress(ccc));
427            } catch (MessagingException messagingException) {
428                Notificator.raiseNotification(messagingException);
429            }
430        }
431        message.setSubject(subject);
432
433        // create the message part
434        MimeBodyPart messageBodyPart = new MimeBodyPart();
435
436        //fill message
437        messageBodyPart.setText(text);
438        Multipart multipart = new MimeMultipart();
439        multipart.addBodyPart(messageBodyPart);
440
441        if (attachment != null) {
442            // Part two is attachment
443            messageBodyPart = new MimeBodyPart();
444            DataSource source = new FileDataSource(attachment);
445            messageBodyPart.setDataHandler(new DataHandler(source));
446            messageBodyPart.setFileName(attachment.getName());
447            multipart.addBodyPart(messageBodyPart);
448        }
449
450        // Put parts in message
451        message.setContent(multipart);
452        message.saveChanges();
453// transport the message
454// < -- we will send the message over smtps -->
455        SMTPSSLTransport transport = (SMTPSSLTransport) session.getTransport("smtps");
456
457// connect to server
458        try {
459            // < -- fill in email address and password -->
460            transport.connect();
461// send the message
462            transport.sendMessage(message, message.getAllRecipients());
463            mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(false);
464            Log.Debug(this, "Mail sent: " + message);
465            Popup.notice(Messages.MAIL_SENT + " " + recipientsAddress);
466        } catch (MessagingException messagingException) {
467            Popup.error(messagingException);
468            Log.Debug(this, messagingException.getLocalizedMessage());
469        } finally {
470// close the connection
471            transport.close();
472        }
473    }
474
475    /**
476     * @return the bccAddress
477     */
478    public String getBccAddress() {
479        return bccAddress;
480    }
481
482    /**
483     * @param bccAddress the bccAddress to set
484     */
485    public void setBccAddress(String bccAddress) {
486        this.bccAddress = bccAddress;
487        String[] ccs = bccAddress.split(";");
488        for (int i = 0; i < ccs.length; i++) {
489            String ccc = ccs[i];
490            addBCCAddress(ccc);
491        }
492    }
493
494    public void addCCAddress(String ccc) {
495        cc.add(ccc);
496    }
497
498    public void setCCAddress(String cc) {
499        this.ccAddress = cc;
500        String[] ccs = cc.split(";");
501        for (int i = 0; i < ccs.length; i++) {
502            String ccc = ccs[i];
503            addCCAddress(ccc);
504        }
505    }
506
507    private void addAddress(String ccc) {
508        rec.add(ccc);
509    }
510
511    private void addBCCAddress(String ccc) {
512        bcc.add(ccc);
513    }
514
515    class MailAuthenticator extends Authenticator {
516
517        private final String user;
518        private final String password;
519
520        public MailAuthenticator(String user, String password) {
521            this.user = user;
522            this.password = password;
523        }
524
525        @Override
526        protected PasswordAuthentication getPasswordAuthentication() {
527            return new PasswordAuthentication(this.user, this.password);
528        }
529    }
530}