List of usage examples for javax.mail Message getSentDate
public abstract Date getSentDate() throws MessagingException;
From source file:com.cws.esolutions.core.utils.EmailUtils.java
/** * Processes and sends an email message as generated by the requesting * application. This method is utilized with a JNDI datasource. * * @param dataSource - The email message * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise * @param authList - If authRequired is true, this must be populated with the auth info * @return List - The list of email messages in the mailstore * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing *//* w w w . j ava 2s. co m*/ public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException { final String methodName = EmailUtils.CNAME + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("dataSource: {}", dataSource); DEBUGGER.debug("authRequired: {}", authRequired); DEBUGGER.debug("authList: {}", authList); } Folder mailFolder = null; Session mailSession = null; Folder archiveFolder = null; List<EmailMessage> emailMessages = null; Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, -24); final Long TIME_PERIOD = cal.getTimeInMillis(); final URLName URL_NAME = (authRequired) ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1)) : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"), Integer.parseInt(dataSource.getProperty("port")), null, null, null); if (DEBUG) { DEBUGGER.debug("timePeriod: {}", TIME_PERIOD); DEBUGGER.debug("URL_NAME: {}", URL_NAME); } try { // Set up mail session mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator()) : Session.getDefaultInstance(dataSource); if (DEBUG) { DEBUGGER.debug("mailSession: {}", mailSession); } if (mailSession == null) { throw new MessagingException("Unable to configure email services"); } mailSession.setDebug(DEBUG); Store mailStore = mailSession.getStore(URL_NAME); mailStore.connect(); if (DEBUG) { DEBUGGER.debug("mailStore: {}", mailStore); } if (!(mailStore.isConnected())) { throw new MessagingException("Failed to connect to mail service. Cannot continue."); } mailFolder = mailStore.getFolder("inbox"); archiveFolder = mailStore.getFolder("archive"); if (!(mailFolder.exists())) { throw new MessagingException("Requested folder does not exist. Cannot continue."); } mailFolder.open(Folder.READ_WRITE); if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) { throw new MessagingException("Failed to open requested folder. Cannot continue"); } if (!(archiveFolder.exists())) { archiveFolder.create(Folder.HOLDS_MESSAGES); } Message[] mailMessages = mailFolder.getMessages(); if (mailMessages.length == 0) { throw new MessagingException("No messages were found in the provided store."); } emailMessages = new ArrayList<EmailMessage>(); for (Message message : mailMessages) { if (DEBUG) { DEBUGGER.debug("MailMessage: {}", message); } // validate the message here String messageId = message.getHeader("Message-ID")[0]; Long messageDate = message.getReceivedDate().getTime(); if (DEBUG) { DEBUGGER.debug("messageId: {}", messageId); DEBUGGER.debug("messageDate: {}", messageDate); } // only get emails for the last 24 hours // this should prevent us from pulling too // many emails if (messageDate >= TIME_PERIOD) { // process it Multipart attachment = (Multipart) message.getContent(); Map<String, InputStream> attachmentList = new HashMap<String, InputStream>(); for (int x = 0; x < attachment.getCount(); x++) { BodyPart bodyPart = attachment.getBodyPart(x); if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) { continue; } attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream()); } List<String> toList = new ArrayList<String>(); List<String> ccList = new ArrayList<String>(); List<String> bccList = new ArrayList<String>(); List<String> fromList = new ArrayList<String>(); for (Address from : message.getFrom()) { fromList.add(from.toString()); } if ((message.getRecipients(RecipientType.TO) != null) && (message.getRecipients(RecipientType.TO).length != 0)) { for (Address to : message.getRecipients(RecipientType.TO)) { toList.add(to.toString()); } } if ((message.getRecipients(RecipientType.CC) != null) && (message.getRecipients(RecipientType.CC).length != 0)) { for (Address cc : message.getRecipients(RecipientType.CC)) { ccList.add(cc.toString()); } } if ((message.getRecipients(RecipientType.BCC) != null) && (message.getRecipients(RecipientType.BCC).length != 0)) { for (Address bcc : message.getRecipients(RecipientType.BCC)) { bccList.add(bcc.toString()); } } EmailMessage emailMessage = new EmailMessage(); emailMessage.setMessageTo(toList); emailMessage.setMessageCC(ccList); emailMessage.setMessageBCC(bccList); emailMessage.setEmailAddr(fromList); emailMessage.setMessageAttachments(attachmentList); emailMessage.setMessageDate(message.getSentDate()); emailMessage.setMessageSubject(message.getSubject()); emailMessage.setMessageBody(message.getContent().toString()); emailMessage.setMessageSources(message.getHeader("Received")); if (DEBUG) { DEBUGGER.debug("emailMessage: {}", emailMessage); } emailMessages.add(emailMessage); if (DEBUG) { DEBUGGER.debug("emailMessages: {}", emailMessages); } } // archive it archiveFolder.open(Folder.READ_WRITE); if (archiveFolder.isOpen()) { mailFolder.copyMessages(new Message[] { message }, archiveFolder); message.setFlag(Flags.Flag.DELETED, true); } } } catch (IOException iox) { throw new MessagingException(iox.getMessage(), iox); } catch (MessagingException mex) { throw new MessagingException(mex.getMessage(), mex); } finally { try { if ((mailFolder != null) && (mailFolder.isOpen())) { mailFolder.close(true); } if ((archiveFolder != null) && (archiveFolder.isOpen())) { archiveFolder.close(false); } } catch (MessagingException mx) { ERROR_RECORDER.error(mx.getMessage(), mx); } } return emailMessages; }
From source file:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java
/** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above.//from w ww .j a va 2 s . c o m *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { List<String> requiredMetadata = new ArrayList<String>(); for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode sn = spec.getChild(i); if (sn.getType().equals(EmailConfig.NODE_METADATA)) { String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME); requiredMetadata.add(metadataAttribute); } } // Keep a cached set of open folders Map<String, Folder> openFolders = new HashMap<String, Folder>(); try { for (String documentIdentifier : documentIdentifiers) { String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change. // Check if we need to index if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) continue; String compositeID = documentIdentifier; String version = versionString; String folderName = extractFolderNameFromDocumentIdentifier(compositeID); String id = extractEmailIDFromDocumentIdentifier(compositeID); String errorCode = null; String errorDesc = null; Long fileLengthLong = null; long startTime = System.currentTimeMillis(); try { try { Folder folder = openFolders.get(folderName); if (folder == null) { getSession(); OpenFolderThread oft = new OpenFolderThread(session, folderName); oft.start(); folder = oft.finishUp(); openFolders.put(folderName, folder); } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'"); SearchTerm messageIDTerm = new MessageIDTerm(id); getSession(); SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm); smt.start(); Message[] message = smt.finishUp(); String msgURL = makeDocumentURI(urlTemplate, folderName, id); Message msg = null; for (Message msg2 : message) { msg = msg2; } if (msg == null) { // email was not found activities.deleteDocument(id); continue; } if (!activities.checkURLIndexable(msgURL)) { errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('" + msgURL + "')"; activities.noDocument(id, version); continue; } long fileLength = msg.getSize(); if (!activities.checkLengthIndexable(fileLength)) { errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length (" + fileLength + ")"; activities.noDocument(id, version); continue; } Date sentDate = msg.getSentDate(); if (!activities.checkDateIndexable(sentDate)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of date (" + sentDate + ")"; activities.noDocument(id, version); continue; } String mimeType = "text/plain"; if (!activities.checkMimeTypeIndexable(mimeType)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of mime type ('" + mimeType + "')"; activities.noDocument(id, version); continue; } RepositoryDocument rd = new RepositoryDocument(); rd.setFileName(msg.getFileName()); rd.setMimeType(mimeType); rd.setCreatedDate(sentDate); rd.setModifiedDate(sentDate); String subject = StringUtils.EMPTY; for (String metadata : requiredMetadata) { if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) { Address[] to = msg.getRecipients(Message.RecipientType.TO); String[] toStr = new String[to.length]; int j = 0; for (Address address : to) { toStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, toStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) { Address[] from = msg.getFrom(); String[] fromStr = new String[from.length]; int j = 0; for (Address address : from) { fromStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, fromStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) { subject = msg.getSubject(); rd.addField(EmailConfig.EMAIL_SUBJECT, subject); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) { Multipart mp = (Multipart) msg.getContent(); for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition == null)) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags } } } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) { rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString()); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) { Multipart mp = (Multipart) msg.getContent(); if (mp != null) { String[] encoding = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { encoding[k] = part.getFileName().split("\\?")[1]; } } rd.addField(EmailConfig.ENCODING_FIELD, encoding); } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) { Multipart mp = (Multipart) msg.getContent(); String[] MIMEType = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { MIMEType[k] = part.getContentType(); } } rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType); } } InputStream is = msg.getInputStream(); try { rd.setBinary(is, fileLength); activities.ingestDocumentWithException(id, version, msgURL, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleMessagingException(e, "processing email"); } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(e, "processing email"); throw new ManifoldCFException(e.getMessage(), e); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong, documentIdentifier, errorCode, errorDesc, null); } } } finally { for (Folder f : openFolders.values()) { try { CloseFolderThread cft = new CloseFolderThread(session, f); cft.start(); cft.finishUp(); } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { handleMessagingException(e, "closing folders"); } } } }
From source file:org.nuclos.server.ruleengine.RuleInterface.java
/** * * @param pop3Host/*from ww w . j a v 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:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java
private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session) throws MessagingException, IOException, ScanException, PolicyException { // Prepare subject String subject = msg.getSubject(); if (!StringUtils.isBlank(subject)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(subject, policy); subject = cr.getCleanHTML();/*from ww w . j a v a 2 s. c o m*/ } // Prepare content if requested EmailMessageContent msgContent = null; // default... if (populateContent) { // Defend against the dreaded: "Unable to load BODYSTRUCTURE" try { msgContent = getMessageContent(msg.getContent(), msg.getContentType()); } catch (MessagingException me) { // We are unable to read digitally-signed messages (perhaps // others?) in the API-standard way; we have to use a work around. // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug // Logging as DEBUG because this behavior is known & expected. log.debug("Difficulty reading a message (digitally signed?). Attempting workaround..."); try { MimeMessage mm = (MimeMessage) msg; ByteArrayOutputStream bos = new ByteArrayOutputStream(); mm.writeTo(bos); bos.close(); SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray()); MimeMessage copy = new MimeMessage(session, bis); bis.close(); msgContent = getMessageContent(copy.getContent(), copy.getContentType()); } catch (Throwable t) { log.error("Failed to read message body", t); msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false); } } // Sanitize with AntiSamy String content = msgContent.getContentString(); if (!StringUtils.isBlank(content)) { AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(content, policy); content = cr.getCleanHTML(); } msgContent.setContentString(content); } int messageNumber = msg.getMessageNumber(); // Prepare the UID if present String uid = null; // default if (msg.getFolder() instanceof UIDFolder) { uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg)); } Address[] addr = msg.getFrom(); String sender = getFormattedAddresses(addr); Date sentDate = msg.getSentDate(); boolean unread = !msg.isSet(Flag.SEEN); boolean answered = msg.isSet(Flag.ANSWERED); boolean deleted = msg.isSet(Flag.DELETED); // Defend against the dreaded: "Unable to load BODYSTRUCTURE" boolean multipart = false; // sensible default; String contentType = null; // sensible default try { multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN); contentType = msg.getContentType(); } catch (MessagingException me) { // Message was digitally signed and we are unable to read it; // logging as DEBUG because this issue is known/expected, and // because the user's experience is in no way affected (at this point) log.debug("Message content unavailable (digitally signed?); " + "message will appear in the preview table correctly, " + "but the body will not be viewable"); log.trace(me.getMessage(), me); } String to = getTo(msg); String cc = getCc(msg); String bcc = getBcc(msg); return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart, contentType, msgContent, to, cc, bcc); }
From source file:org.accesointeligente.server.robots.ResponseChecker.java
public void connectAndCheck() { if (ApplicationProperties.getProperty("email.server") == null || ApplicationProperties.getProperty("email.user") == null || ApplicationProperties.getProperty("email.password") == null || ApplicationProperties.getProperty("email.folder") == null || ApplicationProperties.getProperty("email.failfolder") == null || ApplicationProperties.getProperty("attachment.directory") == null || ApplicationProperties.getProperty("attachment.baseurl") == null) { logger.error("Properties are not defined!"); return;/*from w w w . j a v a2s . com*/ } org.hibernate.Session hibernate = null; try { session = Session.getInstance(props, null); store = session.getStore("imaps"); store.connect(ApplicationProperties.getProperty("email.server"), ApplicationProperties.getProperty("email.user"), ApplicationProperties.getProperty("email.password")); Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder")); Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder")); inbox.open(Folder.READ_WRITE); for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) { try { logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject()); remoteIdentifiers = null; messageBody = null; remoteIdentifiers = new HashSet<String>(); if (message.getSubject() != null) { Matcher matcher = pattern.matcher(message.getSubject()); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } Object content = message.getContent(); if (content instanceof Multipart) { Multipart mp = (Multipart) message.getContent(); logger.info("Email content type is Multipart, each part of " + mp.getCount() + " will be processed"); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); logger.info("Part: " + (i + 1) + " of " + mp.getCount()); processPart(part); } } else if (content instanceof String) { logger.info("Email content type is String"); messageBody = (String) content; Matcher matcher; StringTokenizer tokenizer = new StringTokenizer(messageBody); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); matcher = pattern.matcher(token); if (matcher.matches()) { remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2), Integer.parseInt(matcher.group(3)))); } } } else { logger.info("Email content type isn't String or Multipart"); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); continue; } Boolean requestFound = false; Matcher matcher = htmlPattern.matcher(messageBody); if (matcher.find()) { messageBody = htmlToString(messageBody); } logger.info("Searching for Request Remote Identifier"); for (String remoteIdentifier : remoteIdentifiers) { hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); Criteria criteria = hibernate.createCriteria(Request.class); criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier)); Request request = (Request) criteria.uniqueResult(); hibernate.getTransaction().commit(); if (request != null) { logger.info("Request found for Remote Identifier: " + remoteIdentifier); Response response; // If the attachments haven't been used, use them. Otherwise, copy them. if (!requestFound) { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } else { response = createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); } hibernate = HibernateUtil.getSession(); hibernate.beginTransaction(); response.setRequest(request); request.setStatus(RequestStatus.RESPONDED); request.setExpired(RequestExpireType.WITHRESPONSE); request.setResponseDate(new Date()); hibernate.update(request); hibernate.update(response); hibernate.getTransaction().commit(); requestFound = true; } } if (!requestFound) { logger.info("Request not found"); createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(), messageBody); message.setFlag(Flag.SEEN, false); inbox.copyMessages(new Message[] { message }, failbox); message.setFlag(Flag.DELETED, true); inbox.expunge(); } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } } } catch (Exception e) { if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) { hibernate.getTransaction().rollback(); } logger.error(e.getMessage(), e); } }
From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java
private void _processMails(final String username, final boolean headerOnly) { Long session_id = null;/*from ww w . jav a 2 s.c o 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:edu.stanford.muse.email.EmailFetcherStats.java
/** * recursively processes attachments, fetching and saving it if needed * parses the given part p, and adds it to hte attachmentsList. * in some cases, like a text/html type without a filename, we instead append it to the textlist * @throws MessagingException/*from w ww. j av a 2 s .c o m*/ */ private void handleAttachments(int idx, Message m, Part p, List<String> textList, List<Blob> attachmentsList) throws MessagingException { String ct = null; if (!(m instanceof MimeMessage)) { Exception e = new IllegalArgumentException("Not a MIME message!"); e.fillInStackTrace(); log.warn(Util.stackTrace(e)); return; } String filename = null; try { filename = p.getFileName(); } catch (Exception e) { // seen this happen with: // Folders__gmail-sent Message #12185 Expected ';', got "Message" // javax.mail.internet.ParseException: Expected ';', got "Message" dataErrors.add("Unable to read attachment name: " + folder_name() + " Message# " + idx); return; } String sanitizedFName = Util.sanitizeFolderName(emailStore.getAccountID() + "." + folder_name()); if (filename == null) { String tempFname = sanitizedFName + "." + idx; dataErrors.add("attachment filename is null for " + sanitizedFName + " Message#" + idx + " assigning it the name: " + tempFname); if (p.isMimeType("text/html")) { try { log.info("Turning message " + sanitizedFName + " Message#" + idx + " into text although it is an attachment"); String html = (String) p.getContent(); String text = Util.unescapeHTML(html); org.jsoup.nodes.Document doc = Jsoup.parse(text); StringBuilder sb = new StringBuilder(); HTMLUtils.extractTextFromHTML(doc.body(), sb); textList.add(sb.toString()); return; } catch (Exception e) { Util.print_exception("Error reading contents of text/html multipart without a filename!", e, log); return; } } filename = tempFname; } // Replacing any of the disallowed filename characters (\/:*?"<>|&) to _ // (note: & causes problems with URLs for serveAttachment etc, so it's also replaced) String newFilename = Util.sanitizeFileName(filename); // Updating filename if it's changed after sanitizing. if (!newFilename.equals(filename)) { log.info("Filename changed from " + filename + " to " + newFilename); filename = newFilename; } try { ct = p.getContentType(); if (filename.indexOf(".") < 0) // no ext in filename... let's fix it if possible { // Using startsWith instead of equals because sometimes the ct has crud beyond the image/jpeg;...crud.... // Below are the most common file types, more type can be added if needed // Most common APPLICATION TYPE if (ct.startsWith("application/pdf")) filename = filename + ".pdf"; if (ct.startsWith("application/zip")) filename = filename + ",zip"; // Most common IMAGE TYPE if (ct.startsWith("image/jpeg")) filename = filename + ".jpg"; if (ct.startsWith("image/gif")) filename = filename + ".gif"; if (ct.startsWith("image/png")) filename = filename + ".png"; // Most Common VIDEO TYPE if (ct.startsWith("video/x-ms-wmv")) filename = filename + ".wmv"; // Most Common AUDIO TYPE if (ct.startsWith("audio/mpeg")) filename = filename + ".mp3"; if (ct.startsWith("audio/mp4")) filename = filename + ".mp4"; // Most Common TEXT TYPE if (ct.startsWith("text/html")) filename = filename + ".html"; // Windows Office if (ct.startsWith("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) //Word filename = filename + ".docx"; if (ct.startsWith("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) //Excel filename = filename + ".xlsx"; if (ct.startsWith("application/vnd.openxmlformats-officedocument.presentationml.presentation")) //PowerPoint filename = filename + ".pptx"; } // retain only up to first semi-colon; often ct is something like text/plain; name="filename"' we don't want to log the filename int x = ct.indexOf(";"); if (x >= 0) ct = ct.substring(0, x); log.info("Attachment content type: " + ct + " filename = " + Util.blurKeepingExtension(filename)); } catch (Exception pex) { dataErrors.add("Can't read CONTENT-TYPE: " + ct + " filename:" + filename + " size = " + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\n Exception: " + pex + "\n" + Util.stackTrace(pex)); return; } // if (filename == null && !p.isMimeType("text/html") && !p.isMimeType("message/partial")) // expected not to have a filename with mime type text/html // log.warn ("Attachment filename is null: " + Util.stackTrace()); boolean success = true; // the size passed in here is the part size, which is not really the binary blob size. // when we read the stream below in blobStore.add(), we'll set it again to the binary blob size Blob b = new EmailAttachmentBlob(filename, p.getSize(), (MimeMessage) m, p); if (fetchConfig.downloadAttachments) { // this containment check is only on the basis of file name and size currently, // not on the actual hash if (archive.getBlobStore().contains(b)) { log.debug("Cache hit! " + b); } else { try { if (filename.endsWith(".tif")) log.info("Fetching attachment..." + Util.blurKeepingExtension(filename)); // performance critical! use large buffer! currently 256KB // stream will be closed by callee long start = System.currentTimeMillis(); long nBytes = archive.getBlobStore().add(b, new BufferedInputStream(p.getInputStream(), 256 * 1024)); long end = System.currentTimeMillis(); if (nBytes != -1) { long diff = end - start; String s = "attachment size " + nBytes + " bytes, fetched in " + diff + " millis"; if (diff > 0) s += " (" + (nBytes / diff) + " KB/s)"; log.info(s); } Util.ASSERT(archive.getBlobStore().contains(b)); } catch (IOException ioe) { success = false; dataErrors.add("WARNING: Unable to fetch attachment: filename: " + filename + " size = " + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\nException: " + ioe); ioe.printStackTrace(System.out); } } if (success) { attachmentsList.add(b); /// generate thumbnail only if not already cached try { archive.getBlobStore().generate_thumbnail(b); // supplement } catch (IOException ioe) { log.warn("failed to create thumbnail, filename: " + filename + " size = " + p.getSize() + " subject: " + m.getSubject() + " Date : " + m.getSentDate().toString() + "\nException: " + ioe); ioe.printStackTrace(System.out); } } } }
From source file:com.sonicle.webtop.mail.Service.java
private String getForwardBody(Message msg, String body, int format, boolean isHtml, String fromtitle, String totitle, String cctitle, String datetitle, String subjecttitle) throws MessagingException { UserProfile profile = environment.getProfile(); Locale locale = profile.getLocale(); String msgSubject = msg.getSubject(); if (msgSubject == null) { msgSubject = ""; }/*from w w w .ja va 2 s .c o m*/ msgSubject = MailUtils.htmlescape(msgSubject); Address ad[] = msg.getFrom(); String msgFrom = ""; if (ad != null) { msgFrom = isHtml ? getHTMLDecodedAddress(ad[0]) : getDecodedAddress(ad[0]); } java.util.Date dt = msg.getSentDate(); String msgDate = ""; if (dt != null) { msgDate = DateFormat.getDateTimeInstance(java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale) .format(dt); } ad = msg.getRecipients(Message.RecipientType.TO); String msgTo = null; if (ad != null) { msgTo = ""; for (int j = 0; j < ad.length; ++j) { msgTo += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " "; } } ad = msg.getRecipients(Message.RecipientType.CC); String msgCc = null; if (ad != null) { msgCc = ""; for (int j = 0; j < ad.length; ++j) { msgCc += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " "; } } StringBuffer sb = new StringBuffer(); String cr = "\n"; if (format != SimpleMessage.FORMAT_TEXT) { cr = "<BR>"; } if (format != SimpleMessage.FORMAT_HTML) { if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append("<TT>"); } sb.append(cr + cr + cr + "----------------------------------------------------------------------------------" + cr + cr); sb.append(fromtitle + ": " + msgFrom + cr); if (msgTo != null) { sb.append(totitle + ": " + msgTo + cr); } if (msgCc != null) { sb.append(cctitle + ": " + msgCc + cr); } sb.append(datetitle + ": " + msgDate + cr); sb.append(subjecttitle + ": " + msgSubject + cr + cr); if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append("</TT>"); } } else { sb.append(cr + "<HR>" + cr + cr); sb.append("<font face='Arial, Helvetica, sans-serif' size=2>"); sb.append("<B>" + fromtitle + ":</B> " + msgFrom + "<BR>"); if (msgTo != null) { sb.append("<B>" + totitle + ":</B> " + msgTo + "<BR>"); } if (msgCc != null) { sb.append("<B>" + cctitle + ":</B> " + msgCc + "<BR>"); } sb.append("<B>" + datetitle + ":</B> " + msgDate + "<BR>"); sb.append("<B>" + subjecttitle + ":</B> " + msgSubject + "<BR>"); sb.append("</font><br>" + cr); } // Prepend "> " for each line in the body // if (body != null) { if (format == SimpleMessage.FORMAT_HTML) { // sb.append("<TABLE border=0 width='100%'><TR><td width=2 bgcolor=#000088></td><td width=2></td><td>"); // sb.append("<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>"); } if (!isHtml) { if (format == SimpleMessage.FORMAT_PREFORMATTED) { // sb.append("<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>"); sb.append("<tt>"); } StringTokenizer st = new StringTokenizer(body, "\n", true); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equals("\n")) { sb.append(cr); } else { if (format == SimpleMessage.FORMAT_TEXT) { sb.append("> "); } //sb.append(MailUtils.htmlescape(token)); sb.append(token); } } if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append("</tt>"); // sb.append("</BLOCKQUOTE>"); } } else { //sb.append(getBodyInnerHtml(body)); sb.append(body); } if (format == SimpleMessage.FORMAT_HTML) { // sb.append("</td></tr></table>"); // sb.append("</BLOCKQUOTE>"); } } return sb.toString(); }
From source file:com.sonicle.webtop.mail.Service.java
private String getReplyBody(Message msg, String body, int format, boolean isHtml, String fromtitle, String totitle, String cctitle, String datetitle, String subjecttitle, ArrayList<String> attnames) throws MessagingException { UserProfile profile = environment.getProfile(); Locale locale = profile.getLocale(); String msgSubject = msg.getSubject(); if (msgSubject == null) { msgSubject = ""; }// w w w .j a v a 2s . c o m msgSubject = MailUtils.htmlescape(msgSubject); Address ad[] = msg.getFrom(); String msgFrom = ""; if (ad != null) { msgFrom = isHtml ? getHTMLDecodedAddress(ad[0]) : getDecodedAddress(ad[0]); } java.util.Date dt = msg.getSentDate(); String msgDate = ""; if (dt != null) { msgDate = DateFormat.getDateTimeInstance(java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale) .format(dt); } ad = msg.getRecipients(Message.RecipientType.TO); String msgTo = null; if (ad != null) { msgTo = ""; for (int j = 0; j < ad.length; ++j) { msgTo += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " "; } } ad = msg.getRecipients(Message.RecipientType.CC); String msgCc = null; if (ad != null) { msgCc = ""; for (int j = 0; j < ad.length; ++j) { msgCc += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " "; } } // /*String sfrom = ""; try { if (msg.getFrom() != null) { InternetAddress ia = (InternetAddress) msg.getFrom()[0]; String personal = ia.getPersonal(); String mail = ia.getAddress(); if (personal == null || personal.equals(mail)) { sfrom = mail; } else { sfrom = personal + " <" + mail + ">"; } } } catch (Exception exc) { }*/ StringBuffer sb = new StringBuffer(); String cr = "\n"; if (format != SimpleMessage.FORMAT_TEXT) { cr = "<BR>"; } if (format != SimpleMessage.FORMAT_HTML) { if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append("<TT>"); } sb.append(cr + cr + cr + "----------------------------------------------------------------------------------" + cr + cr); sb.append(fromtitle + ": " + msgFrom + cr); if (msgTo != null) { sb.append(totitle + ": " + msgTo + cr); } if (msgCc != null) { sb.append(cctitle + ": " + msgCc + cr); } sb.append(datetitle + ": " + msgDate + cr); sb.append(subjecttitle + ": " + msgSubject + cr + cr); if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append("</TT>"); } } else { sb.append(cr + "<HR>" + cr + cr); sb.append("<font face='Arial, Helvetica, sans-serif' size=2>"); sb.append("<B>" + fromtitle + ":</B> " + msgFrom + "<BR>"); if (msgTo != null) { sb.append("<B>" + totitle + ":</B> " + msgTo + "<BR>"); } if (msgCc != null) { sb.append("<B>" + cctitle + ":</B> " + msgCc + "<BR>"); } sb.append("<B>" + datetitle + ":</B> " + msgDate + "<BR>"); sb.append("<B>" + subjecttitle + ":</B> " + msgSubject + "<BR>"); sb.append("</font><br>" + cr); } // Prepend "> " for each line in the body // if (body != null) { if (format == SimpleMessage.FORMAT_HTML) { // sb.append("<TABLE border=0 width='100%'><TR><td width=2 bgcolor=#000088></td><td width=2></td><td>"); sb.append( "<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>"); } if (!isHtml) { if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append( "<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>"); sb.append("<tt>"); } StringTokenizer st = new StringTokenizer(body, "\n", true); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equals("\n")) { sb.append(cr); } else { if (format == SimpleMessage.FORMAT_TEXT) { sb.append("> "); } //sb.append(MailUtils.htmlescape(token)); sb.append(token); } } if (format == SimpleMessage.FORMAT_PREFORMATTED) { sb.append("</tt>"); sb.append("</BLOCKQUOTE>"); } } else { /* //String ubody = body.toUpperCase(); while (true) { int ix1 = StringUtils.indexOfIgnoreCase(body,"<BODY"); if (ix1 < 0) { break; } int ix2 = StringUtils.indexOfIgnoreCase(body,">", ix1 + 1); if (ix2 < 0) { ix2 = ix1 + 4; } int ix3 = StringUtils.indexOfIgnoreCase(body,"</BODY", ix2 + 1); if (ix3 > 0) { body = body.substring(ix2 + 1, ix3); } else { body = body.substring(ix2 + 1); } } //body=removeStartEndTag(body,unwantedTags); */ sb.append(body); } htmlAppendAttachmentNames(sb, attnames); if (format == SimpleMessage.FORMAT_HTML) { // sb.append("</td></tr></table>"); sb.append("</BLOCKQUOTE>"); } } return sb.toString(); }
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 ww . j a v a 2s . co 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; }