1 package org.paneris.jammyjoes.mail; 2 3 import java.io.IOException; 4 import java.io.Writer; 5 import java.util.Enumeration; 6 import java.util.Properties; 7 8 import javax.mail.MessagingException; 9 import javax.mail.Session; 10 11 import org.paneris.jammyjoes.model.User; 12 13 import com.quiotix.html.parser.ParseException; 14 import com.sun.mail.smtp.SMTPTransport; 15 16 public class MailFascade implements Sender { 17 18 19 private Session session; 20 private MailTransport transport; 21 private Properties props = new Properties(); 22 23 24 public MailFascade(Session session, MailTransport transport) { 25 this.session = session; 26 this.transport = transport; 27 } 28 29 public MailFascade(String smtpServer) { 30 props.put("mail.smtp.host", smtpServer); 31 this.session = makeSession(); 32 this.transport = new TransportAbapter(new SMTPTransport(session, null)); 33 } 34 35 public void send(MimeMail mail) throws MessagingException, ParseException, IOException { 36 transport.send(mail); 37 } 38 39 public Newsletter createNewsletter(String directory, String name) throws Exception { 40 return new Newsletter(session, directory, name); 41 } 42 43 public HtmlMail createHtmlMail(String content) throws Exception { 44 return new HtmlMail(session, content); 45 } 46 47 private Session makeSession() { 48 Session session = Session.getDefaultInstance(props); 49 return session; 50 } 51 52 public String getProperty(String name) { 53 return props.getProperty(name); 54 } 55 56 public int mailPeople(Enumeration users, Writer out, Newsletter newsletter) throws IOException { 57 int count=0; 58 while (users.hasMoreElements()) { 59 User user = (User) users.nextElement(); 60 if (sendToUser(out, user, newsletter)) { 61 count++; 62 } 63 out.flush(); 64 } 65 return count; 66 } 67 68 private boolean sendToUser(Writer out, User user, Newsletter newsletter) throws IOException { 69 if (user.getSpam().booleanValue()) { 70 String address = user.getEmail(); 71 out.write(user.getId() + " " + address); 72 out.flush(); 73 try { 74 newsletter.setRecipient(address); 75 send(newsletter); 76 out.write("....Sent<br>\n"); 77 return true; 78 } catch (Exception e) { 79 out.write("....Failed: " + e + "<br>\n"); 80 return false; 81 } 82 } 83 return false; 84 } 85 86 87 }