1 34 package net.myvietnam.mvncore.util; 35 36 import java.io.UnsupportedEncodingException ; 37 import java.util.*; 38 39 import javax.mail.*; 40 import javax.mail.internet.*; 41 import javax.naming.InitialContext ; 42 import javax.naming.NamingException ; 43 44 import net.myvietnam.mvncore.MVNCoreConfig; 45 import net.myvietnam.mvncore.exception.BadInputException; 46 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter; 47 import org.apache.commons.logging.Log; 48 import org.apache.commons.logging.LogFactory; 49 50 public final class MailUtil { 51 52 public static final int MAX_MESSAGES_PER_TRANSPORT = 100; 53 54 private static Log log = LogFactory.getLog(MailUtil.class); 55 56 private MailUtil() { } 58 59 61 66 public static String getEmailUsername(String email) { 67 if (email == null) return ""; 68 int atIndex = email.indexOf('@'); 69 if (atIndex == -1) { 70 return ""; 71 } 72 return email.substring(0, atIndex); 73 } 74 75 80 public static String getEmailDomain(String email) { 81 if (email == null) return ""; 82 int atIndex = email.indexOf('@'); 83 if (atIndex == -1) { 84 return ""; 85 } 86 return email.substring(atIndex + 1); 87 } 88 89 95 public static void checkGoodEmail(String input) throws BadInputException { 96 if (input == null) throw new BadInputException("Sorry, null string is not a good email."); int atIndex = input.indexOf('@'); 98 int dotIndex = input.lastIndexOf('.'); 99 if ((atIndex == -1) || (dotIndex == -1) || (atIndex >= dotIndex)) { 100 throw new BadInputException("Error: '" + DisableHtmlTagFilter.filter(input) + "' is not a valid email value. Please try again."); 102 } 103 104 int length = input.length(); 106 char c = 0; 107 108 for (int i = 0; i < length; i++) { 109 c = input.charAt(i); 110 if ((c >= 'a') && (c <= 'z')) { 111 } else if ((c >= 'A') && (c <= 'Z')) { 113 } else if ((c >= '0') && (c <= '9')) { 115 120 } else if ( ( (c=='_') || (c=='-') || (c=='.') || (c=='@') ) && (i != 0) ) { 122 } else { 124 throw new BadInputException(input + " is not a valid email. Reason: character '" + c + "' is not accepted in an email."); 127 } 128 } 130 try { 132 new javax.mail.internet.InternetAddress (input); 133 } catch (Exception ex) { 134 log.error("Error when running checkGoodEmail", ex); 135 throw new BadInputException("Assertion: dont want to occur in Util.checkGoodEmail"); 136 } 137 } 138 139 151 public static void sendMail(String from, String to, String cc, String bcc, String subject, String message) 152 throws MessagingException, BadInputException, UnsupportedEncodingException { 153 154 MailMessageStruct mailItem = new MailMessageStruct(); 155 mailItem.setFrom(from); 156 mailItem.setTo(to); 157 mailItem.setCc(cc); 158 mailItem.setBcc(bcc); 159 mailItem.setSubject(subject); 160 mailItem.setMessage(message); 161 162 sendMail(mailItem); 163 } 164 165 public static void sendMail(MailMessageStruct mailItem) 166 throws MessagingException, BadInputException, UnsupportedEncodingException { 167 168 ArrayList mailList = new ArrayList(1); 169 mailList.add(mailItem); 170 try { 171 sendMail(mailList); 172 } catch (MessagingException mex) { 173 log.error("MessagingException has occured.", mex); 174 log.debug("MessagingException has occured. Detail info:"); 175 log.debug("from = " + mailItem.getFrom()); 176 log.debug("to = " + mailItem.getTo()); 177 log.debug("cc = " + mailItem.getCc()); 178 log.debug("bcc = " + mailItem.getBcc()); 179 log.debug("subject = " + mailItem.getSubject()); 180 log.debug("message = " + mailItem.getMessage()); 181 throw mex; } 183 } 184 185 public static void sendMail(Collection mailStructCollection) 186 throws MessagingException, BadInputException, UnsupportedEncodingException { 187 188 Session session = null; 189 Transport transport = null; 190 int totalEmails = mailStructCollection.size(); 191 int count = 0; 192 int sendFailedExceptionCount = 0; 193 194 String server = ""; 195 String userName = ""; 196 String password = ""; 197 int port = 25; 198 199 boolean useMailsource = MVNCoreConfig.isUseMailSource(); 200 201 try { 202 for (Iterator iter = mailStructCollection.iterator(); iter.hasNext(); ) { 203 count++; 204 205 if ((transport == null) || (session == null)) { 206 if (useMailsource) { 207 try { 208 InitialContext ic = new InitialContext (); 209 String mailSourceName = MVNCoreConfig.getMailSourceName(); 211 log.debug("MailUtil : use mailsource = " + mailSourceName); 212 session = (Session) ic.lookup("java:comp/env/" + mailSourceName); 213 transport = session.getTransport("smtp"); 214 } catch (NamingException e) { 215 log.error("Cannot get Mail session", e); 216 throw new MessagingException("Cannot get the mail session from JNDI. Send mail failed."); 217 } 218 } else { Properties props = new Properties(); 220 221 server = MVNCoreConfig.getMailServer(); 222 port = MVNCoreConfig.getMailServerPort(); 223 userName = MVNCoreConfig.getMailUserName(); 224 password = MVNCoreConfig.getMailPassword(); 225 226 props.put("mail.smtp.host", server); 227 props.put("mail.smtp.port", String.valueOf(port)); 228 if ((userName != null) && (userName.length() > 0)) { 229 props.put("mail.smtp.auth", "true"); 230 } 231 session = Session.getDefaultInstance(props, null); 233 transport = session.getTransport("smtp"); 234 } 236 if ((userName != null) && (userName.length() > 0)) { 237 transport.connect(server, userName, password); 238 } else { 239 transport.connect(); 240 } 241 } 242 243 MailMessageStruct mailItem = (MailMessageStruct)iter.next(); 244 245 String from = mailItem.getFrom(); 246 String to = mailItem.getTo(); 247 String cc = mailItem.getCc(); 248 String bcc = mailItem.getBcc(); 249 String subject = mailItem.getSubject(); 250 String message = mailItem.getMessage(); 251 252 if (from == null) from = MVNCoreConfig.getDefaultMailFrom(); 254 255 try { 256 checkGoodEmail(from); 258 InternetAddress fromAddress = new InternetAddress(from); 259 InternetAddress[] toAddress = getInternetAddressEmails(to); 260 InternetAddress[] ccAddress = getInternetAddressEmails(cc); 261 InternetAddress[] bccAddress = getInternetAddressEmails(bcc); 262 if ((toAddress == null) && (ccAddress == null) && (bccAddress == null)) { 263 throw new BadInputException("Cannot send mail since all To, Cc, Bcc addresses are empty."); 265 } 266 267 MimeMessage msg = new MimeMessage(session); 269 msg.setSentDate(new Date()); 270 msg.setFrom(fromAddress); 271 272 if (toAddress != null) { 273 msg.setRecipients(Message.RecipientType.TO, toAddress); 274 } 275 if (ccAddress != null) { 276 msg.setRecipients(Message.RecipientType.CC, ccAddress); 277 } 278 if (bccAddress != null) { 279 msg.setRecipients(Message.RecipientType.BCC, bccAddress); 280 } 281 msg.setSubject(subject, "UTF-8"); 286 msg.setText(message, "UTF-8"); 287 288 298 msg.saveChanges(); 299 300 transport.sendMessage(msg, msg.getAllRecipients()); 301 302 if ((count % MAX_MESSAGES_PER_TRANSPORT) == 0) { 304 try { 305 if (transport != null) transport.close(); 306 } catch (MessagingException ex) {} 307 transport = null; 308 session = null; 309 } 310 311 } catch (SendFailedException ex) { 312 sendFailedExceptionCount++; 313 log.error("SendFailedException has occured.", ex); 314 log.warn("SendFailedException has occured. Detail info:"); 315 log.warn("from = " + from); 316 log.warn("to = " + to); 317 log.warn("cc = " + cc); 318 log.warn("bcc = " + bcc); 319 log.warn("subject = " + subject); 320 log.info("message = " + message); 321 if ((totalEmails != 1) && (sendFailedExceptionCount > 10)) { 322 throw ex; } 324 } catch (MessagingException mex) { 325 log.error("MessagingException has occured.", mex); 326 log.warn("MessagingException has occured. Detail info:"); 327 log.warn("from = " + from); 328 log.warn("to = " + to); 329 log.warn("cc = " + cc); 330 log.warn("bcc = " + bcc); 331 log.warn("subject = " + subject); 332 log.info("message = " + message); 333 throw mex; } 335 } } finally { 337 try { 338 if (transport != null) transport.close(); 339 } catch (MessagingException ex) { } 340 if (totalEmails != 1) { 341 log.info("sendMail: totalEmails = " + totalEmails + " sent count = " + count); 342 } 343 } 344 } 345 346 351 public static String [] getEmails(String email) throws BadInputException { 352 if (email == null) email = ""; 353 email = email.trim(); email = email.replace(',', ';'); StringTokenizer t = new StringTokenizer(email, ";"); 356 String [] ret = new String [t.countTokens()]; 357 int index = 0; 358 while(t.hasMoreTokens()) { 359 String mail = t.nextToken().trim(); 360 checkGoodEmail(mail); 361 ret[index] = mail; 362 index++; 364 } 365 return ret; 366 } 367 368 public static String [] getEmails(String to, String cc, String bcc) throws BadInputException { 369 String [] toMail = getEmails(to); 370 String [] ccMail = getEmails(cc); 371 String [] bccMail= getEmails(bcc); 372 String [] ret = new String [toMail.length + ccMail.length + bccMail.length]; 373 int index = 0; 374 for (int i = 0; i < toMail.length; i++) { 375 ret[index] = toMail[i]; 376 index++; 377 } 378 for (int i = 0; i < ccMail.length; i++) { 379 ret[index] = ccMail[i]; 380 index++; 381 } 382 for (int i = 0; i < bccMail.length; i++) { 383 ret[index] = bccMail[i]; 384 index++; 385 } 386 return ret; 387 } 388 389 397 private static InternetAddress[] getInternetAddressEmails(String email) 398 throws BadInputException, AddressException { 399 String [] mails = getEmails(email); 400 if (mails.length == 0) return null; 402 InternetAddress[] address = new InternetAddress[mails.length]; 404 for (int i = 0; i < mails.length; i++) { 405 address[i] = new InternetAddress(mails[i]); 406 } 408 return address; 409 } 410 411 } 412 | Popular Tags |