1 package net.jaekl.cfb.analyze;
3 import java.io.PrintWriter;
4 import java.io.StringWriter;
5 import java.util.ArrayList;
6 import java.util.Properties;
8 import javax.mail.Message.RecipientType;
9 import javax.mail.MessagingException;
10 import javax.mail.Session;
11 import javax.mail.Transport;
12 import javax.mail.internet.InternetAddress;
13 import javax.mail.internet.MimeMessage;
15 import net.jaekl.cfb.CfbBundle;
16 import net.jaekl.cfb.Config;
18 public class Notifier {
19 private static final String MAIL_SMTP_HOST = "mail.smtp.host";
20 private static final String TEXT_HTML = "text/html";
25 public Notifier(CfbBundle bundle, Config config) {
30 public void sendEmailIfNeeded(PrintWriter pw, HtmlReport report) {
31 Delta delta = report.getDelta();
32 if ((delta.getNumNew() > 0) || (delta.getNumFixed() > 0)) {
33 sendEmail(pw, report);
37 void sendEmail(PrintWriter pw, HtmlReport report) {
38 Properties props = System.getProperties();
39 props.setProperty(MAIL_SMTP_HOST, m_config.getMailSmtpHost());
40 Session sess = Session.getDefaultInstance(props);
42 ArrayList<String> recipients = m_config.getNotify();
43 if (recipients.size() < 1) {
47 PrintWriter mailWriter = null;
50 MimeMessage msg = new MimeMessage(sess);
52 String earlier = report.getDelta().getEarlier().constructVersionText(m_bundle);
53 String later = report.getDelta().getLater().constructVersionText(m_bundle);
55 msg.setFrom(new InternetAddress(m_config.getMailFrom()));
56 msg.setSubject(m_bundle.get(CfbBundle.CFB_MAIL_SUBJECT, earlier, later));
58 for (String recipient : recipients) {
59 msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
62 StringWriter sw = new StringWriter();
63 mailWriter = new PrintWriter(sw);
64 report.write(mailWriter);
67 msg.setContent(sw.toString(), TEXT_HTML);
70 catch (MessagingException exc) {
71 StringBuilder toList = new StringBuilder();
72 for (String recipient : recipients) {
73 if (toList.length() > 0) {
76 toList.append(recipient);
78 pw.println(m_bundle.get(CfbBundle.CANNOT_SEND_MAIL, toList.toString(), exc.toString()));
79 exc.printStackTrace(pw);
82 if (null != mailWriter) {