1 26 27 package mailsb; 28 29 import java.rmi.RemoteException; 31 32 import javax.ejb.EJBException; 34 import javax.ejb.SessionBean; 35 import javax.ejb.SessionContext; 36 37 import javax.mail.Message; 38 import javax.mail.MessagingException; 39 import javax.mail.Session; 40 import javax.mail.Transport; 41 import javax.mail.internet.InternetAddress; 42 import javax.mail.internet.MimeMessage; 43 44 import javax.naming.InitialContext; 45 import javax.naming.NamingException; 46 47 55 public class SessionMailerBean implements SessionBean { 56 57 60 private String name = null; 61 62 66 private SessionContext sessionContext = null; 67 68 72 private Message message = null; 73 74 75 76 81 public void ejbCreate(String name) { 82 this.name = name; 83 } 84 85 86 87 103 public void setSessionContext(SessionContext sessionContext) throws EJBException, java.rmi.RemoteException { 104 this.sessionContext = sessionContext; 105 } 106 107 122 public void ejbRemove() throws EJBException, java.rmi.RemoteException { 123 } 125 126 141 public void ejbActivate() throws EJBException, java.rmi.RemoteException { 142 } 144 145 162 public void ejbPassivate() throws EJBException, java.rmi.RemoteException { 163 } 165 166 167 168 176 public void setMessage(String recipient, String subject, String content) throws Exception, RemoteException { 177 178 InitialContext ictx = null; 180 try { 181 ictx = new InitialContext(); 182 } catch (NamingException e) { 183 throw new Exception("Can not get an inital context : " + e.getMessage()); 184 } 185 186 Session session = null; 188 try { 189 session = (Session) ictx.lookup("java:comp/env/mail/MailSession"); 190 } catch (NamingException e) { 191 throw new Exception("You have not configure the mail factory with the name specified" 192 + " in the jonas-ejb-jar.xml file for java:comp/env/mail/MailSession ." 193 + " By default, the factory's name is mailSession_1 :" + e.getMessage()); 194 } 195 196 try { 197 message = new MimeMessage(session); 199 InternetAddress[] toRecipients = new InternetAddress[] {new InternetAddress(recipient)}; 200 205 message.setRecipients(Message.RecipientType.TO, toRecipients); 206 message.setSubject(subject); 207 message.setContent(content, "text/plain"); 208 } catch (MessagingException e) { 209 throw new Exception("A failure occurs when getting a message from the session and setting " 210 + "the different parameters :" + e.getMessage()); 211 } 212 213 } 214 215 220 public void send() throws Exception, RemoteException { 221 222 if (message == null) { 223 throw new Exception("The message can not be send because the method setMessage() " 224 + " was not called before the send() method."); 225 } 226 227 try { 228 Transport.send(message); 229 } catch (MessagingException e) { 230 throw new Exception("The message can not be send : " + e.getMessage()); 231 } 232 } 233 234 } | Popular Tags |