1 25 package org.ofbiz.content.email; 26 27 import java.io.ByteArrayInputStream ; 28 import java.io.ByteArrayOutputStream ; 29 import java.io.IOException ; 30 import java.io.InputStream ; 31 import java.io.OutputStream ; 32 import java.io.StringWriter ; 33 import java.io.Writer ; 34 import java.net.MalformedURLException ; 35 import java.net.URL ; 36 import java.util.Iterator ; 37 import java.util.List ; 38 import java.util.ArrayList ; 39 import java.util.Locale ; 40 import java.util.Map ; 41 import java.util.HashMap ; 42 import java.util.Properties ; 43 import java.sql.Timestamp ; 44 import java.util.Date ; 45 import java.util.Calendar ; 46 47 import javax.activation.DataHandler ; 48 import javax.activation.DataSource ; 49 import javax.mail.Message ; 50 import javax.mail.Address ; 51 import javax.mail.Session ; 52 import javax.mail.Transport ; 53 import javax.mail.internet.InternetAddress ; 54 import javax.mail.internet.MimeBodyPart ; 55 import javax.mail.internet.MimeMessage ; 56 import javax.mail.internet.MimeMultipart ; 57 import javax.xml.parsers.ParserConfigurationException ; 58 import javax.mail.MessagingException ; 59 import javax.mail.Multipart ; 60 import javax.mail.Part ; 61 62 import javolution.util.FastList; 63 import javolution.util.FastMap; 64 65 import org.apache.avalon.framework.logger.Log4JLogger; 66 import org.apache.avalon.framework.logger.Logger; 67 import org.apache.fop.apps.Driver; 68 import org.apache.fop.apps.FOPException; 69 import org.apache.fop.image.FopImageFactory; 70 import org.apache.fop.messaging.MessageHandler; 71 import org.apache.fop.tools.DocumentInputSource; 72 import org.ofbiz.base.util.Debug; 73 import org.ofbiz.base.util.GeneralException; 74 import org.ofbiz.base.util.HttpClient; 75 import org.ofbiz.base.util.HttpClientException; 76 import org.ofbiz.base.util.UtilMisc; 77 import org.ofbiz.base.util.UtilProperties; 78 import org.ofbiz.base.util.UtilValidate; 79 import org.ofbiz.base.util.UtilXml; 80 import org.ofbiz.base.util.UtilDateTime; 81 import org.ofbiz.base.util.collections.MapStack; 82 import org.ofbiz.base.util.string.FlexibleStringExpander; 83 import org.ofbiz.entity.GenericDelegator; 84 import org.ofbiz.entity.GenericValue; 85 import org.ofbiz.service.DispatchContext; 86 import org.ofbiz.service.GenericServiceException; 87 import org.ofbiz.service.LocalDispatcher; 88 import org.ofbiz.service.ServiceUtil; 89 import org.ofbiz.service.mail.MimeMessageWrapper; 90 import org.ofbiz.widget.html.HtmlScreenRenderer; 91 import org.ofbiz.widget.screen.ScreenRenderer; 92 import org.w3c.dom.Document ; 93 import org.xml.sax.SAXException ; 94 95 104 public class EmailServices { 105 106 public final static String module = EmailServices.class.getName(); 107 108 protected static final HtmlScreenRenderer htmlScreenRenderer = new HtmlScreenRenderer(); 109 110 116 public static Map sendMail(DispatchContext ctx, Map context) { 117 Map results = ServiceUtil.returnSuccess(); 118 String subject = (String ) context.get("subject"); 119 String partyId = (String ) context.get("partyId"); 120 String body = (String ) context.get("body"); 121 List bodyParts = (List ) context.get("bodyParts"); 122 GenericValue userLogin = (GenericValue) context.get("userLogin"); 123 124 results.put("partyId", partyId); 125 results.put("subject", subject); 126 if (UtilValidate.isNotEmpty(body)) results.put("body", body); 127 if (UtilValidate.isNotEmpty(bodyParts)) results.put("bodyParts", bodyParts); 128 results.put("userLogin", userLogin); 129 130 String mailEnabled = UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N"); 132 if (!"Y".equalsIgnoreCase(mailEnabled)) { 133 Debug.logImportant("Mail notifications disabled in general.properties; here is the context with info that would have been sent: " + context, module); 135 return results; 136 } 137 String sendTo = (String ) context.get("sendTo"); 138 String sendCc = (String ) context.get("sendCc"); 139 String sendBcc = (String ) context.get("sendBcc"); 140 141 String redirectAddress = UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo"); 143 if (UtilValidate.isNotEmpty(redirectAddress)) { 144 String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]"; 145 subject = subject + originalRecipients; 146 sendTo = redirectAddress; 147 sendCc = null; 148 sendBcc = null; 149 } 150 151 String sendFrom = (String ) context.get("sendFrom"); 152 String sendType = (String ) context.get("sendType"); 153 String sendVia = (String ) context.get("sendVia"); 154 String authUser = (String ) context.get("authUser"); 155 String authPass = (String ) context.get("authPass"); 156 String contentType = (String ) context.get("contentType"); 157 158 boolean useSmtpAuth = false; 159 160 if (sendType == null || sendType.equals("mail.smtp.host")) { 162 sendType = "mail.smtp.host"; 163 if (sendVia == null || sendVia.length() == 0) { 164 sendVia = UtilProperties.getPropertyValue("general.properties", "mail.smtp.relay.host", "localhost"); 165 } 166 if (authUser == null || authUser.length() == 0) { 167 authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user"); 168 } 169 if (authPass == null || authPass.length() == 0) { 170 authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password"); 171 } 172 if (authUser != null && authUser.length() > 0) { 173 useSmtpAuth = true; 174 } 175 } else if (sendVia == null) { 176 return ServiceUtil.returnError("Parameter sendVia is required when sendType is not mail.smtp.host"); 177 } 178 179 180 if (contentType == null) { 181 contentType = "text/html"; 182 } 183 184 if (UtilValidate.isNotEmpty(bodyParts)) { 185 contentType = "multipart/mixed"; 186 } 187 results.put("contentType", contentType); 188 189 try { 190 Properties props = System.getProperties(); 191 props.put(sendType, sendVia); 192 if (useSmtpAuth) { 193 props.put("mail.smtp.auth", "true"); 194 } 195 196 Session session = Session.getInstance(props); 197 198 MimeMessage mail = new MimeMessage (session); 199 mail.setFrom(new InternetAddress (sendFrom)); 200 mail.setSubject(subject); 201 mail.addRecipients(Message.RecipientType.TO, sendTo); 202 203 if (UtilValidate.isNotEmpty(sendCc)) { 204 mail.addRecipients(Message.RecipientType.CC, sendCc); 205 } 206 if (UtilValidate.isNotEmpty(sendBcc)) { 207 mail.addRecipients(Message.RecipientType.BCC, sendBcc); 208 } 209 210 if (UtilValidate.isNotEmpty(bodyParts)) { 211 MimeMultipart mp = new MimeMultipart (); 214 Debug.logInfo(bodyParts.size() + " multiparts found",module); 215 Iterator bodyPartIter = bodyParts.iterator(); 216 while (bodyPartIter.hasNext()) { 217 Map bodyPart = (Map ) bodyPartIter.next(); 218 Object bodyPartContent = bodyPart.get("content"); 219 MimeBodyPart mbp = new MimeBodyPart (); 220 221 if (bodyPartContent instanceof String ) { 222 StringDataSource sdr = new StringDataSource((String ) bodyPartContent, (String ) bodyPart.get("type")); 223 Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length() , module); 224 mbp.setDataHandler(new DataHandler (sdr)); 225 } else if (bodyPartContent instanceof byte[]) { 226 ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String ) bodyPart.get("type")); 227 Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length , module); 228 mbp.setDataHandler(new DataHandler (bads)); 229 } else { 230 mbp.setDataHandler(new DataHandler (bodyPartContent, (String ) bodyPart.get("type"))); 231 } 232 233 String fileName = (String ) bodyPart.get("filename"); 234 if (fileName != null) { 235 mbp.setFileName(fileName); 236 } 237 mp.addBodyPart(mbp); 238 } 239 mail.setContent(mp); 240 mail.saveChanges(); 241 } else { 242 mail.setContent(body, contentType); 244 mail.saveChanges(); 245 } 246 247 Transport trans = session.getTransport("smtp"); 248 if (!useSmtpAuth) { 249 trans.connect(); 250 } else { 251 trans.connect(sendVia, authUser, authPass); 252 } 253 trans.sendMessage(mail, mail.getAllRecipients()); 254 trans.close(); 255 } catch (Exception e) { 256 String errMsg = "Cannot send email message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]"; 257 Debug.logError(e, errMsg, module); 258 Debug.logError(e, "Email message that could not be sent to [" + sendTo + "] had context: " + context, module); 259 return ServiceUtil.returnError(errMsg); 260 } 261 return results; 262 } 263 264 270 public static Map sendMailFromUrl(DispatchContext ctx, Map context) { 271 String bodyUrl = (String ) context.remove("bodyUrl"); 273 Map bodyUrlParameters = (Map ) context.remove("bodyUrlParameters"); 274 275 URL url = null; 276 277 try { 278 url = new URL (bodyUrl); 279 } catch (MalformedURLException e) { 280 Debug.logWarning(e, module); 281 return ServiceUtil.returnError("Malformed URL: " + bodyUrl + "; error was: " + e.toString()); 282 } 283 284 HttpClient httpClient = new HttpClient(url, bodyUrlParameters); 285 String body = null; 286 287 try { 288 body = httpClient.post(); 289 } catch (HttpClientException e) { 290 Debug.logWarning(e, module); 291 return ServiceUtil.returnError("Error getting content: " + e.toString()); 292 } 293 294 context.put("body", body); 295 Map result = sendMail(ctx, context); 296 297 result.put("body", body); 298 return result; 299 } 300 301 308 public static Map sendMailFromScreen(DispatchContext dctx, Map serviceContext) { 309 LocalDispatcher dispatcher = dctx.getDispatcher(); 310 String webSiteId = (String ) serviceContext.remove("webSiteId"); 311 String bodyText = (String ) serviceContext.remove("bodyText"); 312 String bodyScreenUri = (String ) serviceContext.remove("bodyScreenUri"); 313 String xslfoAttachScreenLocation = (String ) serviceContext.remove("xslfoAttachScreenLocation"); 314 Map bodyParameters = (Map ) serviceContext.remove("bodyParameters"); 315 String partyId = (String ) bodyParameters.get("partyId"); 316 NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters); 317 String contentType = (String ) serviceContext.remove("contentType"); 318 319 StringWriter bodyWriter = new StringWriter (); 320 321 MapStack screenContext = MapStack.create(); 322 ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer); 323 screens.populateContextForService(dctx, bodyParameters); 324 screenContext.putAll(bodyParameters); 325 326 if (bodyScreenUri != null) { 327 try { 328 screens.render(bodyScreenUri); 329 } catch (GeneralException e) { 330 String errMsg = "Error rendering screen for email: " + e.toString(); 331 Debug.logError(e, errMsg, module); 332 return ServiceUtil.returnError(errMsg); 333 } catch (IOException e) { 334 String errMsg = "Error rendering screen for email: " + e.toString(); 335 Debug.logError(e, errMsg, module); 336 return ServiceUtil.returnError(errMsg); 337 } catch (SAXException e) { 338 String errMsg = "Error rendering screen for email: " + e.toString(); 339 Debug.logError(e, errMsg, module); 340 return ServiceUtil.returnError(errMsg); 341 } catch (ParserConfigurationException e) { 342 String errMsg = "Error rendering screen for email: " + e.toString(); 343 Debug.logError(e, errMsg, module); 344 return ServiceUtil.returnError(errMsg); 345 } 346 } 347 348 boolean isMultiPart = false; 349 350 if (UtilValidate.isNotEmpty(xslfoAttachScreenLocation)) { 352 isMultiPart = true; 353 try { 355 Writer writer = new StringWriter (); 356 MapStack screenContextAtt = MapStack.create(); 357 ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, htmlScreenRenderer); 359 screensAtt.populateContextForService(dctx, bodyParameters); 360 screenContextAtt.putAll(bodyParameters); 361 screensAtt.render(xslfoAttachScreenLocation); 362 363 373 374 Logger logger = new Log4JLogger(Debug.getLogger(module)); 376 MessageHandler.setScreenLogger(logger); 377 378 Driver driver = new Driver(); 380 driver.setRenderer(Driver.RENDER_PDF); 381 driver.setLogger(logger); 382 383 Document xslfo = UtilXml.readXmlDocument(writer.toString()); 385 386 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 388 driver.setOutputStream(baos); 389 driver.setInputSource(new DocumentInputSource(xslfo)); 390 391 driver.run(); 393 FopImageFactory.resetCache(); 394 baos.flush(); 395 baos.close(); 396 397 406 407 List bodyParts = FastList.newInstance(); 409 if (bodyText != null) { 410 bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, (Locale ) screenContext.get("locale")); 411 bodyParts.add(UtilMisc.toMap("content", bodyText, "type", "text/html")); 412 } else { 413 bodyParts.add(UtilMisc.toMap("content", bodyWriter.toString(), "type", "text/html")); 414 } 415 bodyParts.add(UtilMisc.toMap("content", baos.toByteArray(), "type", "application/pdf", "filename", "Details.pdf")); 416 serviceContext.put("bodyParts", bodyParts); 417 } catch (GeneralException ge) { 418 String errMsg = "Error rendering PDF attachment for email: " + ge.toString(); 419 Debug.logError(ge, errMsg, module); 420 return ServiceUtil.returnError(errMsg); 421 } catch (IOException ie) { 422 String errMsg = "Error rendering PDF attachment for email: " + ie.toString(); 423 Debug.logError(ie, errMsg, module); 424 return ServiceUtil.returnError(errMsg); 425 } catch (FOPException fe) { 426 String errMsg = "Error rendering PDF attachment for email: " + fe.toString(); 427 Debug.logError(fe, errMsg, module); 428 return ServiceUtil.returnError(errMsg); 429 } catch (SAXException se) { 430 String errMsg = "Error rendering PDF attachment for email: " + se.toString(); 431 Debug.logError(se, errMsg, module); 432 return ServiceUtil.returnError(errMsg); 433 } catch (ParserConfigurationException pe) { 434 String errMsg = "Error rendering PDF attachment for email: " + pe.toString(); 435 Debug.logError(pe, errMsg, module); 436 return ServiceUtil.returnError(errMsg); 437 } 438 } else { 439 isMultiPart = false; 440 if (bodyText != null) { 442 bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, (Locale ) screenContext.get("locale")); 443 serviceContext.put("body", bodyText); 444 } else { 445 serviceContext.put("body", bodyWriter.toString()); 446 } 447 448 if (contentType != null && contentType.equalsIgnoreCase("text/plain")) { 451 serviceContext.put("contentType", "text/plain"); 452 } else { 453 serviceContext.put("contentType", "text/html"); 454 } 455 } 456 457 String subject = (String ) serviceContext.remove("subject"); 459 subject = FlexibleStringExpander.expandString(subject, screenContext, (Locale ) screenContext.get("locale")); 460 serviceContext.put("subject", subject); 461 serviceContext.put("partyId", partyId); 462 463 if (Debug.verboseOn()) Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module); 464 Map result = ServiceUtil.returnSuccess(); 465 466 try { 467 if (isMultiPart) { 468 dispatcher.runSync("sendMailMultiPart", serviceContext); 469 } else { 470 dispatcher.runSync("sendMail", serviceContext); 471 } 472 } catch (Exception e) { 473 String errMsg = "Error send email :" + e.toString(); 474 Debug.logError(e, errMsg, module); 475 return ServiceUtil.returnError(errMsg); 476 } 477 result.put("body", bodyWriter.toString()); 478 return result; 479 } 480 481 487 public static Map storeEmailAsCommunication(DispatchContext dctx, Map serviceContext) { 488 LocalDispatcher dispatcher = dctx.getDispatcher(); 489 GenericValue userLogin = (GenericValue) serviceContext.get("userLogin"); 490 491 String subject = (String ) serviceContext.get("subject"); 492 String body = (String ) serviceContext.get("body"); 493 String partyId = (String ) serviceContext.get("partyId"); 494 String communicationEventId = (String ) serviceContext.get("communicationEventId"); 495 String contentType = (String ) serviceContext.get("contentType"); 496 497 if (communicationEventId == null) { 499 String partyIdFrom = (String ) userLogin.get("partyId"); 500 Map commEventMap = FastMap.newInstance(); 501 commEventMap.put("communicationEventTypeId", "EMAIL_COMMUNICATION"); 502 commEventMap.put("statusId", "COM_COMPLETE"); 503 commEventMap.put("contactMechTypeId", "EMAIL_ADDRESS"); 504 commEventMap.put("partyIdFrom", partyIdFrom); 505 commEventMap.put("partyIdTo", partyId); 506 commEventMap.put("subject", subject); 507 commEventMap.put("content", body); 508 commEventMap.put("userLogin", userLogin); 509 commEventMap.put("contentMimeTypeId", contentType); 510 try { 511 dispatcher.runSync("createCommunicationEvent", commEventMap); 512 } catch (Exception e) { 513 Debug.logError(e, "Cannot store email as communication event", module); 514 return ServiceUtil.returnError("Cannot store email as communication event; see logs"); 515 } 516 } 517 518 return ServiceUtil.returnSuccess(); 519 } 520 521 522 public static class StringDataSource implements DataSource { 523 private String contentType; 524 private ByteArrayOutputStream contentArray; 525 526 public StringDataSource(String content, String contentType) throws IOException { 527 this.contentType = contentType; 528 contentArray = new ByteArrayOutputStream (); 529 contentArray.write(content.getBytes("iso-8859-1")); 530 contentArray.flush(); 531 contentArray.close(); 532 } 533 534 public String getContentType() { 535 return contentType == null ? "application/octet-stream" : contentType; 536 } 537 538 public InputStream getInputStream() throws IOException { 539 return new ByteArrayInputStream (contentArray.toByteArray()); 540 } 541 542 public String getName() { 543 return "stringDatasource"; 544 } 545 546 public OutputStream getOutputStream() throws IOException { 547 throw new IOException ("Cannot write to this read-only resource"); 548 } 549 } 550 551 552 public static class ByteArrayDataSource implements DataSource { 553 private String contentType; 554 private byte[] contentArray; 555 556 public ByteArrayDataSource(byte[] content, String contentType) throws IOException { 557 this.contentType = contentType; 558 this.contentArray = content; 559 } 560 561 public String getContentType() { 562 return contentType == null ? "application/octet-stream" : contentType; 563 } 564 565 public InputStream getInputStream() throws IOException { 566 return new ByteArrayInputStream (contentArray); 567 } 568 569 public String getName() { 570 return "ByteArrayDataSource"; 571 } 572 573 public OutputStream getOutputStream() throws IOException { 574 throw new IOException ("Cannot write to this read-only resource"); 575 } 576 } 577 578 581 private static Map getParyInfoFromEmailAddress(Address [] addresses, GenericValue userLogin, LocalDispatcher dispatcher) throws GenericServiceException 582 { 583 InternetAddress emailAddress = null; 584 Map map = null; 585 Map result = null; 586 587 if (addresses.length > 0) { 588 Address addr = addresses[0]; 589 if (addr instanceof InternetAddress ) { 590 emailAddress = (InternetAddress )addr; 591 } 592 } 593 594 if (!UtilValidate.isEmpty(emailAddress)) { 595 map = new HashMap (); 596 map.put("address", emailAddress.getAddress()); 597 map.put("personal", emailAddress.getPersonal()); 598 map.put("userLogin", userLogin); 599 result = dispatcher.runSync("findPartyFromEmailAddress", map); 600 } 601 602 return result; 603 } 604 605 608 private static List buildListOfPartyInfoFromEmailAddresses(Address [] addresses, GenericValue userLogin, LocalDispatcher dispatcher) throws GenericServiceException 609 { 610 InternetAddress emailAddress = null; 611 Address addr = null; 612 Map map = null; 613 Map result = null; 614 List tempResults = new ArrayList (); 615 616 if (addresses != null) { 617 for (int i = 0; i < addresses.length; i++) { 618 addr = addresses[i]; 619 if (addr instanceof InternetAddress ) { 620 emailAddress = (InternetAddress )addr; 621 622 if (!UtilValidate.isEmpty(emailAddress)) { 623 map = new HashMap (); 624 map.put("address", emailAddress.getAddress()); 625 map.put("personal", emailAddress.getPersonal()); 626 map.put("userLogin", userLogin); 627 result = dispatcher.runSync("findPartyFromEmailAddress", map); 628 629 tempResults.add(result); 630 } 631 } 632 } 633 } 634 635 return tempResults; 636 } 637 638 641 private static List getListOfParyInfoFromEmailAddresses(Address [] addressesTo, Address [] addressesCC, Address [] addressesBCC, GenericValue userLogin, LocalDispatcher dispatcher) throws GenericServiceException 642 { 643 List allResults = new ArrayList (); 644 645 allResults.addAll(buildListOfPartyInfoFromEmailAddresses(addressesTo, userLogin, dispatcher)); 647 648 allResults.addAll(buildListOfPartyInfoFromEmailAddresses(addressesCC, userLogin, dispatcher)); 650 651 allResults.addAll(buildListOfPartyInfoFromEmailAddresses(addressesBCC, userLogin, dispatcher)); 653 654 return allResults; 655 } 656 657 684 public static Map storeIncomingEmail(DispatchContext dctx, Map context) { 685 686 GenericDelegator delegator = dctx.getDelegator(); 687 LocalDispatcher dispatcher = dctx.getDispatcher(); 688 MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper"); 689 MimeMessage message = wrapper.getMessage(); 690 Timestamp nowTimestamp = UtilDateTime.nowTimestamp(); 691 GenericValue userLogin = (GenericValue) context.get("userLogin"); 692 String partyIdTo = null; 693 String partyIdFrom = null; 694 String contentType = null; 695 String content = null; 696 String communicationEventId = null; 697 String contactMechIdFrom = null; 698 String contactMechIdTo = null; 699 700 Map result = null; 701 try { 702 String contentTypeRaw = message.getContentType(); 703 int idx = contentTypeRaw.indexOf(";"); 704 contentType = contentTypeRaw.substring(0, idx); 705 Address [] addressesFrom = message.getFrom(); 706 Address [] addressesTo = message.getRecipients(MimeMessage.RecipientType.TO); 707 Address [] addressesCC = message.getRecipients(MimeMessage.RecipientType.CC); 708 Address [] addressesBCC = message.getRecipients(MimeMessage.RecipientType.BCC); 709 Debug.logInfo("Processing Incoming Email message from: " + addressesFrom[0].toString() + " to: " + addressesTo[0].toString(), module); 710 711 String spamHeaderName = UtilProperties.getPropertyValue("general.properties", "mail.spam.name", "N"); 713 String configHeaderValue = UtilProperties.getPropertyValue("general.properties", "mail.spam.value"); 714 if (!spamHeaderName.equals("N") && message.getHeader(spamHeaderName) != null) { 716 String msgHeaderValue = message.getHeader(spamHeaderName)[0]; 717 if(msgHeaderValue != null && msgHeaderValue.startsWith(configHeaderValue)) { 718 Debug.logInfo("Incoming Email message ignored, was detected by external spam checker", module); 719 return ServiceUtil.returnSuccess(" Message Ignored: detected by external spam checker"); 720 } 721 } 722 723 if (addressesFrom == null) { 725 Debug.logInfo("Incoming Email message ignored, had not 'from' email address", module); 726 return ServiceUtil.returnSuccess(" Message Ignored: no 'From' address specified"); 727 } 728 729 730 result = getParyInfoFromEmailAddress(addressesFrom, userLogin, dispatcher); 731 partyIdFrom = (String )result.get("partyId"); 732 contactMechIdFrom = (String )result.get("contactMechId"); 733 734 List allResults = getListOfParyInfoFromEmailAddresses(addressesTo, addressesCC, addressesBCC, userLogin, dispatcher); 735 Iterator itr = allResults.iterator(); 736 737 if ((allResults != null) && (allResults.size() > 0)) { 739 Map firstAddressTo = (Map ) itr.next(); 740 partyIdTo = (String )firstAddressTo.get("partyId"); 741 contactMechIdTo = (String )firstAddressTo.get("contactMechId"); 742 } 743 744 Map commEventMap = new HashMap (); 745 commEventMap.put("communicationEventTypeId", "AUTO_EMAIL_COMM"); 746 commEventMap.put("contactMechTypeId", "EMAIL_ADDRESS"); 747 String subject = message.getSubject(); 748 commEventMap.put("subject", subject); 749 750 commEventMap.put("entryDate", nowTimestamp); 751 752 commEventMap.put("datetimeStarted", UtilDateTime.toTimestamp(message.getSentDate())); 754 commEventMap.put("datetimeEnded", UtilDateTime.toTimestamp(message.getReceivedDate())); 755 756 int contentIndex = -1; Multipart multipart = null; 758 if (contentType.startsWith("text")) { 759 content = (String )message.getContent(); 761 commEventMap.put("contentMimeTypeId", contentType); 762 } else if (contentType.startsWith("multipart")) { 763 multipart = (Multipart )message.getContent(); 764 int multipartCount = multipart.getCount(); 765 766 for (int i=0; i < multipartCount; i++) { 768 Part part = multipart.getBodyPart(i); 769 String thisContentTypeRaw = part.getContentType(); 770 int idx2 = thisContentTypeRaw.indexOf(";"); 771 String thisContentType = thisContentTypeRaw.substring(0, idx2); 772 String disposition = part.getDisposition(); 773 774 if ((disposition == null) && (i == 0)) 776 { 777 if (part.getContent() != null) { 778 if (thisContentType.startsWith("text")) { 781 content = (String )part.getContent(); 783 } 784 else { 785 if(part.getContent() instanceof Multipart ) { 787 Multipart components = (Multipart )part.getContent(); 788 int numOfComponents = components.getCount(); 789 790 for (int j = 0; j < numOfComponents; j++) { 791 Part component = components.getBodyPart(j); 792 String entireContent = component.getContentType(); 793 int idxOfSemiColon = entireContent.indexOf(";"); 794 String requiredContent = entireContent.substring(0, idxOfSemiColon); 795 796 if (requiredContent.startsWith("text/html")) { 797 content = (String )component.getContent(); 798 799 break; 801 } 802 } 803 } 804 } 805 } 806 807 if (UtilValidate.isNotEmpty(content)) { 808 contentIndex = i; 809 commEventMap.put("contentMimeTypeId", thisContentType); 810 break; 811 } 812 } else if ((disposition != null) 813 && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) 814 && thisContentType.startsWith("text")) 815 { 816 content = (String )part.getContent(); 817 contentIndex = i; 818 commEventMap.put("contentMimeTypeId", thisContentType); 819 break; 820 } 821 } 822 } 823 commEventMap.put("content", content); 824 825 String commNote = ""; 827 if (partyIdFrom != null) { 828 commEventMap.put("partyIdFrom", partyIdFrom); 829 commEventMap.put("contactMechIdFrom", contactMechIdFrom); 830 commEventMap.put("contactMechIdTo", contactMechIdTo); 831 commEventMap.put("statusId", "COM_ENTERED"); 832 } else { 833 commNote += "Sent from: " + ((InternetAddress )addressesFrom[0]).getAddress() + "; "; 834 } 835 836 if (partyIdTo != null) { 837 commEventMap.put("partyIdTo", partyIdTo); 838 commEventMap.put("contactMechIdTo", contactMechIdTo); 839 } else { 840 commNote += "Sent to: " + ((InternetAddress )addressesTo[0]).getAddress() + "; "; 841 } 842 843 if (partyIdTo != null && partyIdFrom != null) { 844 commEventMap.put("statusId", "COM_ENTERED"); 845 } else { 846 commEventMap.put("statusId", "COM_UNKNOWN_PARTY"); 847 } 848 849 if (!("".equals(commNote))) { 850 commEventMap.put("note", commNote); 851 } 852 853 commEventMap.put("userLogin", userLogin); 854 result = dispatcher.runSync("createCommunicationEvent", commEventMap); 855 communicationEventId = (String )result.get("communicationEventId"); 856 if (contentType.startsWith("multipart")) { 857 int attachmentCount = EmailWorker.addAttachmentsToCommEvent(message, communicationEventId, contentIndex, dispatcher, userLogin); 858 if (Debug.infoOn()) Debug.logInfo(attachmentCount + " attachments added to CommunicationEvent:" + communicationEventId,module); 859 } 860 861 while (itr.hasNext()) { 863 Map address = (Map ) itr.next(); 864 String partyId = (String )address.get("partyId"); 865 866 GenericValue partyRole = delegator.findByPrimaryKey("PartyRole", UtilMisc.toMap("partyId", partyId, "roleTypeId", "_NA_")); 869 if (partyRole == null) { 870 dispatcher.runSync("createPartyRole", UtilMisc.toMap("partyId", partyId, "roleTypeId", "_NA_", "userLogin", userLogin)); 871 } 872 Map input = UtilMisc.toMap("communicationEventId", communicationEventId, "partyId", partyId, "roleTypeId", "_NA_", "userLogin", userLogin, "contactMechId", (String )address.get("contactMechId")); 873 dispatcher.runSync("createCommunicationEventRole", input); 874 } 875 876 Map results = ServiceUtil.returnSuccess(); 877 results.put("communicationEventId", communicationEventId); 878 return results; 879 } catch (MessagingException e) { 880 Debug.logError(e, module); 881 return ServiceUtil.returnError(e.getMessage()); 882 } catch (GenericServiceException e) { 883 Debug.logError(e, module); 884 return ServiceUtil.returnError(e.getMessage()); 885 } catch (IOException e) { 886 Debug.logError(e, module); 887 return ServiceUtil.returnError(e.getMessage()); 888 } catch (Exception e) { 889 Debug.logError(e, module); 890 return ServiceUtil.returnError(e.getMessage()); 891 } 892 } 893 } 894 | Popular Tags |