List of usage examples for javax.mail Message getRecipients
public abstract Address[] getRecipients(RecipientType type) throws MessagingException;
From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }//from w w w . ja va 2 s . c o m im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0, preferHtmlContent); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withHtmlContent) { // try { String htmlContent = getText(jmm, 0, true); im.setHtmlContent(htmlContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }
From source file:com.ikon.util.MailUtils.java
/** * Convert Mime Message to Mail//from w w w.j av a2s . c o m */ public static Mail messageToMail(Message msg) throws MessagingException, IOException { com.ikon.bean.Mail mail = new com.ikon.bean.Mail(); Calendar receivedDate = Calendar.getInstance(); Calendar sentDate = Calendar.getInstance(); // Can be void if (msg.getReceivedDate() != null) { receivedDate.setTime(msg.getReceivedDate()); } // Can be void if (msg.getSentDate() != null) { sentDate.setTime(msg.getSentDate()); } String body = getText(msg); // log.info("getText: "+body); if (body.charAt(0) == 'H') { mail.setMimeType(MimeTypeConfig.MIME_HTML); } else if (body.charAt(0) == 'T') { mail.setMimeType(MimeTypeConfig.MIME_TEXT); } else { mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED); } String content = body.substring(1); // Need to replace 0x00 because PostgreSQL does not accept string containing 0x00 content = FormatUtil.fixUTF8(content); // Need to remove Unicode surrogate because of MySQL => SQL Error: 1366, SQLState: HY000 content = FormatUtil.trimUnicodeSurrogates(content); mail.setContent(content); if (msg.getFrom().length > 0) { mail.setFrom(MimeUtility.decodeText(msg.getFrom()[0].toString())); } mail.setSize(msg.getSize()); mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject()); mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO))); mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC))); mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC))); mail.setReceivedDate(receivedDate); mail.setSentDate(sentDate); return mail; }
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc/* w w w. jav a 2 s . com*/ */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message's content simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(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 {/*from w w w . j ava2s .com*/ 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:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java
private void _processMails(final String username, final boolean headerOnly) { Long session_id = null;/*w ww . j a v a 2 s.co m*/ boolean should_remove_user_id_processing = false; final GeneralServices.UserAndAccounts userAndAccounts = generalServices.getUserAndAccounts(username); if (!validAccount(userAndAccounts.accounts)) { log.warn("invalid number of accounts"); return; } try { synchronized (userIdsProcessing) { if (userIdsProcessing.contains(userAndAccounts.user.getId())) { // log.warn("account is currently processed"); return; } else { should_remove_user_id_processing = true; userIdsProcessing.add(userAndAccounts.user.getId()); } } final Account account = userAndAccounts.accounts.iterator().next(); // on supprime les mails qui sont plus vieux que la marque et rcuprs il y a plus d'un certain temps // s'il n'y a pas de marque, on ne supprime rien generalServices.removeOldMessages(account); final List<String> msgids = generalServices.getMsgIds(account); final List<String> msgids_older_than_mark = generalServices.getMessageIdsOlderThanMark(account); // final String message_id_mark = generalServices.getMessageIdMark(account); // if (message_id_mark != null) { // // trouver comment se servir de "assert(msgids.contains(message_id_mark));" // if (msgids.contains(message_id_mark) == false) { // log.error("assertion failed"); // System.exit(1); // } // } final MailManager manager = new MailManager(); try { manager.connectToProvider(account.getProvider(), account.getUsername(), account.getPassword()); if (manager.getMessages() == null) log.error("manager.getMessages() == null"); else { final Message[] messages = manager.getMessages(); boolean marked = false; String first_message_id = null; for (int msg_idx = messages.length - 1; (msg_idx >= 0) && (messages.length - msg_idx <= MAX_MAILS_PER_SESSION); msg_idx--) { final Message message = messages[msg_idx]; final String[] msgidHeaders = message.getHeader("Message-Id"); if (msgidHeaders == null || msgidHeaders.length == 0) log.warn("ignoring message without Message-Id"); else { if (first_message_id == null) first_message_id = msgidHeaders[0]; if (!msgids.contains(msgidHeaders[0])) { // this is a new mail final InboxMail inboxMail = new InboxMail(); inboxMail.setUnread(true); inboxMail.setHeaderOnly(headerOnly); // Message-Id inboxMail.setMessageId( GenericTools.truncate(msgidHeaders[0], InboxMail.MAX_MESG_ID_LENGTH)); // From final Address[] from_addr = message.getFrom(); if (from_addr != null) { final StringBuffer from_addresses = new StringBuffer(); for (int i = 0; i < from_addr.length; i++) { if (i > 0) from_addresses.append("; "); from_addresses.append(from_addr[0].toString()); } inboxMail.setFromAddr(GenericTools.truncate(from_addr[0].toString(), InboxMail.MAX_ADDRESS_LENGTH)); } // To final Address[] to_addr = message.getRecipients(RecipientType.TO); if (to_addr != null) { final StringBuffer to_addresses = new StringBuffer(); for (int i = 0; i < to_addr.length; i++) { if (i > 0) to_addresses.append("; "); to_addresses.append(to_addr[0].toString()); } inboxMail.setToAddr(GenericTools.truncate(to_addr[0].toString(), InboxMail.MAX_ADDRESS_LENGTH)); } // Cc final Address[] cc_addr = message.getRecipients(RecipientType.CC); if (cc_addr != null) { final StringBuffer cc_addresses = new StringBuffer(); for (int i = 0; i < cc_addr.length; i++) { if (i > 0) cc_addresses.append("; "); cc_addresses.append(cc_addr[0].toString()); } inboxMail.setCcAddr(GenericTools.truncate(cc_addr[0].toString(), InboxMail.MAX_ADDRESS_LENGTH)); } // Subject if (message.getSubject() != null) inboxMail.setSubject(GenericTools.truncate(message.getSubject(), InboxMail.MAX_SUBJECT_LENGTH)); // Dates inboxMail.setSentDate(message.getSentDate()); inboxMail.setReceivedDate(new java.util.Date()); if (!headerOnly) { // Content try { inboxMail.setContent( GenericTools.truncate(manager.getMessageContentString(message), InboxMail.MAX_CONTENT_LENGTH)); } catch (final IOException ex) { ex.printStackTrace(); } catch (final MessagingException ex) { ex.printStackTrace(); } } // persists entity if (headerOnly) { // header only == objectif : ce qui est dj dans la bote mail du provider ne sera jamais rcupr // le plus rcent mail (on commence par les plus rcents et on marque le 1er), qu'on n'a pas dj vu (car on ne passe ici que pour les mails pas dj vus), est marqu if (!marked) { session_id = generalServices.saveInboxMailMark(account, inboxMail, session_id); marked = true; } else session_id = generalServices.saveInboxMail(account, inboxMail, session_id); } else { session_id = generalServices.saveInboxMail(account, inboxMail, session_id); } } else { // on a dj ce message-id if (headerOnly) { // header only == objectif : ce qui est dj dans la bote mail du provider ne sera jamais rcupr // le plus rcent mail (on commence par les plus rcents et on marque le 1er), qu'on n'a pas dj vu (car on ne passe ici que pour les mails pas dj vus), est marqu if (!marked) { generalServices.saveMark(account, msgidHeaders[0]); marked = true; } } else { // pas en mode header only => on vrifie si on a rencontr la marque // if (msgidHeaders[0].equals(message_id_mark)) { // marque rencontre => on arrte // break; // } // log.debug("msgids_older_than_mark size:" + msgids_older_than_mark.size()); if (msgids_older_than_mark != null && msgids_older_than_mark.contains(msgidHeaders[0])) { // marque rencontre => on arrte break; } } } } } // aprs la boucle sur les messages (donc soit sortie du break car rencontre de la marque, soit boucle termine) // on met donc jour la marque avec le 1er message (le plus rcent rcupr) if (!headerOnly && first_message_id != null) generalServices.saveMark(account, first_message_id); } } catch (final AuthenticationFailedException ex) { log.info("TRACE: authentication failure;" + username + ";" + ex.toString() + ";"); generalServices.saveProviderError(account, ex.toString()); } catch (final MessagingException ex) { ex.printStackTrace(); } finally { try { manager.disconnect(); } catch (final MessagingException ex) { ex.printStackTrace(); } } } finally { synchronized (userIdsProcessing) { if (should_remove_user_id_processing && userIdsProcessing.contains(userAndAccounts.user.getId())) userIdsProcessing.remove(userAndAccounts.user.getId()); } } }
From source file:com.sonicle.webtop.mail.Service.java
private void removeDestination(Message msg, String email) throws MessagingException { Address a[] = null;//from ww w . j av a 2 s . c om try { a = msg.getRecipients(Message.RecipientType.TO); } catch (AddressException exc) { } if (a != null) { msg.setRecipients(Message.RecipientType.TO, removeDestination(a, email)); } try { a = msg.getRecipients(Message.RecipientType.CC); } catch (AddressException exc) { } if (a != null) { msg.setRecipients(Message.RecipientType.CC, removeDestination(a, email)); } try { a = msg.getRecipients(Message.RecipientType.BCC); } catch (AddressException exc) { } if (a != null) { msg.setRecipients(Message.RecipientType.BCC, removeDestination(a, email)); } }
From source file:com.sonicle.webtop.mail.Service.java
public void processDeclineInvitation(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {// w w w.ja v a 2 s . c o m MailAccount account = getAccount(request); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pidattach = request.getParameter("idattach"); try { account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); long newmsguid = Long.parseLong(puidmessage); Message m = mcache.getMessage(newmsguid); HTMLMailData mailData = mcache.getMailData((MimeMessage) m); Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach)); ICalendarRequest ir = new ICalendarRequest(part.getInputStream()); sendICalendarReply(account, ir, ((InternetAddress) m.getRecipients(RecipientType.TO)[0]), PartStat.DECLINED); new JsonResult().printTo(out); } catch (Exception exc) { new JsonResult(false, exc.getMessage()).printTo(out); logger.error("Error sending decline", exc); } }
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;// w w w .j a va2 s .c o m 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; }
From source file:com.sonicle.webtop.mail.Service.java
public void processPortletMail(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { ArrayList<JsPreviewMessage> items = new ArrayList<>(); try {/*www . ja va2 s .com*/ MailAccount account = getAccount(request); String query = ServletUtils.getStringParameter(request, "query", null); int visibleRows = 0; int maxVisibleRows = 20; if (query == null) { String folderId = account.getInboxFolderFullName(); FolderCache fc = account.getFolderCache(folderId); Message msgs[] = fc.getMessages(FolderCache.SORT_BY_DATE, false, true, -1, true, false, null, false); if (msgs != null) fc.fetch(msgs, getMessageFetchProfile(), 0, 50); else msgs = new Message[0]; for (Message msg : msgs) { SonicleIMAPMessage simsg = (SonicleIMAPMessage) msg; InternetAddress iafrom = null; Address vfrom[] = msg.getFrom(); if (vfrom != null && vfrom.length > 0) { Address afrom = vfrom[0]; if (afrom instanceof InternetAddress) { iafrom = (InternetAddress) afrom; } } Address[] rcpts = msg.getRecipients(Message.RecipientType.TO); ArrayList<InternetAddress> tos = new ArrayList<>(); if (rcpts != null) for (Address ato : rcpts) { if (ato instanceof InternetAddress) { InternetAddress iato = (InternetAddress) ato; tos.add(iato); } } String msgtext = ""; if (visibleRows < maxVisibleRows) { msgtext = MailUtils.peekText(simsg); if (msgtext == null) msgtext = ""; else { msgtext = msgtext.trim(); if (msgtext.length() > 100) msgtext = msgtext.substring(0, 100); } ++visibleRows; } String from = iafrom != null ? (iafrom.getPersonal() != null ? iafrom.getPersonal() : iafrom.getAddress()) : ""; String to = ""; if (tos.size() > 0) { boolean first = true; for (InternetAddress iato : tos) { if (!first) to += "; "; to += (iato.getPersonal() != null ? iato.getPersonal() : iato.getAddress()); first = false; } } JsPreviewMessage jsmsg = new JsPreviewMessage(simsg.getUID(), folderId, getInternationalFolderName(account.getFolderCache(folderId)), simsg.getSubject(), from, to, msg.getReceivedDate(), msgtext); items.add(jsmsg); } } else { } new JsonResult(items).printTo(out); } catch (Exception ex) { logger.error("Error in PortletMail", ex); new JsonResult(false, "Error").printTo(out); } }
From source file:com.sonicle.webtop.mail.Service.java
public void processCalendarRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String pcalaction = request.getParameter("calaction"); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pidattach = request.getParameter("idattach"); try {/* w ww . j a v a 2s.co m*/ account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); long newmsguid = Long.parseLong(puidmessage); Message m = mcache.getMessage(newmsguid); HTMLMailData mailData = mcache.getMailData((MimeMessage) m); Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach)); ICalendarRequest ir = new ICalendarRequest(part.getInputStream()); ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true, environment.getProfileId()); if (pcalaction.equals("accept")) { Event ev = cm.addEventFromICal(cm.getBuiltInCalendar().getCalendarId(), ir.getCalendar()); String ekey = cm.getEventInstanceKey(ev.getEventId()); sendICalendarReply(account, ir, ((InternetAddress) m.getRecipients(RecipientType.TO)[0]), PartStat.ACCEPTED); new JsonResult(ekey).printTo(out); } else if (pcalaction.equals("import")) { Event ev = cm.addEventFromICal(cm.getBuiltInCalendar().getCalendarId(), ir.getCalendar()); String ekey = cm.getEventInstanceKey(ev.getEventId()); new JsonResult(ekey).printTo(out); } else if (pcalaction.equals("cancel") || pcalaction.equals("update")) { cm.updateEventFromICal(ir.getCalendar()); new JsonResult().printTo(out); } else { throw new Exception("Unsupported calendar request action : " + pcalaction); } } catch (Exception exc) { new JsonResult(exc).printTo(out); logger.error("Error sending " + pcalaction, exc); } }