List of usage examples for javax.mail.internet ParseException getMessage
public String getMessage()
From source file:com.medsavant.mailer.Mail.java
public static void main(String[] args) throws IOException { CommandLineParser parser = new GnuParser(); Options ops = getOptions();//w w w . j a v a 2 s .c o m try { // parse the command line arguments CommandLine line = parser.parse(ops, args); // print help if (line.hasOption('h') || line.getOptions().length == 0) { printHelp(); return; } // parse args String email = null; String emailPass = null; String mailingList = null; String subject = null; String htmlFile = null; for (Option o : line.getOptions()) { switch (o.getOpt().charAt(0)) { case 's': subject = o.getValue(); break; case 'e': htmlFile = o.getValue(); break; case 'u': email = o.getValue(); break; case 'p': emailPass = o.getValue(); break; case 'l': mailingList = o.getValue(); break; } } setMailCredentials(email, emailPass, host, port); String text = readFileIntoString(new File(htmlFile)); sendEmail(mailingList, subject, text); } catch (org.apache.commons.cli.ParseException exp) { printHelp(); // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } }
From source file:org.apache.tika.server.resource.TikaResource.java
public static String detectFilename(MultivaluedMap<String, String> httpHeaders) { String disposition = httpHeaders.getFirst("Content-Disposition"); if (disposition != null) { try {/*from ww w . j a v a2s. c o m*/ ContentDisposition c = new ContentDisposition(disposition); // only support "attachment" dispositions if ("attachment".equals(c.getDisposition())) { String fn = c.getParameter("filename"); if (fn != null) { return fn; } } } catch (ParseException e) { // not a valid content-disposition field LOG.warn("Parse exception {} determining content disposition", e.getMessage(), e); } } // this really should not be used, since it's not an official field return httpHeaders.getFirst("File-Name"); }
From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java
protected String getFileName(Part part) throws MessagingException { String fileName = part.getFileName(); if (fileName == null) { try {/*from ww w . j a v a2s .c o m*/ ContentType type = new ContentType(part.getContentType()); fileName = type.getParameter("name"); } catch (ParseException e) { logger.error(e.getMessage(), e); } } return fileName; }
From source file:org.silverpeas.components.mailinglist.service.job.MailProcessor.java
/** * Analyze the part to check if it is an attachment, a base64 encoded file or some text. * @param part the part to be analyzed./*from ww w . ja v a2 s . co m*/ * @return true if it is some text - false otherwise. * @throws MessagingException */ protected boolean isTextPart(Part part) throws MessagingException { String disposition = part.getDisposition(); if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) { try { ContentType type = new ContentType(part.getContentType()); return "text".equalsIgnoreCase(type.getPrimaryType()); } catch (ParseException e) { logger.error(e.getMessage(), e); } } else if (Part.INLINE.equals(disposition)) { try { ContentType type = new ContentType(part.getContentType()); return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null; } catch (ParseException e) { logger.error(e.getMessage(), e); } } return false; }
From source file:org.esxx.Response.java
public void writeResult(OutputStream out) throws IOException { try {/*from w w w .j a v a2 s .com*/ writeObject(resultObject, new ContentType(guessContentType()), out); } catch (javax.mail.internet.ParseException ex) { throw new IOException("Invalid content-type: " + ex.getMessage(), ex); } }
From source file:org.apache.axis.attachments.MultiPartRelatedInputStream.java
/** * Create a new Multipart stream./*w w w .ja v a 2s . co m*/ * @param contentType the string that holds the contentType * @param stream the true input stream from where the source * * @throws org.apache.axis.AxisFault if the stream could not be created */ public MultiPartRelatedInputStream(String contentType, java.io.InputStream stream) throws org.apache.axis.AxisFault { super(null); // don't cache this stream. if (!(stream instanceof BufferedInputStream)) { stream = new BufferedInputStream(stream); } try { // First find the start and boundary parameters. There are real weird rules regard what // can be in real headers what needs to be escaped etc let mail parse it. javax.mail.internet.ContentType ct = new javax.mail.internet.ContentType(contentType); String rootPartContentId = ct.getParameter("start"); // Get the root part content. if (rootPartContentId != null) { rootPartContentId = rootPartContentId.trim(); if (rootPartContentId.startsWith("<")) { rootPartContentId = rootPartContentId.substring(1); } if (rootPartContentId.endsWith(">")) { rootPartContentId = rootPartContentId.substring(0, rootPartContentId.length() - 1); } } if (ct.getParameter("boundary") != null) { String boundaryStr = "--" + ct.getParameter("boundary"); // The boundary with -- add as always the case. // if start is null then the first attachment is the rootpart // First read the start boundary -- this is done with brute force since the servlet may swallow the crlf between headers. // after this we use the more efficient boundarydelimeted stream. There should never be any data here anyway. byte[][] boundaryMarker = new byte[2][boundaryStr.length() + 2]; IOUtils.readFully(stream, boundaryMarker[0]); boundary = (boundaryStr + "\r\n").getBytes("US-ASCII"); int current = 0; // This just goes brute force one byte at a time to find the first boundary. // in most cases this just a crlf. for (boolean found = false; !found; ++current) { if (!(found = java.util.Arrays.equals(boundaryMarker[current & 0x1], boundary))) { System.arraycopy(boundaryMarker[current & 0x1], 1, boundaryMarker[(current + 1) & 0x1], 0, boundaryMarker[0].length - 1); if (stream.read(boundaryMarker[(current + 1) & 0x1], boundaryMarker[0].length - 1, 1) < 1) { throw new org.apache.axis.AxisFault( Messages.getMessage("mimeErrorNoBoundary", new String(boundary))); } } } // after the first boundary each boundary will have a cr lf at the beginning since after the data in any part there // is a cr lf added to put the boundary at the begining of a line. boundaryStr = "\r\n" + boundaryStr; boundary = boundaryStr.getBytes("US-ASCII"); } else { // Since boundary is not specified, we try to find one. for (boolean found = false; !found;) { boundary = readLine(stream); if (boundary == null) throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorNoBoundary", "--")); found = boundary.length > 4 && boundary[2] == '-' && boundary[3] == '-'; } } // create the boundary delmited stream. boundaryDelimitedStream = new org.apache.axis.attachments.BoundaryDelimitedStream(stream, boundary, 1024); // Now read through all potential streams until we have found the root part. String contentTransferEncoding = null; do { contentId = null; contentLocation = null; contentTransferEncoding = null; // Read this attachments headers from the stream. javax.mail.internet.InternetHeaders headers = new javax.mail.internet.InternetHeaders( boundaryDelimitedStream); // Use java mail utility to read through the headers. contentId = headers.getHeader(HTTPConstants.HEADER_CONTENT_ID, null); // Clean up the headers and remove any < > if (contentId != null) { contentId = contentId.trim(); if (contentId.startsWith("<")) { contentId = contentId.substring(1); } if (contentId.endsWith(">")) { contentId = contentId.substring(0, contentId.length() - 1); } contentId = contentId.trim(); // if (!contentId.startsWith("cid:")) { // contentId = // "cid:" // + contentId; // make sure its identified as cid // } } contentLocation = headers.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION, null); if (contentLocation != null) { contentLocation = contentLocation.trim(); if (contentLocation.startsWith("<")) { contentLocation = contentLocation.substring(1); } if (contentLocation.endsWith(">")) { contentLocation = contentLocation.substring(0, contentLocation.length() - 1); } contentLocation = contentLocation.trim(); } contentType = headers.getHeader(HTTPConstants.HEADER_CONTENT_TYPE, null); if (contentType != null) { contentType = contentType.trim(); } contentTransferEncoding = headers.getHeader(HTTPConstants.HEADER_CONTENT_TRANSFER_ENCODING, null); if (contentTransferEncoding != null) { contentTransferEncoding = contentTransferEncoding.trim(); } java.io.InputStream decodedStream = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { decodedStream = MimeUtility.decode(decodedStream, contentTransferEncoding); } if ((rootPartContentId != null) && !rootPartContentId.equals(contentId)) { // This is a part that has come in prior to the root part. Need to buffer it up. javax.activation.DataHandler dh = new javax.activation.DataHandler( new org.apache.axis.attachments.ManagedMemoryDataSource(decodedStream, MAX_CACHED, contentType, true)); AttachmentPart ap = new AttachmentPart(dh); if (contentId != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_ID, contentId); } if (contentLocation != null) { ap.setMimeHeader(HTTPConstants.HEADER_CONTENT_LOCATION, contentLocation); } for (java.util.Enumeration en = headers.getNonMatchingHeaders( new String[] { HTTPConstants.HEADER_CONTENT_ID, HTTPConstants.HEADER_CONTENT_LOCATION, HTTPConstants.HEADER_CONTENT_TYPE }); en.hasMoreElements();) { javax.mail.Header header = (javax.mail.Header) en.nextElement(); String name = header.getName(); String value = header.getValue(); if ((name != null) && (value != null)) { name = name.trim(); if (name.length() != 0) { ap.addMimeHeader(name, value); } } } addPart(contentId, contentLocation, ap); boundaryDelimitedStream = boundaryDelimitedStream.getNextStream(); // Gets the next stream. } } while ((null != boundaryDelimitedStream) && (rootPartContentId != null) && !rootPartContentId.equals(contentId)); if (boundaryDelimitedStream == null) { throw new org.apache.axis.AxisFault(Messages.getMessage("noRoot", rootPartContentId)); } soapStreamBDS = boundaryDelimitedStream; if ((contentTransferEncoding != null) && (0 != contentTransferEncoding.length())) { soapStream = MimeUtility.decode(boundaryDelimitedStream, contentTransferEncoding); } else { soapStream = boundaryDelimitedStream; // This should be the SOAP part } // Read from the input stream all attachments prior to the root part. } catch (javax.mail.internet.ParseException e) { throw new org.apache.axis.AxisFault(Messages.getMessage("mimeErrorParsing", e.getMessage())); } catch (java.io.IOException e) { throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage())); } catch (javax.mail.MessagingException e) { throw new org.apache.axis.AxisFault(Messages.getMessage("readError", e.getMessage())); } }
From source file:org.apache.james.server.core.MailImpl.java
/** * Read the MailImpl from an <code>ObjectInputStream</code>. * * @param in the ObjectInputStream from which the object is read * @throws IOException if an error occurs while reading from the stream * @throws ClassNotFoundException ?/* w ww. j a va 2 s . c o m*/ * @throws ClassCastException if the serialized objects are not of the appropriate type */ @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { try { Object obj = in.readObject(); if (obj == null) { sender = null; } else if (obj instanceof String) { sender = new MailAddress((String) obj); } else if (obj instanceof MailAddress) { sender = (MailAddress) obj; } } catch (ParseException pe) { throw new IOException("Error parsing sender address: " + pe.getMessage()); } recipients = (Collection<MailAddress>) in.readObject(); state = (String) in.readObject(); errorMessage = (String) in.readObject(); name = (String) in.readObject(); remoteHost = (String) in.readObject(); remoteAddr = (String) in.readObject(); setLastUpdated((Date) in.readObject()); // the following is under try/catch to be backwards compatible // with messages created with James version <= 2.2.0a8 try { setAttributesRaw((Map<String, Object>) in.readObject()); } catch (OptionalDataException ode) { if (ode.eof) { attributes = new HashMap<>(); } else { throw ode; } } perRecipientSpecificHeaders = (PerRecipientHeaders) in.readObject(); }
From source file:org.masukomi.aspirin.core.RemoteDelivery.java
/** * We can assume that the recipients of this message are all going to the * same mail server. We will now rely on the JNDI to do DNS MX record lookup * and try to deliver to the multiple mail servers. If it fails, it should * throw an exception.// www . java2 s. c om * * Creation date: (2/24/00 11:25:00 PM) * * @param mail * org.apache.james.core.MailImpl * @param session * javax.mail.Session * @return boolean Whether the delivery was successful and the message can * be deleted */ private boolean deliver(QuedItem qi, Session session) { MailAddress rcpt = null; try { if (log.isDebugEnabled()) { log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)"); } MailImpl mail = (MailImpl) qi.getMail(); MimeMessage message = mail.getMessage(); // Create an array of the recipients as InternetAddress objects Collection recipients = mail.getRecipients(); InternetAddress addr[] = new InternetAddress[recipients.size()]; int j = 0; // funky ass look because you can't getElementAt() in a Collection for (Iterator i = recipients.iterator(); i.hasNext(); j++) { MailAddress currentRcpt = (MailAddress) i.next(); addr[j] = currentRcpt.toInternetAddress(); } if (addr.length <= 0) { if (log.isDebugEnabled()) { log.debug("No recipients specified... returning"); } return true; } // Figure out which servers to try to send to. This collection // will hold all the possible target servers Collection targetServers = null; Iterator it = recipients.iterator(); while (it.hasNext()) { rcpt = (MailAddress) recipients.iterator().next(); if (!qi.recepientHasBeenHandled(rcpt)) { break; } } // theoretically it is possible to not hav eone that hasn't been // handled // however that's only if something has gone really wrong. if (rcpt != null) { String host = rcpt.getHost(); // Lookup the possible targets try { // targetServers = MXLookup.urlsForHost(host); // farking // unreliable jndi bs targetServers = getMXRecordsForHost(host); } catch (Exception e) { log.error(e); } if (targetServers == null || targetServers.size() == 0) { log.warn("No mail server found for: " + host); StringBuffer exceptionBuffer = new StringBuffer(128) .append("I found no MX record entries for the hostname ").append(host) .append(". I cannot determine where to send this message."); return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true); } else if (log.isTraceEnabled()) { log.trace(targetServers.size() + " servers found for " + host); } MessagingException lastError = null; Iterator i = targetServers.iterator(); while (i.hasNext()) { try { URLName outgoingMailServer = (URLName) i.next(); StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ") .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString()) .append(" to addresses ").append(Arrays.asList(addr)); if (log.isDebugEnabled()) { log.debug(logMessageBuffer.toString()); } ; // URLName urlname = new URLName("smtp://" // + outgoingMailServer); Properties props = session.getProperties(); if (mail.getSender() == null) { props.put("mail.smtp.from", "<>"); } else { String sender = mail.getSender().toString(); props.put("mail.smtp.from", sender); } // Many of these properties are only in later JavaMail // versions // "mail.smtp.ehlo" //default true // "mail.smtp.auth" //default false // "mail.smtp.dsn.ret" //default to nothing... appended // as // RET= after MAIL FROM line. // "mail.smtp.dsn.notify" //default to // nothing...appended as // NOTIFY= after RCPT TO line. Transport transport = null; try { transport = session.getTransport(outgoingMailServer); try { transport.connect(); } catch (MessagingException me) { log.error(me); // Any error on connect should cause the mailet // to // attempt // to connect to the next SMTP server associated // with this MX record, // assuming the number of retries hasn't been // exceeded. if (failMessage(qi, rcpt, me, false)) { return true; } else { continue; } } transport.sendMessage(message, addr); // log.debug("message sent to " +addr); /*TODO: catch failures that should result * in failure with no retries } catch (SendFailedException sfe){ qi.failForRecipient(que, ); */ } finally { if (transport != null) { transport.close(); transport = null; } } logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName()) .append(") sent successfully to ").append(outgoingMailServer); log.debug(logMessageBuffer.toString()); qi.succeededForRecipient(que, rcpt); return true; } catch (MessagingException me) { log.error(me); // MessagingException are horribly difficult to figure // out // what actually happened. StringBuffer exceptionBuffer = new StringBuffer(256) .append("Exception delivering message (").append(mail.getName()).append(") - ") .append(me.getMessage()); log.warn(exceptionBuffer.toString()); if ((me.getNextException() != null) && (me.getNextException() instanceof java.io.IOException)) { // This is more than likely a temporary failure // If it's an IO exception with no nested exception, // it's probably // some socket or weird I/O related problem. lastError = me; continue; } // This was not a connection or I/O error particular to // one // SMTP server of an MX set. Instead, it is almost // certainly // a protocol level error. In this case we assume that // this // is an error we'd encounter with any of the SMTP // servers // associated with this MX record, and we pass the // exception // to the code in the outer block that determines its // severity. throw me; } // end catch } // end while // If we encountered an exception while looping through, // throw the last MessagingException we caught. We only // do this if we were unable to send the message to any // server. If sending eventually succeeded, we exit // deliver() though the return at the end of the try // block. if (lastError != null) { throw lastError; } } // END if (rcpt != null) else { log.error("unable to find recipient that handn't already been handled"); } } catch (SendFailedException sfe) { log.error(sfe); boolean deleteMessage = false; Collection recipients = qi.getMail().getRecipients(); // Would like to log all the types of email addresses if (log.isDebugEnabled()) { log.debug("Recipients: " + recipients); } /* * The rest of the recipients failed for one reason or another. * * SendFailedException actually handles this for us. For example, if * you send a message that has multiple invalid addresses, you'll * get a top-level SendFailedException that that has the valid, * valid-unsent, and invalid address lists, with all of the server * response messages will be contained within the nested exceptions. * [Note: the content of the nested exceptions is implementation * dependent.] * * sfe.getInvalidAddresses() should be considered permanent. * sfe.getValidUnsentAddresses() should be considered temporary. * * JavaMail v1.3 properly populates those collections based upon the * 4xx and 5xx response codes. * */ if (sfe.getInvalidAddresses() != null) { Address[] address = sfe.getInvalidAddresses(); if (address.length > 0) { recipients.clear(); for (int i = 0; i < address.length; i++) { try { recipients.add(new MailAddress(address[i].toString())); } catch (ParseException pe) { // this should never happen ... we should have // caught malformed addresses long before we // got to this code. if (log.isDebugEnabled()) { log.debug("Can't parse invalid address: " + pe.getMessage()); } } } if (log.isDebugEnabled()) { log.debug("Invalid recipients: " + recipients); } deleteMessage = failMessage(qi, rcpt, sfe, true); } } if (sfe.getValidUnsentAddresses() != null) { Address[] address = sfe.getValidUnsentAddresses(); if (address.length > 0) { recipients.clear(); for (int i = 0; i < address.length; i++) { try { recipients.add(new MailAddress(address[i].toString())); } catch (ParseException pe) { // this should never happen ... we should have // caught malformed addresses long before we // got to this code. if (log.isDebugEnabled()) { log.debug("Can't parse unsent address: " + pe.getMessage()); } pe.printStackTrace(); } } if (log.isDebugEnabled()) { log.debug("Unsent recipients: " + recipients); } deleteMessage = failMessage(qi, rcpt, sfe, false); } } return deleteMessage; } catch (MessagingException ex) { log.error(ex); // We should do a better job checking this... if the failure is a // general // connect exception, this is less descriptive than more specific // SMTP command // failure... have to lookup and see what are the various Exception // possibilities // Unable to deliver message after numerous tries... fail // accordingly // We check whether this is a 5xx error message, which // indicates a permanent failure (like account doesn't exist // or mailbox is full or domain is setup wrong). // We fail permanently if this was a 5xx error return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0))); } catch (Throwable t) { log.error(t); } /* * If we get here, we've exhausted the loop of servers without sending * the message or throwing an exception. One case where this might * happen is if we get a MessagingException on each transport.connect(), * e.g., if there is only one server and we get a connect exception. * Return FALSE to keep run() from deleting the message. */ return false; }