Tutorial :Design: Emailing System in Java


I'm building an emailing system for a framework I'm developing. Thus far, I've got a generic MailMessage interface that every different type of email message will implement, something along the lines of

public interface MailMessage {      public String[] getTo();      public void setTo(String[] to);      public String getFrom();      public void setFrom(String from);      ...      // you can guess the setters/getters here      ...  }  

I've then got a SimpleMailMessage that's exactly what you would expect as a simple implementation of the interface (no encryption or encoding, just plain text).

I've created an MailMessageFactory interface that's used as an abstract factory. I've got a SimpleMailMessageFactory that implements the factory to produce instances of SimpleMailMessage.

One type of email I'd like to the framework to send is an Alert mail message, that is essentially a regular mail message except with "[Alert]" prefixed to the subject line (Another might be a email containing a "list" of order items, but I'm not sure of where the responsibility falls for converting the list to a String for an email lies). I can either subclass the SimpleMailMessage and override the setSubject(String subject) method to something like

public class AlertMailMessage {      ...      public void setSuject(String subject) {          this.to = "[Alert]" + to;      }      ...  }  

Or I can create a decorator:

public abstract class EmailDecorator implements MailMessage {      protected MailMessage email;      ...      // delegate all implemented methods to email      ...  }    public class AlertEmailDecorator extends EmailDecorator {      public void setSubject(String subject) {          email.setSubject("[Alert]" + subject);      }  }  

Or I can just delegate adding the "[Alert]" string in the SimpleMailMessageFactory.

Thoughts on what I have? I think the problem is that I might be too thoughtful and forward-thinking, but I want the perfect design.


A decorator seems a better option to me. I am thinking of, may be you need to append your subject line with, Fwd: or Re: as well, or may be you need to support signature where you will be adding a signature to the email body.


The decorator seems like the better option. However, why are you writing your own email framework for Java? Why not just use the JavaMail API?


Sounds just like the Spring's support for JavaMail. Don't reinvent the wheel, use already existing, proven solutions, and build on top of that.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »