1 package org.springframework.samples.jpetstore.domain.logic; 2 3 import java.lang.reflect.Method ; 4 5 import org.apache.commons.logging.Log; 6 import org.apache.commons.logging.LogFactory; 7 8 import org.springframework.aop.AfterReturningAdvice; 9 import org.springframework.beans.factory.InitializingBean; 10 import org.springframework.mail.MailException; 11 import org.springframework.mail.MailSender; 12 import org.springframework.mail.SimpleMailMessage; 13 import org.springframework.samples.jpetstore.domain.Account; 14 import org.springframework.samples.jpetstore.domain.Order; 15 16 20 public class SendOrderConfirmationEmailAdvice implements AfterReturningAdvice, InitializingBean { 21 22 private static final String DEFAULT_MAIL_FROM = "jpetstore@springframework.org"; 23 24 private static final String DEFAULT_SUBJECT = "Thank you for your order!"; 25 26 private final Log logger = LogFactory.getLog(getClass()); 27 28 private MailSender mailSender; 29 30 private String mailFrom = DEFAULT_MAIL_FROM; 31 32 private String subject = DEFAULT_SUBJECT; 33 34 public void setMailSender(MailSender mailSender) { 35 this.mailSender = mailSender; 36 } 37 38 public void setMailFrom(String mailFrom) { 39 this.mailFrom = mailFrom; 40 } 41 42 public void setSubject(String subject) { 43 this.subject = subject; 44 } 45 46 public void afterPropertiesSet() throws Exception { 47 if (this.mailSender == null) { 48 throw new IllegalStateException ("mailSender is required"); 49 } 50 } 51 52 public void afterReturning(Object returnValue, Method m, Object [] args, Object target) throws Throwable { 53 Order order = (Order) args[0]; 54 Account account = ((PetStoreFacade) target).getAccount(order.getUsername()); 55 56 if (account.getEmail() == null || account.getEmail().length() == 0) { 58 return; 59 } 60 61 StringBuffer text = new StringBuffer (); 62 text.append("Dear ").append(account.getFirstName()).append(' ').append(account.getLastName()); 63 text.append(", thank your for your order from JPetStore. Please note that your order number is "); 64 text.append(order.getOrderId()); 65 66 SimpleMailMessage mailMessage = new SimpleMailMessage(); 67 mailMessage.setTo(account.getEmail()); 68 mailMessage.setFrom(this.mailFrom); 69 mailMessage.setSubject(this.subject); 70 mailMessage.setText(text.toString()); 71 try { 72 this.mailSender.send(mailMessage); 73 } 74 catch (MailException ex) { 75 logger.warn("An exception occured when trying to send email", ex); 77 } 78 } 79 80 } 81 | Popular Tags |