1 package xpetstore.services.mail.ejb; 2 3 import java.util.Date ; 4 5 import javax.activation.DataHandler ; 6 7 import javax.ejb.MessageDrivenBean ; 8 import javax.ejb.MessageDrivenContext ; 9 10 import javax.jms.Message ; 11 import javax.jms.MessageListener ; 12 import javax.jms.ObjectMessage ; 13 14 import javax.mail.Session ; 15 import javax.mail.Transport ; 16 import javax.mail.internet.InternetAddress ; 17 import javax.mail.internet.MimeMessage ; 18 19 import javax.naming.InitialContext ; 20 21 import xpetstore.services.mail.model.Email; 22 23 import xpetstore.util.Debug; 24 import xpetstore.util.JNDINames; 25 26 27 60 public class MailerMDB 61 implements MessageDrivenBean , 62 MessageListener 63 { 64 66 70 public void onMessage( Message recvMsg ) 71 { 72 try 73 { 74 Debug.print( "MailerMDB.onMessage(" + recvMsg + ")" ); 75 76 ObjectMessage msg = ( ObjectMessage ) recvMsg; 77 Email email = ( Email ) msg.getObject( ); 78 79 send( email.getTo( ), email.getSubject( ), email.getBody( ) ); 80 } 81 catch ( Exception e ) 82 { 83 Debug.print( "Unable to send the email", e ); 84 } 85 } 86 87 public void send( String to, 88 String subject, 89 String body ) 90 throws Exception 91 { 92 Debug.print( "MailerMDB.send(" + to + "," + subject + ",...)" ); 93 94 InitialContext ic = new InitialContext ( ); 95 Session session = ( Session ) ic.lookup( JNDINames.MAIL_SESSION ); 96 javax.mail.Message msg = new MimeMessage ( session ); 97 98 msg.setFrom( ); 99 msg.setRecipients( javax.mail.Message.RecipientType.TO, InternetAddress.parse( to, false ) ); 100 msg.setSubject( subject ); 101 102 msg.setDataHandler( new DataHandler ( body, "text/html" ) ); 103 msg.setHeader( "X-Mailer", "JavaMailer" ); 104 msg.setSentDate( new Date ( ) ); 105 106 Transport.send( msg ); 107 } 108 109 public void ejbCreate( ) {} 113 114 public void setMessageDrivenContext( MessageDrivenContext mdc ) {} 115 116 public void ejbRemove( ) {} 117 } 118 | Popular Tags |