1 39 40 package demo; 41 42 import java.util.*; 43 import java.net.*; 44 import javax.mail.*; 45 import javax.mail.internet.*; 46 import javax.servlet.jsp.*; 47 import javax.servlet.jsp.tagext.*; 48 49 52 public class SendTag extends BodyTagSupport { 53 private String body; 54 private String cc; 55 private String host; 56 private String recipients; 57 private String sender; 58 private String subject; 59 60 63 public void setHost(String host) { 64 this.host = host; 65 } 66 67 70 public void setRecipients(String recipients) { 71 this.recipients = recipients; 72 } 73 74 77 public void setSender(String sender) { 78 this.sender = sender; 79 } 80 81 84 public void setCc(String cc) { 85 this.cc = cc; 86 } 87 88 91 public void setSubject(String subject) { 92 this.subject = subject; 93 } 94 95 98 public int doEndTag() throws JspException { 99 Properties props = System.getProperties(); 100 101 try { 102 if (host != null) 103 props.put("mail.smtp.host", host); 104 else if (props.getProperty("mail.smtp.host") == null) 105 props.put("mail.smtp.host", InetAddress.getLocalHost(). 106 getHostName()); 107 } catch (Exception ex) { 108 throw new JspException(ex.getMessage()); 109 } 110 Session session = Session.getDefaultInstance(props, null); 111 112 Message msg = new MimeMessage(session); 113 InternetAddress[] toAddrs = null, ccAddrs = null; 114 115 try { 116 if (recipients != null) { 117 toAddrs = InternetAddress.parse(recipients, false); 118 msg.setRecipients(Message.RecipientType.TO, toAddrs); 119 } else 120 throw new JspException("No recipient address specified"); 121 122 if (sender != null) 123 msg.setFrom(new InternetAddress(sender)); 124 else 125 throw new JspException("No sender address specified"); 126 127 if (cc != null) { 128 ccAddrs = InternetAddress.parse(cc, false); 129 msg.setRecipients(Message.RecipientType.CC, ccAddrs); 130 } 131 132 if (subject != null) 133 msg.setSubject(subject); 134 135 if ((body = getBodyContent().getString()) != null) 136 msg.setText(body); 137 else 138 msg.setText(""); 139 140 Transport.send(msg); 141 142 } catch (Exception ex) { 143 throw new JspException(ex.getMessage()); 144 } 145 146 return(EVAL_PAGE); 147 } 148 } 149 150 | Popular Tags |