Author: sgoeschl
Date: Mon Nov 1 23:59:16 2010
New Revision: 1029898
URL: http://svn.apache.org/viewvc?rev=1029898&view=rev
Log:
+) Adding MimeMessageParser and MimeMessageUtils
+) cleand up most CheckStyle errors
+) improved test coverage
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/DataSourceResolver.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/DataSourceResolverImpl.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageParser.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageUtils.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/URLFactory.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/package.html
commons/proper/email/trunk/src/test/eml/
commons/proper/email/trunk/src/test/eml/html-attachment.eml
commons/proper/email/trunk/src/test/eml/simple.eml
commons/proper/email/trunk/src/test/org/apache/commons/mail/DataSourceResolverTest.java
(contents, props changed)
- copied, changed from r1006345,
commons/proper/email/trunk/src/test/org/apache/commons/mail/DefaultAuthenticatorTest.java
commons/proper/email/trunk/src/test/org/apache/commons/mail/util/
commons/proper/email/trunk/src/test/org/apache/commons/mail/util/MimeMessageParserTest.java
commons/proper/email/trunk/src/test/org/apache/commons/mail/util/URLFactoryTest.java
Removed:
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/URLFactory.java
Modified:
commons/proper/email/trunk/src/changes/changes.xml
commons/proper/email/trunk/src/java/org/apache/commons/mail/Email.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailConstants.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailUtils.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/ImageHtmlEmail.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/MultiPartEmail.java
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/package.html
commons/proper/email/trunk/src/test/org/apache/commons/mail/BaseEmailTestCase.java
commons/proper/email/trunk/src/test/org/apache/commons/mail/EmailAttachmentTest.java
commons/proper/email/trunk/src/test/org/apache/commons/mail/EmailLiveTest.java
commons/proper/email/trunk/src/test/org/apache/commons/mail/HtmlEmailTest.java
commons/proper/email/trunk/src/test/org/apache/commons/mail/ImageHtmlEmailTest.java
Modified: commons/proper/email/trunk/src/changes/changes.xml
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/changes/changes.xml?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
--- commons/proper/email/trunk/src/changes/changes.xml (original)
+++ commons/proper/email/trunk/src/changes/changes.xml Mon Nov 1 23:59:16 2010
@@ -23,6 +23,9 @@
<body>
<release version="1.3-SNAPSHOT" date="as in SVN">
+ <action dev="sgoeschl" type="add" date="2010-11-01">
+ Added MimeMessageParser and MimeMessageUtils.
+ </action>
<action dev="sgoeschl" type="fix" issue="EMAIL-96" date="2010-10-27">
Throwing an IllegalStateException when setting mail session properties
for an already
created mail session because the settings would be ignored. Please
note that this
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/DataSourceResolver.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/DataSourceResolver.java?rev=1029898&view=auto
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/DataSourceResolver.java
(added)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/DataSourceResolver.java
Mon Nov 1 23:59:16 2010
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.mail;
+
+import javax.activation.DataSource;
+import java.io.IOException;
+
+/**
+ * Creates a <code>DataSource</code> based on an URL.
+ *
+ * @since 1.3
+ */
+public interface DataSourceResolver
+{
+ /**
+ * Resolves the given resource location to a <code>DataSource</code>.
+ *
+ * @param resourceLocation the location of the resource
+ * @return the <code>DataSource</code>
+ * @throws IOException the resource was not found
+ */
+ DataSource resolve(final String resourceLocation) throws IOException;
+}
Modified: commons/proper/email/trunk/src/java/org/apache/commons/mail/Email.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/Email.java?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
--- commons/proper/email/trunk/src/java/org/apache/commons/mail/Email.java
(original)
+++ commons/proper/email/trunk/src/java/org/apache/commons/mail/Email.java Mon
Nov 1 23:59:16 2010
@@ -147,15 +147,19 @@ public abstract class Email implements E
* Used to determine whether to use pop3 before smtp, and if so the
settings.
*/
protected boolean popBeforeSmtp;
+
/** the host name of the pop3 server */
protected String popHost;
+
/** the user name to log into the pop3 server */
protected String popUsername;
+
/** the password to log into the pop3 server */
protected String popPassword;
/** does server require TLS encryption for authentication */
protected boolean tls;
+
/** does the current transport use SSL encryption? */
protected boolean ssl;
@@ -347,7 +351,7 @@ public abstract class Email implements E
/**
* Set the port number of the outgoing mail server.
- *
+ *
* @param aPortNumber aPortNumber
* @return An Email.
* @since 1.0
@@ -417,7 +421,7 @@ public abstract class Email implements E
/**
* Supply a mail Session object from a JNDI directory.
- *
+ *
* @param jndiName name of JNDI ressource (javax.mail.Session type),
ressource
* if searched in java:comp/env if name dont start with "java:"
* @return An Email.
@@ -1437,6 +1441,7 @@ public abstract class Email implements E
* Default is 60 second timeout.
*
* @param socketTimeout the socket I/O timeout
+ * @return An Email.
* @since 1.2
*/
public Email setSocketTimeout(int socketTimeout)
@@ -1482,7 +1487,7 @@ public abstract class Email implements E
{
result = MimeUtility.fold(name.length() + 2,
MimeUtility.encodeText(value.toString(), this.charset, null));
}
- catch(UnsupportedEncodingException e)
+ catch (UnsupportedEncodingException e)
{
result = value.toString();
}
@@ -1550,7 +1555,7 @@ public abstract class Email implements E
* @throws IllegalStateException when the mail session is
* already initialized
*/
- private void checkSessionAlreadyInitialized() throws IllegalStateException
+ private void checkSessionAlreadyInitialized()
{
if (this.session != null)
{
Modified:
commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailConstants.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailConstants.java?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailConstants.java
(original)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailConstants.java
Mon Nov 1 23:59:16 2010
@@ -52,13 +52,18 @@ public interface EmailConstants
String MAIL_SMTP_PASSWORD = "mail.smtp.password";
String MAIL_TRANSPORT_PROTOCOL = "mail.transport.protocol";
+ /////////////////////////////////////////////////////////////////////////
// since 1.1
+ /////////////////////////////////////////////////////////////////////////
+
String MAIL_TRANSPORT_TLS = "mail.smtp.starttls.enable";
String MAIL_SMTP_SOCKET_FACTORY_FALLBACK =
"mail.smtp.socketFactory.fallback";
String MAIL_SMTP_SOCKET_FACTORY_CLASS = "mail.smtp.socketFactory.class";
String MAIL_SMTP_SOCKET_FACTORY_PORT = "mail.smtp.socketFactory.port";
+ /////////////////////////////////////////////////////////////////////////
// since 1.2
+ /////////////////////////////////////////////////////////////////////////
/**
* Socket connection timeout value in milliseconds. Default is infinite
timeout.
Modified:
commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailUtils.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailUtils.java?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
--- commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailUtils.java
(original)
+++ commons/proper/email/trunk/src/java/org/apache/commons/mail/EmailUtils.java
Mon Nov 1 23:59:16 2010
@@ -17,10 +17,11 @@
package org.apache.commons.mail;
+import org.apache.commons.mail.util.MimeMessageUtils;
+
import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
import java.util.Random;
-import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
@@ -237,45 +238,6 @@ final class EmailUtils
*/
static void writeMimeMessage(File resultFile, MimeMessage mimeMessage)
throws IOException, MessagingException
{
- FileOutputStream fos = null;
-
- if (mimeMessage == null)
- {
- throw new IllegalArgumentException("mimeMessage is null");
- }
-
- if (resultFile == null)
- {
- throw new IllegalArgumentException("resultFile is null");
- }
-
- if (resultFile.getParentFile() != null)
- {
- resultFile.getParentFile().mkdirs();
- }
-
- try
- {
- fos = new FileOutputStream(resultFile);
- mimeMessage.writeTo(fos);
- fos.flush();
- fos.close();
- fos = null;
- }
- finally
- {
- if (fos != null)
- {
- try
- {
- fos.close();
- fos = null;
- }
- catch (Exception e)
- {
- // ignore
- }
- }
- }
+ MimeMessageUtils.writeMimeMessage(mimeMessage, resultFile);
}
}
Modified:
commons/proper/email/trunk/src/java/org/apache/commons/mail/ImageHtmlEmail.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/ImageHtmlEmail.java?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/ImageHtmlEmail.java
(original)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/ImageHtmlEmail.java
Mon Nov 1 23:59:16 2010
@@ -16,14 +16,8 @@
*/
package org.apache.commons.mail;
-import org.apache.commons.mail.impl.URLFactory;
-
import javax.activation.DataSource;
-import javax.activation.URLDataSource;
-import java.io.File;
import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
@@ -67,73 +61,35 @@ public class ImageHtmlEmail extends Html
/** pattern for extracting <script> tags */
private static final Pattern SCRIPT_PATTERN =
Pattern.compile(REGEX_SCRIPT_SRC);
- /**
- * Set the HTML message and try to add any image that is linked in the HTML
- * source.
- *
- * @param htmlMessage the HTML message
- * @return An HtmlEmail.
- * @throws EmailException assembling the email failed
- */
- public HtmlEmail setHtmlMsg(final String htmlMessage)
- throws EmailException
+ /** resolve the images and script resources to a DataSource */
+ private DataSourceResolver dataSourceResolver;
+
+ public DataSourceResolver getDataSourceResolver()
{
- return setHtmlMsg(htmlMessage, false);
+ return dataSourceResolver;
}
- /**
- * Set the HTML message and try to add any image that is linked in the HTML
- * source.
- *
- * @param htmlMessage the HTML message
- * @return An HtmlEmail.
- * @throws EmailException assembling the email failed
- */
- public HtmlEmail setHtmlMsg(final String htmlMessage, boolean isLenient)
- throws EmailException
+ public void setDataSourceResolver(DataSourceResolver dataSourceResolver)
+ {
+ this.dataSourceResolver = dataSourceResolver;
+ }
+
+ public void buildMimeMessage() throws EmailException
{
- URL currentWorkingDirectoryUrl;
+ String temp;
try
{
- currentWorkingDirectoryUrl = new File("").toURI().toURL();
+ // embed all the matching image and script resources within the
email
+ temp = replacePattern(super.html, IMG_PATTERN);
+ temp = replacePattern(temp, SCRIPT_PATTERN);
+ setHtmlMsg(temp);
+ super.buildMimeMessage();
}
- catch (MalformedURLException e)
+ catch (IOException e)
{
- throw new EmailException("Unable to create URL for current working
directory", e);
+ throw new EmailException("Building the MimeMessage failed", e);
}
-
- return setHtmlMsg(htmlMessage, currentWorkingDirectoryUrl, isLenient);
- }
-
- /**
- * Set the HTML content and try to add any image that is linked in the HTML
- * source. The 'baseUrl' is either a "http://..." or a "file://" in order
- * to resolve relative image resources.
- *
- * @param htmlMessage the HTML message.
- * @param baseUrl an base URL that is used as starting point for resolving
images that are embedded in the HTML
- * @param isLenient shall we ignore resources not found or throw an
exception?
- * @return a HTML email
- * @throws EmailException creating the email failed
- */
- public HtmlEmail setHtmlMsg(final String htmlMessage, final URL baseUrl,
boolean isLenient)
- throws EmailException
- {
- // if there is no useful HTML then simply route it through to the
super class
- if (htmlMessage == null || htmlMessage.length() == 0)
- {
- return super.setHtmlMsg(htmlMessage);
- }
-
- // replace images
- String temp = replacePattern(htmlMessage, IMG_PATTERN, baseUrl,
isLenient);
-
- // replace scripts
- temp = replacePattern(temp, SCRIPT_PATTERN, baseUrl, isLenient);
-
- // finally set the resulting HTML with all images replaced if possible
- return super.setHtmlMsg(temp);
}
/**
@@ -141,15 +97,14 @@ public class ImageHtmlEmail extends Html
*
* @param htmlMessage the HTML message to analyze
* @param pattern the regular expression to find resources
- * @param baseUrl the starting point for resolving relative resource paths
- * @param isLenient shall we ignore resources not found or throw an
exception?
* @return the HTML message containing "cid" references
* @throws EmailException creating the email failed
+ * @throws IOException resolving the resources failed
*/
- private String replacePattern(final String htmlMessage, final Pattern
pattern, final URL baseUrl, final boolean isLenient)
- throws EmailException
+ private String replacePattern(final String htmlMessage, final Pattern
pattern)
+ throws EmailException, IOException
{
- DataSource imageDataSource;
+ DataSource dataSource;
StringBuffer stringBuffer = new StringBuffer();
// maps "cid" --> name
@@ -166,32 +121,32 @@ public class ImageHtmlEmail extends Html
while (matcher.find())
{
// in the RegEx we have the <src> element as second "group"
- String image = matcher.group(2);
+ String resourceLocation = matcher.group(2);
// avoid loading the same data source more than once
- if (dataSourceCache.get(image) == null)
+ if (dataSourceCache.get(resourceLocation) == null)
{
// in lenient mode we might get a 'null' data source if the
resource was not found
- imageDataSource = resolve(baseUrl, image, isLenient);
+ dataSource = getDataSourceResolver().resolve(resourceLocation);
- if (imageDataSource != null)
+ if (dataSource != null)
{
- dataSourceCache.put(image, imageDataSource);
+ dataSourceCache.put(resourceLocation, dataSource);
}
}
else
{
- imageDataSource = (DataSource) dataSourceCache.get(image);
+ dataSource = (DataSource)
dataSourceCache.get(resourceLocation);
}
- if (imageDataSource != null)
+ if (dataSource != null)
{
- String name = imageDataSource.getName();
+ String name = dataSource.getName();
String cid = (String) cidCache.get(name);
if (cid == null)
{
- cid = embed(imageDataSource, imageDataSource.getName());
+ cid = embed(dataSource, dataSource.getName());
cidCache.put(name, cid);
}
@@ -210,45 +165,4 @@ public class ImageHtmlEmail extends Html
return stringBuffer.toString();
}
-
-
- /**
- * Resolve a resource location to be embedded into the email. When using
- * the lenient mode a resource which can't be resolved returns "null".
- * When using the non-lenient mode an exception would be thrown.
- *
- * @param baseUrl the base url of the resourceLocation
- * @param resourceLocation the location of the resource
- * @param isLenient shall we ignore resources not found?
- * @return the data source containing the resource
- * @throws EmailException resolving the resource failed
- */
- protected DataSource resolve(final URL baseUrl, final String
resourceLocation, final boolean isLenient)
- throws EmailException
- {
- DataSource result = null;
-
- try
- {
- if (!resourceLocation.startsWith("cid:"))
- {
- URL url = URLFactory.createUrl(baseUrl, resourceLocation);
- result = new URLDataSource(url);
- result.getInputStream();
- }
-
- return result;
- }
- catch (IOException e)
- {
- if (!isLenient)
- {
- throw new EmailException("Resolving the resource failed : " +
resourceLocation, e);
- }
- else
- {
- return null;
- }
- }
- }
}
Modified:
commons/proper/email/trunk/src/java/org/apache/commons/mail/MultiPartEmail.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/MultiPartEmail.java?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/MultiPartEmail.java
(original)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/MultiPartEmail.java
Mon Nov 1 23:59:16 2010
@@ -510,7 +510,7 @@ public class MultiPartEmail extends Emai
MimeMultipart mmp = new MimeMultipart();
return mmp;
}
-
+
/**
* Checks whether there are attachments.
*
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/DataSourceResolverImpl.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/DataSourceResolverImpl.java?rev=1029898&view=auto
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/DataSourceResolverImpl.java
(added)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/DataSourceResolverImpl.java
Mon Nov 1 23:59:16 2010
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.mail.impl;
+
+import org.apache.commons.mail.DataSourceResolver;
+import org.apache.commons.mail.util.URLFactory;
+
+import javax.activation.DataSource;
+import javax.activation.URLDataSource;
+import java.io.IOException;
+import java.net.URL;
+
+/**
+ * Creates a <code>DataSource</code> based on an URL.
+ *
+ * @since 1.3
+ */
+public class DataSourceResolverImpl implements DataSourceResolver
+{
+ /** the base url of the resource when resolving relative paths */
+ private URL baseUrl;
+
+ /** shall we ignore resources not found or complain with an exception */
+ private boolean isLenient;
+
+ /**
+ * Constructor.
+ *
+ * @param baseUrl the base URL used for resolving relative resource
locations
+ */
+ public DataSourceResolverImpl(URL baseUrl)
+ {
+ this(baseUrl, false);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param baseUrl the base URL used for resolving relative resource
locations
+ * @param lenient shall we ignore resources not found or complain with an
exception
+ */
+ public DataSourceResolverImpl(URL baseUrl, boolean lenient)
+ {
+ this.baseUrl = baseUrl;
+ this.isLenient = lenient;
+ }
+
+ public URL getBaseUrl()
+ {
+ return baseUrl;
+ }
+
+ public boolean isLenient()
+ {
+ return isLenient;
+ }
+
+ /**
+ * Resolve a resource location to be embedded into the email. When using
+ * the lenient mode a resource which can't be resolved returns "null".
+ * When using the non-lenient mode an exception would be thrown.
+ *
+ * @param resourceLocation the location of the resource
+ * @return the data source containing the resource
+ * @throws IOException resolving the resource failed
+ */
+ public DataSource resolve(String resourceLocation) throws IOException
+ {
+ DataSource result = null;
+
+ try
+ {
+ if (!resourceLocation.startsWith("cid:"))
+ {
+ URL url = URLFactory.createUrl(getBaseUrl(), resourceLocation);
+ result = new URLDataSource(url);
+ result.getInputStream();
+ }
+
+ return result;
+ }
+ catch (IOException e)
+ {
+ if (isLenient())
+ {
+ return null;
+ }
+ else
+ {
+ throw e;
+ }
+ }
+ }
+}
Modified:
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/package.html
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/package.html?rev=1029898&r1=1029897&r2=1029898&view=diff
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/package.html
(original)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/impl/package.html
Mon Nov 1 23:59:16 2010
@@ -17,8 +17,7 @@
<html>
<body>
<p>
-The content of this package is depending on the current implementation
-and might unexpectedly change.
+ Contains implemetation classes.
</p>
</body>
</html>
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageParser.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageParser.java?rev=1029898&view=auto
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageParser.java
(added)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageParser.java
Mon Nov 1 23:59:16 2010
@@ -0,0 +1,344 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.mail.util;
+
+import javax.activation.DataHandler;
+import javax.activation.DataSource;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimePart;
+import javax.mail.internet.MimeUtility;
+import javax.mail.util.ByteArrayDataSource;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Parses a MimeMessage and stores the individual parts such a plain text,
+ * HTML text and attachments.
+ *
+ * @since 1.3
+ */
+public class MimeMessageParser
+{
+ /** The MimeMessage to convert */
+ private MimeMessage mimeMessage;
+
+ /** Plain mail content from MimeMessage */
+ private String plainContent;
+
+ /** Html mail content from MimeMessage */
+ private String htmlContent;
+
+ /** List of attachments of MimeMessage */
+ private List attachmentList;
+
+ /** Is this a Multipart email */
+ private boolean isMultiPart;
+
+ /**
+ * Constructs an instance with the MimeMessage to be extracted.
+ *
+ * @param message the message to parse
+ */
+ public MimeMessageParser(MimeMessage message)
+ {
+ attachmentList = new ArrayList();
+ this.mimeMessage = message;
+ this.isMultiPart = false;
+ }
+
+ /**
+ * Does the actual extraction.
+ *
+ * @return this instance
+ * @throws Exception parsing the mime message failed
+ */
+ public MimeMessageParser parse() throws Exception
+ {
+ this.parse(null, mimeMessage);
+ return this;
+ }
+
+ /**
+ * @return the 'to' recipents of the message
+ * @throws Exception determining the recipients failed
+ */
+ public Collection getTo() throws Exception
+ {
+ javax.mail.Address[] recipients =
this.mimeMessage.getRecipients(Message.RecipientType.TO);
+ return (recipients != null ? Arrays.asList(recipients) : new
ArrayList());
+ }
+
+ /**
+ * @return the 'cc' recipents of the message
+ * @throws Exception determining the recipients failed
+ */
+ public Collection getCc() throws Exception
+ {
+ javax.mail.Address[] recipients =
this.mimeMessage.getRecipients(Message.RecipientType.CC);
+ return (recipients != null ? Arrays.asList(recipients) : new
ArrayList());
+ }
+
+ /**
+ * @return the 'bcc' recipents of the message
+ * @throws Exception determining the recipients failed
+ */
+ public Collection getBcc() throws Exception
+ {
+ javax.mail.Address[] recipients =
this.mimeMessage.getRecipients(Message.RecipientType.BCC);
+ return (recipients != null ? Arrays.asList(recipients) : new
ArrayList());
+ }
+
+ /**
+ * @return the 'from' field of the message
+ * @throws Exception parsing the mime message failed
+ */
+ public String getFrom() throws Exception
+ {
+ javax.mail.Address[] addresses = this.mimeMessage.getFrom();
+ if ((addresses == null) || (addresses.length == 0))
+ {
+ return null;
+ }
+ else
+ {
+ return ((InternetAddress) addresses[0]).getAddress();
+ }
+ }
+
+ /**
+ * @return the 'replyTo' address of the email
+ * @throws Exception parsing the mime message failed
+ */
+ public String getReplyTo() throws Exception
+ {
+ javax.mail.Address[] addresses = this.mimeMessage.getReplyTo();
+ if ((addresses == null) || (addresses.length == 0))
+ {
+ return null;
+ }
+ else
+ {
+ return ((InternetAddress) addresses[0]).getAddress();
+ }
+ }
+
+ /**
+ * @return the mail subject
+ * @throws Exception parsing the mime message failed
+ */
+ public String getSubject() throws Exception
+ {
+ return this.mimeMessage.getSubject();
+ }
+
+ /**
+ * Extracts the content of a MimeMessage recursively.
+ *
+ * @param parent the parent Mulitpart
+ * @param part the current MimePart
+ * @throws MessagingException parsing the MimeMessage failed
+ * @throws IOException parsing the MimeMessage failed
+ */
+ protected void parse(Multipart parent, MimePart part)
+ throws MessagingException, IOException
+ {
+ if (part.isMimeType("text/plain") && (plainContent == null))
+ {
+ plainContent = (String) part.getContent();
+ }
+ else
+ {
+ if (part.isMimeType("text/html") && (htmlContent == null))
+ {
+ htmlContent = (String) part.getContent();
+ }
+ else
+ {
+ if (part.isMimeType("multipart/*"))
+ {
+ this.isMultiPart = true;
+ Multipart mp = (Multipart) part.getContent();
+ int count = mp.getCount();
+
+ // iterate over all MimeBodyPart
+
+ for (int i = 0; i < count; i++)
+ {
+ parse(mp, (MimeBodyPart) mp.getBodyPart(i));
+ }
+ }
+ else
+ {
+ this.attachmentList.add(createDataSource(parent, part));
+ }
+ }
+ }
+ }
+
+ /**
+ * Parses the MimePart to create a DataSource.
+ *
+ * @param parent the parent MultiPart
+ * @param part the part to be processed
+ * @return the DataSource
+ * @throws MessagingException creating the DataSource failed
+ * @throws IOException creating the DataSource failed
+ */
+ protected DataSource createDataSource(Multipart parent, MimePart part)
+ throws MessagingException, IOException
+ {
+ DataHandler dataHandler = part.getDataHandler();
+ DataSource dataSource = dataHandler.getDataSource();
+ String contentType = getBaseMimeType(dataSource.getContentType());
+ byte[] content = this.getContent(dataSource.getInputStream());
+ ByteArrayDataSource result = new ByteArrayDataSource(content,
contentType);
+ String dataSourceName = MimeUtility.decodeText(dataSource.getName());
+
+ result.setName(dataSourceName);
+ return result;
+ }
+
+ /** @return Returns the mimeMessage. */
+ public MimeMessage getMimeMessage()
+ {
+ return mimeMessage;
+ }
+
+ /** @return Returns the isMultiPart. */
+ public boolean isMultipart()
+ {
+ return isMultiPart;
+ }
+
+ /** @return Returns the plainContent if any */
+ public String getPlainContent()
+ {
+ return plainContent;
+ }
+
+ /** @return Returns the attachmentList. */
+ public List getAttachmentList()
+ {
+ return attachmentList;
+ }
+
+ /** @return Returns the htmlContent if any */
+ public String getHtmlContent()
+ {
+ return htmlContent;
+ }
+
+ /** @return true if a plain content is available */
+ public boolean hasPlainContent()
+ {
+ return (this.plainContent != null);
+ }
+
+ /** @return true if HTML content is available */
+ public boolean hasHtmlContent()
+ {
+ return (this.htmlContent != null);
+ }
+
+ /** @return true if attachments are available */
+ public boolean hasAttachments()
+ {
+ return (this.attachmentList.size() > 0);
+ }
+
+ /**
+ * Find an attachment using its name.
+ *
+ * @param name the name of the attachment
+ * @return the corresponding datasource or null if nothing was found
+ */
+ public DataSource findAttachmentByName(String name)
+ {
+ DataSource dataSource = null;
+
+ for (int i = 0; i < getAttachmentList().size(); i++)
+ {
+ dataSource = (DataSource) getAttachmentList().get(i);
+ if (name.equalsIgnoreCase(dataSource.getName()))
+ {
+ return dataSource;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Read the content of the input stream.
+ *
+ * @param is the input stream to process
+ * @return the content of the input stream
+ * @throws IOException reading the input stream failed
+ */
+ private byte[] getContent(InputStream is)
+ throws IOException
+ {
+ int ch;
+ byte[] result;
+
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ BufferedInputStream isReader = new BufferedInputStream(is);
+ BufferedOutputStream osWriter = new BufferedOutputStream(os);
+
+ while ((ch = isReader.read()) != -1)
+ {
+ osWriter.write(ch);
+ }
+
+ osWriter.flush();
+ result = os.toByteArray();
+ osWriter.close();
+
+ return result;
+ }
+
+ /**
+ * Parses the mimeType.
+ *
+ * @param fullMimeType the mime type from the mail api
+ * @return the real mime type
+ */
+ private String getBaseMimeType(String fullMimeType)
+ {
+ int pos = fullMimeType.indexOf(';');
+ if (pos >= 0)
+ {
+ return fullMimeType.substring(0, pos);
+ }
+ else
+ {
+ return fullMimeType;
+ }
+ }
+}
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageUtils.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageUtils.java?rev=1029898&view=auto
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageUtils.java
(added)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/MimeMessageUtils.java
Mon Nov 1 23:59:16 2010
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.mail.util;
+
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.internet.MimeMessage;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Static helper methods.
+ *
+ * @author <a href="mailto:[email protected]">Siegfried Goeschl</a>
+ */
+public final class MimeMessageUtils
+{
+ /**
+ * Instances should NOT be constructed in standard programming.
+ */
+ private MimeMessageUtils()
+ {
+ super();
+ }
+
+ /**
+ * Create a MimeMessage.
+ *
+ * @param session the mail session
+ * @param source the input data
+ * @return the MimeMessage
+ * @throws MessagingException creating the MimeMessage failed
+ * @throws IOException creating the MimeMessage failed
+ */
+ public static MimeMessage createMimeMessage(Session session, byte[] source)
+ throws MessagingException, IOException
+ {
+ ByteArrayInputStream is = null;
+
+ try
+ {
+ is = new ByteArrayInputStream(source);
+ return new MimeMessage(session, is);
+ }
+ finally
+ {
+ if (is != null)
+ {
+ is.close();
+ }
+ }
+ }
+
+ /**
+ * Create a MimeMessage.
+ *
+ * @param session the mail session
+ * @param source the input data
+ * @return the MimeMessage
+ * @throws MessagingException creating the MimeMessage failed
+ * @throws IOException creating the MimeMessage failed
+ */
+ public static MimeMessage createMimeMessage(Session session, File source)
+ throws MessagingException, IOException
+ {
+ FileInputStream is = null;
+
+ try
+ {
+ is = new FileInputStream(source);
+ return createMimeMessage(session, is);
+ }
+ finally
+ {
+ if (is != null)
+ {
+ is.close();
+ }
+ }
+ }
+
+ /**
+ * Create a MimeMessage.
+ *
+ * @param session the mail session
+ * @param source the input data
+ * @return the MimeMessage
+ * @throws MessagingException creating the MimeMessage failed
+ */
+ public static MimeMessage createMimeMessage(Session session, InputStream
source)
+ throws MessagingException
+ {
+ return new MimeMessage(session, source);
+ }
+
+ /**
+ * Create a MimeMessage using the platform's default character encoding.
+ *
+ * @param session the mail session
+ * @param source the input data
+ * @return the MimeMessage
+ * @throws MessagingException creating the MimeMessage failed
+ * @throws IOException creating the MimeMessage failed
+ */
+ public static MimeMessage createMimeMessage(Session session, String source)
+ throws MessagingException, IOException
+ {
+ ByteArrayInputStream is = null;
+
+ try
+ {
+ byte[] byteSource = source.getBytes();
+ is = new ByteArrayInputStream(byteSource);
+ return createMimeMessage(session, is);
+ }
+ finally
+ {
+ if (is != null)
+ {
+ is.close();
+ }
+ }
+ }
+
+ /**
+ * Convenience method to write a MimeMessage into a file.
+ *
+ * @param mimeMessage the MimeMessage to write
+ * @param resultFile the file containing the MimeMessgae
+ * @throws MessagingException accessing MimeMessage failed
+ * @throws IOException writing the MimeMessage failed
+ */
+ public static void writeMimeMessage(MimeMessage mimeMessage, File
resultFile)
+ throws MessagingException, IOException
+ {
+
+ FileOutputStream fos = null;
+
+ try
+ {
+ resultFile.getParentFile().mkdirs();
+ fos = new FileOutputStream(resultFile);
+ mimeMessage.writeTo(fos);
+ fos.flush();
+ fos.close();
+ fos = null;
+ }
+ finally
+ {
+ if (fos != null)
+ {
+ try
+ {
+ fos.close();
+ fos = null;
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/URLFactory.java
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/util/URLFactory.java?rev=1029898&view=auto
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/URLFactory.java
(added)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/URLFactory.java
Mon Nov 1 23:59:16 2010
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.mail.util;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * Create an URL for embedding a resource.
+ *
+ * @since 1.3
+ */
+public final class URLFactory
+{
+ /**
+ * Instances should NOT be constructed in standard programming.
+ */
+ private URLFactory()
+ {
+ super();
+ }
+
+ /**
+ * Create an URL based on a base URL and a resource location suitable for
loading
+ * the resource.
+ *
+ * @param baseUrl an optional base URL
+ * @param resource a resource location
+ * @return the corresponding URL
+ * @throws java.net.MalformedURLException creating the URL failed
+ */
+ public static URL createUrl(final URL baseUrl, final String resource)
throws MalformedURLException
+ {
+ // if we get an non-existing base url than the resource can
+ // be directly used to create an URL
+ if (baseUrl == null)
+ {
+ return new URL(resource);
+ }
+
+ // if we get an non-existing location what we shall do?
+ if (resource == null)
+ {
+ throw new IllegalArgumentException("No resource defined");
+ }
+
+ // if we get a stand-alone resource than ignore the base url
+ if (isFileUrl(resource) || isHttpUrl(resource))
+ {
+ return new URL(resource);
+ }
+
+ // crate a file URL
+ String baseUrlString = baseUrl.toExternalForm();
+ if (isFileUrl(baseUrlString))
+ {
+ return new File(toFile(baseUrl), resource).toURI().toURL();
+ }
+ else
+ {
+ return new URL(baseUrl, resource.replaceAll("&", "&"));
+ }
+ }
+
+ /**
+ * Is this a file URL?
+ *
+ * @param urlString the URL string
+ * @return true if it is a file URL
+ */
+ private static boolean isFileUrl(String urlString)
+ {
+ return urlString.startsWith("file:/");
+ }
+
+ /**
+ * Is this a HTTP/HTTPS URL?
+ *
+ * @param urlString the URL string
+ * @return true if it is a HTTP/HTTPS URL
+ */
+ private static boolean isHttpUrl(String urlString)
+ {
+ return urlString.startsWith("http://") ||
urlString.startsWith("https://");
+ }
+
+ /**
+ * Convert from a <code>URL</code> to a <code>File</code>.
+ *
+ * @param url the file URL to convert, <code>null</code> returns
<code>null</code>
+ * @return the equivalent <code>File</code> object, or <code>null</code>
+ * if the URL's protocol is not <code>file</code>
+ * @throws IllegalArgumentException if the file is incorrectly encoded
+ */
+ private static File toFile(URL url)
+ {
+ if (url == null || !url.getProtocol().equals("file"))
+ {
+ return null;
+ }
+ else
+ {
+ String filename = url.getFile().replace('/', File.separatorChar);
+ int pos = 0;
+ while ((pos = filename.indexOf('%', pos)) >= 0)
+ {
+ if (pos + 2 < filename.length())
+ {
+ String hexStr = filename.substring(pos + 1, pos + 3);
+ char ch = (char) Integer.parseInt(hexStr, 16);
+ filename = filename.substring(0, pos) + ch +
filename.substring(pos + 3);
+ }
+ }
+ return new File(filename);
+ }
+ }
+}
Added:
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/package.html
URL:
http://svn.apache.org/viewvc/commons/proper/email/trunk/src/java/org/apache/commons/mail/util/package.html?rev=1029898&view=auto
==============================================================================
---
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/package.html
(added)
+++
commons/proper/email/trunk/src/java/org/apache/commons/mail/util/package.html
Mon Nov 1 23:59:16 2010
@@ -0,0 +1,23 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<html>
+<body>
+<p>
+ This package provides some utility classes.
+</p>
+</body>
+</html>