List of usage examples for javax.mail Message getContentType
public String getContentType() throws MessagingException;
From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java
/** * Aggregates the e-mail message by reading it and turning it either into a * page or a file upload./* w w w .ja v a 2 s. com*/ * * @param message * the e-mail message * @param site * the site to publish to * @throws MessagingException * if fetching the message data fails * @throws IOException * if writing the contents to the output stream fails */ protected Page aggregate(Message message, Site site) throws IOException, MessagingException, IllegalArgumentException { ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString()); Page page = new PageImpl(uri); Language language = site.getDefaultLanguage(); // Extract title and subject. Without these two, creating a page is not // feasible, therefore both messages throw an IllegalArgumentException if // the fields are not present. String title = getSubject(message); String author = getAuthor(message); // Collect default settings PageTemplate template = site.getDefaultTemplate(); if (template == null) throw new IllegalStateException("Missing default template in site '" + site + "'"); String stage = template.getStage(); if (StringUtils.isBlank(stage)) throw new IllegalStateException( "Missing stage definition in template '" + template.getIdentifier() + "'"); // Standard fields page.setTitle(title, language); page.setTemplate(template.getIdentifier()); page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null); // TODO: Translate e-mail "from" into site user and throw if no such // user can be found page.setCreated(site.getAdministrator(), message.getSentDate()); // Start looking at the message body String contentType = message.getContentType(); if (StringUtils.isBlank(contentType)) throw new IllegalArgumentException("Message content type is unspecified"); // Text body if (contentType.startsWith("text/plain")) { // TODO: Evaluate charset String body = null; if (message.getContent() instanceof String) body = (String) message.getContent(); else if (message.getContent() instanceof InputStream) body = IOUtils.toString((InputStream) message.getContent()); else throw new IllegalArgumentException("Message body is of unknown type"); return handleTextPlain(body, page, language); } // HTML body if (contentType.startsWith("text/html")) { // TODO: Evaluate charset return handleTextHtml((String) message.getContent(), page, null); } // Multipart body else if ("mime/multipart".equalsIgnoreCase(contentType)) { Multipart mp = (Multipart) message.getContent(); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { return handleTextPlain((String) mbp.getContent(), page, null); } else { // TODO: Implement special non-attachment cases here of // image/gif, text/html, ... throw new UnsupportedOperationException("Multipart message bodies of type '" + mbp.getContentType() + "' are not yet supported"); } } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) { logger.info("Skipping message attachment " + part.getFileName()); // saveFile(part.getFileName(), part.getInputStream()); } } throw new IllegalArgumentException("Multipart message did not contain any recognizable content"); } // ? else { throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'"); } }
From source file:org.nuclos.server.ruleengine.RuleInterface.java
/** * * @param pop3Host//ww w . j av a 2 s .c o m * @param pop3Port * @param pop3User * @param pop3Password * @param remove * @return * @throws NuclosFatalRuleException */ public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User, final String pop3Password, boolean remove) throws NuclosFatalRuleException { try { Properties properties = new Properties(); properties.setProperty("mail.pop3.host", pop3Host); properties.setProperty("mail.pop3.port", pop3Port); properties.setProperty("mail.pop3.auth", "true"); properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(pop3User, pop3Password); } }); session.setDebug(true); Store store = session.getStore("pop3"); store.connect(); Folder folder = store.getFolder("INBOX"); if (remove) { folder.open(Folder.READ_WRITE); } else { folder.open(Folder.READ_ONLY); } List<NuclosMail> result = new ArrayList<NuclosMail>(); Message message[] = folder.getMessages(); for (int i = 0; i < message.length; i++) { Message m = message[i]; NuclosMail mail = new NuclosMail(); logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: " + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType() + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate()); Address[] senders = m.getFrom(); if (senders.length == 1 && senders[0] instanceof InternetAddress) { mail.setFrom(((InternetAddress) senders[0]).getAddress()); } else { mail.setFrom(Arrays.toString(m.getFrom())); } mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO))); mail.setSubject(m.getSubject()); if (m.isMimeType("text/plain")) { mail.setMessage((String) m.getContent()); } else { Multipart mp = (Multipart) m.getContent(); for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); MimeBodyPart mimePart = (MimeBodyPart) part; logger.debug( "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType()); if (disposition == null && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) { mail.setMessage((String) mimePart.getDataHandler().getContent()); } } getAttachments(mp, mail); } result.add(mail); if (remove) { m.setFlag(Flags.Flag.DELETED, true); } } if (remove) { folder.close(true); } else { folder.close(false); } store.close(); return result; } catch (Exception e) { throw new NuclosFatalRuleException(e); } }
From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java
private boolean extractMessage(Message Mess, long messageID, String attachURI, String attachDIR) { cfArrayData ADD = cfArrayData.createArray(1); try {/*w ww .j a va 2s . c o m*/ setData("subject", new cfStringData(Mess.getSubject())); setData("id", new cfNumberData(messageID)); //--- Pull out all the headers cfStructData headers = new cfStructData(); Enumeration<Header> eH = Mess.getAllHeaders(); String headerKey; while (eH.hasMoreElements()) { Header hdr = eH.nextElement(); headerKey = hdr.getName().replace('-', '_').toLowerCase(); if (headers.containsKey(headerKey)) { headers.setData(headerKey, new cfStringData(headers.getData(headerKey).toString() + ";" + hdr.getValue())); } else headers.setData(headerKey, new cfStringData(hdr.getValue())); } setData("headers", headers); // Get the Date Date DD = Mess.getReceivedDate(); if (DD == null) setData("rxddate", new cfDateData(System.currentTimeMillis())); else setData("rxddate", new cfDateData(DD.getTime())); DD = Mess.getSentDate(); if (DD == null) setData("sentdate", new cfDateData(System.currentTimeMillis())); else setData("sentdate", new cfDateData(DD.getTime())); // Get the FROM field Address[] from = Mess.getFrom(); if (from != null && from.length > 0) { cfStructData sdFrom = new cfStructData(); String name = ((InternetAddress) from[0]).getPersonal(); if (name != null) sdFrom.setData("name", new cfStringData(name)); sdFrom.setData("email", new cfStringData(((InternetAddress) from[0]).getAddress())); setData("from", sdFrom); } //--[ Get the TO/CC/BCC field cfArrayData AD = extractAddresses(Mess.getRecipients(Message.RecipientType.TO)); if (AD != null) setData("to", AD); AD = extractAddresses(Mess.getRecipients(Message.RecipientType.CC)); if (AD != null) setData("cc", AD); AD = extractAddresses(Mess.getRecipients(Message.RecipientType.BCC)); if (AD != null) setData("bcc", AD); AD = extractAddresses(Mess.getReplyTo()); if (AD != null) setData("replyto", AD); //--[ Set the flags setData("answered", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.ANSWERED))); setData("deleted", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DELETED))); setData("draft", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DRAFT))); setData("flagged", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.FLAGGED))); setData("recent", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.RECENT))); setData("seen", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.SEEN))); setData("size", new cfNumberData(Mess.getSize())); setData("lines", new cfNumberData(Mess.getLineCount())); String tmp = Mess.getContentType(); if (tmp.indexOf(";") != -1) tmp = tmp.substring(0, tmp.indexOf(";")); setData("mimetype", new cfStringData(tmp)); // Get the body of the email extractBody(Mess, ADD, attachURI, attachDIR); } catch (Exception E) { return false; } setData("body", ADD); return true; }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null;/*from w w w. ja v a 2 s.com*/ boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null; //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }