List of usage examples for javax.mail.internet MimeMessage setSubject
@Override public void setSubject(String subject) throws MessagingException
From source file:davmail.exchange.ews.EwsExchangeSession.java
/** * Get item content.// w w w. j a v a 2 s . c o m * * @param itemId EWS item id * @return item content as byte array * @throws IOException on error */ protected byte[] getContent(ItemId itemId) throws IOException { GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true); byte[] mimeContent = null; try { executeMethod(getItemMethod); mimeContent = getItemMethod.getMimeContent(); } catch (EWSException e) { LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage()); } if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new HttpNotFoundException("Item " + itemId + " not found"); } if (mimeContent == null) { LOGGER.warn("MimeContent not available, trying to rebuild from properties"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false); getItemMethod.addAdditionalProperty(Field.get("contentclass")); getItemMethod.addAdditionalProperty(Field.get("message-id")); getItemMethod.addAdditionalProperty(Field.get("from")); getItemMethod.addAdditionalProperty(Field.get("to")); getItemMethod.addAdditionalProperty(Field.get("cc")); getItemMethod.addAdditionalProperty(Field.get("subject")); getItemMethod.addAdditionalProperty(Field.get("date")); getItemMethod.addAdditionalProperty(Field.get("body")); executeMethod(getItemMethod); EWSMethod.Item item = getItemMethod.getResponseItem(); MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName())); mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName()))); mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName())); mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName())); mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName())); mimeMessage.setSubject(item.get(Field.get("subject").getResponseName())); String propertyValue = item.get(Field.get("body").getResponseName()); if (propertyValue == null) { propertyValue = ""; } mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); mimeMessage.writeTo(baos); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } mimeContent = baos.toByteArray(); } catch (IOException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } if (mimeContent == null) { throw new IOException("GetItem returned null MimeContent"); } } return mimeContent; }
From source file:com.kgmp.mfds.controller.FormsController.java
@RequestMapping(value = "/updatePaymentProc.do") public ModelAndView updatePayment(@RequestParam("forms_seq") int forms_seq, @RequestParam("payment_name") String payment_name, @RequestParam("payment_bank") String payment_bank) { ModelAndView mav = new ModelAndView(); String msg = null;//from w ww .j a v a 2s.c o m String url = null; Forms forms = new Forms(); forms.setForms_seq(forms_seq); System.out.println(payment_bank); forms.setPayment_name(payment_name); forms.setPayment_bank(payment_bank); String check = null; try { check = forms_service.updatePayment(forms); if (check.equals("yes")) { msg = "."; url = "/MyPage.do?page_seq=6"; } else { msg = "."; url = "/NewForms.do?forms_seq=" + forms_seq; } } catch (Exception e) { e.printStackTrace(); } //send payment check e-mail s try { MimeMessage message = mailSender.createMimeMessage(); String test1 = "K-GMP@K-GMP.com"; String test2 = "K-GMP@K-GMP.com"; String test3 = "STED] "; String test4 = "<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'><html><body style='width:600px border:1px solid grey;'><div style='margin:0 auto; padding:10px; width:700px; border:1px solid grey;'><div> <div> <img src='http://sted.kr/resources/img/common/header_bg2.jpg' width='100%'> </div> <div style='background-color:#102967; color:#ffffff; height:30px;'> ? </div></div><div><br><br> . STED ?? .<br> <b>" + payment_name + "</b> ? .<br> ? ? ? ? ? ? .<br><br> <b>? :</b> <h1 style='color:#303698;'>" + payment_name + "</h1><br> <b> :</b> <h1 style='color:#303698;'>" + payment_bank + "</h1><br><br> ? 7? ?? ? .<br> ? 3? ?? .<br><br> ()_<a href='https://sted.kr/Admin.do'>?? </a><br><br><br> <p style='color:grey;'> ?? . ?? ? . ? ?? ? . ? ? <a href='mailto:K-GMP@K-GMP.COM'>K-GMP@K-GMP.COM</a> ?.</p><br><div style='background-color:#102967; color:#ffffff; height:30px; text-align:right;'>Copyright K-GMP All Right Reserved </div></div></div></body></html>"; message.setFrom(new InternetAddress(test1)); message.addRecipient(RecipientType.TO, new InternetAddress(test2)); message.setSubject(test3); message.setText(test4, "utf-8", "html"); mailSender.send(message); } catch (Exception e) { e.printStackTrace(); } //send e-mail e mav.addObject("msg", msg); mav.addObject("url", url); mav.setViewName("/Opener_check_proc"); return mav; }
From source file:com.flexoodb.common.FlexUtils.java
static public boolean sendMail(String host, int port, String from, String to, String subject, String msg) throws Exception { SMTPTransport transport = null;//from w w w .j a v a 2s .c om boolean ok = false; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); ok = true; } catch (Exception e) { e.printStackTrace(); } finally { try { transport.close(); } catch (Exception f) { f.printStackTrace(); } } return ok; }
From source file:com.flexoodb.common.FlexUtils.java
static public String sendMailShowResult(String host, int port, String from, String to, String subject, String msg) throws Exception { String response = "OK"; SMTPTransport transport = null;/* w w w . j a v a2 s . c o m*/ boolean ok = true; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original props.put("mail.smtp.timeout", "60000"); props.put("mail.smtp.quitwait", "false"); javax.mail.Session session = javax.mail.Session.getInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); } catch (Exception e) { e.printStackTrace(); ok = false; } finally { try { if (!ok) { response = "SENDING FAILED:" + transport.getLastServerResponse(); } else { response = "SENDING SUCCESS:" + transport.getLastServerResponse(); } transport.close(); } catch (Exception f) { } } return response; }
From source file:com.flexoodb.common.FlexUtils.java
static public String sendMailShowResult(String host, int port, String fromname, String from, String to, String subject, String msg) throws Exception { String response = "OK"; SMTPTransport transport = null;//from w w w.ja v a 2 s. c o m boolean ok = true; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original props.put("mail.smtp.timeout", "60000"); props.put("mail.smtp.quitwait", "false"); javax.mail.Session session = javax.mail.Session.getInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); if (fromname == null || fromname.isEmpty()) { message.setFrom(new InternetAddress(from)); } else { message.setFrom(new InternetAddress(from, fromname)); } message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); } catch (Exception e) { e.printStackTrace(); ok = false; } finally { try { if (!ok) { response = "SENDING FAILED:" + transport.getLastServerResponse(); } else { response = "SENDING SUCCESS:" + transport.getLastServerResponse(); } transport.close(); } catch (Exception f) { } } return response; }
From source file:it.infn.ct.nuclemd.Nuclemd.java
private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym, String GATEWAY) {//w w w . j a v a2s.c o m log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]"); log.info("\n- SMTP Server = " + SMTP_HOST); log.info("\n- Sender = " + FROM); log.info("\n- Receiver = " + TO); log.info("\n- Application = " + ApplicationAcronym); log.info("\n- Gateway = " + GATEWAY); // Assuming you are sending email from localhost String HOST = "localhost"; // Get system properties Properties properties = System.getProperties(); properties.setProperty(SMTP_HOST, HOST); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(FROM)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO)); //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM)); // Set Subject: header field message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] "); Date currentDate = new Date(); currentDate.setTime(currentDate.getTime()); // Send the actual HTML message, as big as you like message.setContent("<br/><H4>" + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification" + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ " + ApplicationAcronym + " ]</b><br/><br/>" + "<i>The application has been successfully submitted from the [ " + GATEWAY + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>" + "<b>Disclaimer:</b><br/>" + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>" + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:" + FROM + "\">contact us</a></i>", "text/html"); // Send message Transport.send(message); } catch (MessagingException ex) { Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:it.infn.ct.wrf.Wrf.java
private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym, String GATEWAY) {//from w w w . java 2 s .com log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]"); log.info("\n- SMTP Server = " + SMTP_HOST); log.info("\n- Sender = " + FROM); log.info("\n- Receiver = " + TO); log.info("\n- Application = " + ApplicationAcronym); log.info("\n- Gateway = " + GATEWAY); // Assuming you are sending email from localhost String HOST = "localhost"; // Get system properties Properties properties = System.getProperties(); properties.setProperty(SMTP_HOST, HOST); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(FROM)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO)); //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM)); // Set Subject: header field message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] "); Date currentDate = new Date(); currentDate.setTime(currentDate.getTime()); // Send the actual HTML message, as big as you like message.setContent("<br/><H4>" + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification" + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ " + ApplicationAcronym + " ]</b><br/><br/>" + "<i>The application has been successfully submitted from the [ " + GATEWAY + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>" + "<b>Disclaimer:</b><br/>" + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>" + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:" + FROM + "\">contact us</a></i>", "text/html"); // Send message Transport.send(message); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
/** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail>/*w ww .j a v a 2 s.c o m*/ * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; if (bodyPart.getLocalName().equals("text")) { // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; } else if (bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; } else if (bodyPart.getLocalName().equals("generic")) { // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); } // Now, time to store it if (content != null && contentType != null && contentType.length() > 0) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (attachments.size() > 0) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; }
From source file:immf.ImodeForwardMail.java
@Override public void buildMimeMessage() throws EmailException { super.buildMimeMessage(); MimeMessage msg = this.getMimeMessage(); try {/* w w w .jav a 2 s . c o m*/ msg.setHeader("X-Mailer", ServerMain.Version); if (!this.conf.isRewriteAddress()) { // ??imode???????? msg.setHeader("Resent-From", this.conf.getSmtpMailAddress()); if (!this.conf.getForwardTo().isEmpty()) { msg.setHeader("Resent-To", StringUtils.join(this.conf.getForwardTo(), ",")); } if (!this.conf.getForwardCc().isEmpty()) { msg.setHeader("Resent-Cc", StringUtils.join(this.conf.getForwardCc(), ",")); } if (!this.conf.getForwardBcc().isEmpty()) { msg.setHeader("Resent-Bcc", StringUtils.join(this.conf.getForwardBcc(), ",")); } SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US); msg.setHeader("Resent-Date", df.format(new Date())); msg.setHeader("Date", df.format(this.imm.getTimeDate())); msg.removeHeader("To"); msg.removeHeader("Cc"); msg.removeHeader("Bcc"); List<InternetAddress> tolist = new ArrayList<InternetAddress>(); List<InternetAddress> cclist = new ArrayList<InternetAddress>(); boolean useMyAddress = false; if (this.imm.getFolderId() != ImodeNetClient.FolderIdSent) { if (this.conf.isHideMyaddr()) { if (this.imm.getToAddrList().size() == 0) { useMyAddress = true; } } else { useMyAddress = true; } } if (useMyAddress) { switch (this.imm.getRecvType()) { case ImodeMail.RECV_TYPE_TO: tolist.add(this.imm.getMyInternetAddress()); break; case ImodeMail.RECV_TYPE_CC: cclist.add(this.imm.getMyInternetAddress()); break; case ImodeMail.RECV_TYPE_BCC: break; } } tolist.addAll(this.imm.getToAddrList()); cclist.addAll(this.imm.getCcAddrList()); msg.setHeader("To", InternetAddress.toString(tolist.toArray(new InternetAddress[0]))); if (this.imm.getCcAddrList().size() > 0) { msg.setHeader("Cc", InternetAddress.toString(cclist.toArray(new InternetAddress[0]))); } msg.setFrom(this.imm.getFromAddr()); } String subject = null; if (imm.getFolderId() == ImodeNetClient.FolderIdSent) { subject = conf.getSentSubjectAppendPrefix() + imm.getSubject() + conf.getSentSubjectAppendSuffix(); } else { subject = conf.getSubjectAppendPrefix() + imm.getSubject() + conf.getSubjectAppendSuffix(); } if (conf.isSubjectEmojiReplace()) { subject = EmojiUtil.replaceToLabel(subject); } if (ImodeForwardMail.goomojiSubjectCharConv != null) { String goomojiSubject = ImodeForwardMail.goomojiSubjectCharConv.convert(subject); msg.setHeader("X-Goomoji-Source", "docomo_ne_jp"); msg.setHeader("X-Goomoji-Subject", Util.encodeGoomojiSubject(goomojiSubject)); } subject = ImodeForwardMail.subjectCharConv.convert(subject); msg.setSubject(MimeUtility.encodeText(subject, this.charset, "B")); if (this.conf.getContentTransferEncoding() != null) { msg.setHeader("Content-Transfer-Encoding", this.conf.getContentTransferEncoding()); } } catch (Exception e) { log.warn(e); } }
From source file:davmail.exchange.dav.DavExchangeSession.java
/** * @inheritDoc/* w w w . j a va 2 s . co m*/ */ @Override protected byte[] getContent(ExchangeSession.Message message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream contentInputStream; try { try { try { contentInputStream = getContentInputStream(message.messageUrl); } catch (UnknownHostException e) { // failover for misconfigured Exchange server, replace host name in url restoreHostName = true; contentInputStream = getContentInputStream(message.messageUrl); } } catch (HttpNotFoundException e) { LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl"); contentInputStream = getContentInputStream(message.permanentUrl); } try { IOUtil.write(contentInputStream, baos); } finally { contentInputStream.close(); } } catch (LoginTimeoutException e) { // throw error on expired session LOGGER.warn(e.getMessage()); throw e; } catch (IOException e) { LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl + ", trying to rebuild from properties"); try { DavPropertyNameSet messageProperties = new DavPropertyNameSet(); messageProperties.add(Field.getPropertyName("contentclass")); messageProperties.add(Field.getPropertyName("message-id")); messageProperties.add(Field.getPropertyName("from")); messageProperties.add(Field.getPropertyName("to")); messageProperties.add(Field.getPropertyName("cc")); messageProperties.add(Field.getPropertyName("subject")); messageProperties.add(Field.getPropertyName("date")); messageProperties.add(Field.getPropertyName("htmldescription")); messageProperties.add(Field.getPropertyName("body")); PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl), messageProperties, 0); DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod); MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus(); if (responses.getResponses().length > 0) { MimeMessage mimeMessage = new MimeMessage((Session) null); DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK); String propertyValue = getPropertyIfExists(properties, "contentclass"); if (propertyValue != null) { mimeMessage.addHeader("Content-class", propertyValue); } propertyValue = getPropertyIfExists(properties, "date"); if (propertyValue != null) { mimeMessage.setSentDate(parseDateFromExchange(propertyValue)); } propertyValue = getPropertyIfExists(properties, "from"); if (propertyValue != null) { mimeMessage.addHeader("From", propertyValue); } propertyValue = getPropertyIfExists(properties, "to"); if (propertyValue != null) { mimeMessage.addHeader("To", propertyValue); } propertyValue = getPropertyIfExists(properties, "cc"); if (propertyValue != null) { mimeMessage.addHeader("Cc", propertyValue); } propertyValue = getPropertyIfExists(properties, "subject"); if (propertyValue != null) { mimeMessage.setSubject(propertyValue); } propertyValue = getPropertyIfExists(properties, "htmldescription"); if (propertyValue != null) { mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); } else { propertyValue = getPropertyIfExists(properties, "body"); if (propertyValue != null) { mimeMessage.setText(propertyValue); } } mimeMessage.writeTo(baos); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray())); } } catch (IOException e2) { LOGGER.warn(e2); } catch (DavException e2) { LOGGER.warn(e2); } catch (MessagingException e2) { LOGGER.warn(e2); } // other exception if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) { LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl); try { message.delete(); } catch (IOException ioe) { LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl); } throw e; } } return baos.toByteArray(); }