You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2023/12/13 17:20:07 UTC
(commons-email) 01/04: Add Checkstyle to the default goal
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-email.git
commit 9b38ada778f38d1f2f34f6142a35fcc578affb7a
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sun Dec 10 15:45:36 2023 -0500
Add Checkstyle to the default goal
Normalize formatting
---
pom.xml | 12 +-
src/conf/checkstyle.xml | 1 -
.../apache/commons/mail/ByteArrayDataSource.java | 98 +-
.../apache/commons/mail/DataSourceResolver.java | 8 +-
.../apache/commons/mail/DefaultAuthenticator.java | 18 +-
src/main/java/org/apache/commons/mail/Email.java | 1002 +++++++-------------
.../org/apache/commons/mail/EmailAttachment.java | 36 +-
.../org/apache/commons/mail/EmailConstants.java | 40 +-
.../org/apache/commons/mail/EmailException.java | 60 +-
.../java/org/apache/commons/mail/EmailUtils.java | 120 +--
.../java/org/apache/commons/mail/HtmlEmail.java | 445 ++++-----
.../org/apache/commons/mail/ImageHtmlEmail.java | 86 +-
.../apache/commons/mail/InputStreamDataSource.java | 3 +-
.../org/apache/commons/mail/MultiPartEmail.java | 321 ++-----
.../java/org/apache/commons/mail/SimpleEmail.java | 17 +-
.../java/org/apache/commons/mail/package-info.java | 4 +-
.../mail/resolver/DataSourceBaseResolver.java | 21 +-
.../mail/resolver/DataSourceClassPathResolver.java | 23 +-
.../mail/resolver/DataSourceCompositeResolver.java | 35 +-
.../mail/resolver/DataSourceFileResolver.java | 40 +-
.../mail/resolver/DataSourceUrlResolver.java | 46 +-
.../apache/commons/mail/resolver/package-info.java | 6 +-
.../mail/util/IDNEmailAddressConverter.java | 37 +-
.../commons/mail/util/MimeMessageParser.java | 159 +---
.../apache/commons/mail/util/MimeMessageUtils.java | 63 +-
.../org/apache/commons/mail/AbstractEmailTest.java | 336 +++----
.../commons/mail/DefaultAuthenticatorTest.java | 20 +-
.../apache/commons/mail/EmailAttachmentTest.java | 42 +-
.../org/apache/commons/mail/EmailLiveTest.java | 110 +--
.../java/org/apache/commons/mail/EmailTest.java | 495 +++-------
.../org/apache/commons/mail/HtmlEmailTest.java | 395 +++-----
.../apache/commons/mail/ImageHtmlEmailTest.java | 67 +-
.../apache/commons/mail/InvalidAddressTest.java | 105 +-
.../commons/mail/InvalidInternetAddressTest.java | 148 +--
.../apache/commons/mail/MultiPartEmailTest.java | 183 +---
.../commons/mail/SendWithAttachmentsTest.java | 80 +-
.../org/apache/commons/mail/SimpleEmailTest.java | 74 +-
.../commons/mail/mocks/MockEmailConcrete.java | 55 +-
.../commons/mail/mocks/MockHtmlEmailConcrete.java | 28 +-
.../mail/mocks/MockImageHtmlEmailConcrete.java | 21 +-
.../mail/mocks/MockMultiPartEmailConcrete.java | 23 +-
.../apache/commons/mail/mocks/MockSimpleEmail.java | 13 +-
.../resolver/AbstractDataSourceResolverTest.java | 6 +-
.../resolver/DataSourceClassPathResolverTest.java | 9 +-
.../resolver/DataSourceCompositeResolverTest.java | 15 +-
.../mail/resolver/DataSourceFileResolverTest.java | 9 +-
.../commons/mail/settings/EmailConfiguration.java | 52 +-
.../mail/util/IDNEmailAddressConverterTest.java | 21 +-
.../commons/mail/util/MimeMessageParserTest.java | 56 +-
49 files changed, 1673 insertions(+), 3391 deletions(-)
diff --git a/pom.xml b/pom.xml
index b47589f..d091303 100644
--- a/pom.xml
+++ b/pom.xml
@@ -323,7 +323,7 @@
</properties>
<build>
- <defaultGoal>clean verify apache-rat:check japicmp:cmp pmd:check pmd:cpd-check spotbugs:check javadoc:javadoc</defaultGoal>
+ <defaultGoal>clean verify apache-rat:check checkstyle:check japicmp:cmp pmd:check pmd:cpd-check spotbugs:check javadoc:javadoc</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -426,7 +426,15 @@
<excludeFilterFile>${basedir}/src/conf/spotbugs-exclude-filter.xml</excludeFilterFile>
</configuration>
</plugin>
- </plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <configLocation>${basedir}/src/conf/checkstyle.xml</configLocation>
+ <enableRulesSummary>false</enableRulesSummary>
+ </configuration>
+ </plugin>
+ </plugins>
</build>
<distributionManagement>
diff --git a/src/conf/checkstyle.xml b/src/conf/checkstyle.xml
index 2857a97..5a2a5ee 100644
--- a/src/conf/checkstyle.xml
+++ b/src/conf/checkstyle.xml
@@ -118,7 +118,6 @@
<module name="InnerAssignment" />
<!-- <module name="MagicNumber"/> -->
<module name="MissingSwitchDefault" />
- <module name="RedundantThrows" />
<module name="SimplifyBooleanExpression" />
<module name="SimplifyBooleanReturn" />
<module name="StringLiteralEquality" />
diff --git a/src/main/java/org/apache/commons/mail/ByteArrayDataSource.java b/src/main/java/org/apache/commons/mail/ByteArrayDataSource.java
index 6be4230..b0415b3 100644
--- a/src/main/java/org/apache/commons/mail/ByteArrayDataSource.java
+++ b/src/main/java/org/apache/commons/mail/ByteArrayDataSource.java
@@ -36,15 +36,13 @@ import javax.activation.DataSource;
* - a String<br>
*
* <p>
- * From version 1.3.1, it is possible to set a name for this DataSource,
- * and it is recommended to do so.
+ * From version 1.3.1, it is possible to set a name for this DataSource, and it is recommended to do so.
*
* @since 1.0
* @deprecated since 1.4, use {@link javax.mail.util.ByteArrayDataSource} instead
*/
@Deprecated
-public class ByteArrayDataSource implements DataSource
-{
+public class ByteArrayDataSource implements DataSource {
/** Define the buffer size. */
public static final int BUFFER_SIZE = 512;
@@ -55,8 +53,8 @@ public class ByteArrayDataSource implements DataSource
private final String type; // = "application/octet-stream";
/**
- * The name associated with this data source.
- * By default, the name is an empty string, similar to javax.mail.util.ByteArrayDataSource.
+ * The name associated with this data source. By default, the name is an empty string, similar to javax.mail.util.ByteArrayDataSource.
+ *
* @since 1.3.1
*/
private String name = "";
@@ -64,16 +62,14 @@ public class ByteArrayDataSource implements DataSource
/**
* Create a datasource from a byte array.
*
- * @param data A byte[].
+ * @param data A byte[].
* @param aType A String.
* @throws IOException IOException
* @since 1.0
*/
- public ByteArrayDataSource(final byte[] data, final String aType) throws IOException
- {
+ public ByteArrayDataSource(final byte[] data, final String aType) throws IOException {
this.type = aType;
- try (ByteArrayInputStream bis = new ByteArrayInputStream(data))
- {
+ try (ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
this.byteArrayDataSource(bis);
}
}
@@ -81,32 +77,28 @@ public class ByteArrayDataSource implements DataSource
/**
* Create a datasource from an input stream.
*
- * @param aIs An InputStream.
+ * @param aIs An InputStream.
* @param aType A String.
* @throws IOException IOException
* @since 1.0
*/
- public ByteArrayDataSource(final InputStream aIs, final String aType) throws IOException
- {
+ public ByteArrayDataSource(final InputStream aIs, final String aType) throws IOException {
this.type = aType;
this.byteArrayDataSource(aIs);
}
/**
- * Create a datasource from a String.
- * N.B. assumes the data string can be converted using the charset iso-8859-1.
+ * Create a datasource from a String. N.B. assumes the data string can be converted using the charset iso-8859-1.
*
- * @param data A String.
+ * @param data A String.
* @param aType A String.
* @throws IOException IOException
* @since 1.0
*/
- public ByteArrayDataSource(final String data, final String aType) throws IOException
- {
+ public ByteArrayDataSource(final String data, final String aType) throws IOException {
this.type = aType;
- try
- {
+ try {
baos = new ByteArrayOutputStream();
// Assumption that the string contains only ASCII characters!
@@ -114,34 +106,26 @@ public class ByteArrayDataSource implements DataSource
baos.write(data.getBytes(StandardCharsets.ISO_8859_1));
baos.flush();
baos.close();
- }
- catch (final UnsupportedEncodingException uex)
- {
+ } catch (final UnsupportedEncodingException uex) {
throw new IOException("The Character Encoding is not supported.");
- }
- finally
- {
- if (baos != null)
- {
+ } finally {
+ if (baos != null) {
baos.close();
}
}
}
/**
- * Create a datasource from an input stream.
- *
- * @param aIs An InputStream.
- * @throws IOException IOException
- */
- private void byteArrayDataSource(final InputStream aIs)
- throws IOException
- {
+ * Create a datasource from an input stream.
+ *
+ * @param aIs An InputStream.
+ * @throws IOException IOException
+ */
+ private void byteArrayDataSource(final InputStream aIs) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream osWriter = null;
- try
- {
+ try {
int length = 0;
final byte[] buffer = new byte[ByteArrayDataSource.BUFFER_SIZE];
@@ -150,26 +134,20 @@ public class ByteArrayDataSource implements DataSource
osWriter = new BufferedOutputStream(baos);
// Write the InputData to OutputStream
- while ((length = bis.read(buffer)) != -1)
- {
+ while ((length = bis.read(buffer)) != -1) {
osWriter.write(buffer, 0, length);
}
osWriter.flush();
osWriter.close();
- }
- finally
- {
- if (bis != null)
- {
+ } finally {
+ if (bis != null) {
bis.close();
}
- if (baos != null)
- {
+ if (baos != null) {
baos.close();
}
- if (osWriter != null)
- {
+ if (osWriter != null) {
osWriter.close();
}
}
@@ -182,8 +160,7 @@ public class ByteArrayDataSource implements DataSource
* @since 1.0
*/
@Override
- public String getContentType()
- {
+ public String getContentType() {
return type == null ? "application/octet-stream" : type;
}
@@ -195,10 +172,8 @@ public class ByteArrayDataSource implements DataSource
* @since 1.0
*/
@Override
- public InputStream getInputStream() throws IOException
- {
- if (baos == null)
- {
+ public InputStream getInputStream() throws IOException {
+ if (baos == null) {
throw new IOException("no data");
}
return new ByteArrayInputStream(baos.toByteArray());
@@ -210,8 +185,7 @@ public class ByteArrayDataSource implements DataSource
* @param name The name.
* @since 1.3.1
*/
- public void setName(final String name)
- {
+ public void setName(final String name) {
this.name = name;
}
@@ -222,20 +196,18 @@ public class ByteArrayDataSource implements DataSource
* @since 1.0
*/
@Override
- public String getName()
- {
+ public String getName() {
return name;
}
/**
* Gets the OutputStream to write to.
*
- * @return An OutputStream
+ * @return An OutputStream
* @since 1.0
*/
@Override
- public OutputStream getOutputStream()
- {
+ public OutputStream getOutputStream() {
baos = new ByteArrayOutputStream();
return baos;
}
diff --git a/src/main/java/org/apache/commons/mail/DataSourceResolver.java b/src/main/java/org/apache/commons/mail/DataSourceResolver.java
index ebcb85c..c99e279 100644
--- a/src/main/java/org/apache/commons/mail/DataSourceResolver.java
+++ b/src/main/java/org/apache/commons/mail/DataSourceResolver.java
@@ -24,8 +24,7 @@ import java.io.IOException;
*
* @since 1.3
*/
-public interface DataSourceResolver
-{
+public interface DataSourceResolver {
/**
* Resolves the given resource location to a {@code DataSource}.
*
@@ -39,10 +38,9 @@ public interface DataSourceResolver
* Resolves the given resource location to a {@code DataSource}.
*
* @param resourceLocation the location of the resource
- * @param isLenient shall we ignore resources not found or complain with an exception?
+ * @param isLenient shall we ignore resources not found or complain with an exception?
* @return the data source containing the resource or null if the resource was not found in lenient mode
* @throws IOException resolving the resource failed
*/
- DataSource resolve(final String resourceLocation, final boolean isLenient)
- throws IOException;
+ DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException;
}
diff --git a/src/main/java/org/apache/commons/mail/DefaultAuthenticator.java b/src/main/java/org/apache/commons/mail/DefaultAuthenticator.java
index 9802c1b..8ff56e8 100644
--- a/src/main/java/org/apache/commons/mail/DefaultAuthenticator.java
+++ b/src/main/java/org/apache/commons/mail/DefaultAuthenticator.java
@@ -20,13 +20,11 @@ import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
- * This is a very simple authentication object that can be used for any
- * transport needing basic userName and password type authentication.
+ * This is a very simple authentication object that can be used for any transport needing basic userName and password type authentication.
*
* @since 1.0
*/
-public class DefaultAuthenticator extends Authenticator
-{
+public class DefaultAuthenticator extends Authenticator {
/** Stores the login information for authentication. */
private final PasswordAuthentication authentication;
@@ -37,22 +35,18 @@ public class DefaultAuthenticator extends Authenticator
* @param password password to use when authentication is requested
* @since 1.0
*/
- public DefaultAuthenticator(final String userName, final String password)
- {
+ public DefaultAuthenticator(final String userName, final String password) {
this.authentication = new PasswordAuthentication(userName, password);
}
/**
- * Gets the authentication object that will be used to login to the mail
- * server.
+ * Gets the authentication object that will be used to login to the mail server.
*
- * @return A {@code PasswordAuthentication} object containing the
- * login information.
+ * @return A {@code PasswordAuthentication} object containing the login information.
* @since 1.0
*/
@Override
- protected PasswordAuthentication getPasswordAuthentication()
- {
+ protected PasswordAuthentication getPasswordAuthentication() {
return this.authentication;
}
}
diff --git a/src/main/java/org/apache/commons/mail/Email.java b/src/main/java/org/apache/commons/mail/Email.java
index bab4441..45045a4 100644
--- a/src/main/java/org/apache/commons/mail/Email.java
+++ b/src/main/java/org/apache/commons/mail/Email.java
@@ -45,16 +45,13 @@ import javax.naming.NamingException;
import org.apache.commons.mail.util.IDNEmailAddressConverter;
/**
- * The base class for all email messages. This class sets the
- * sender's email & name, receiver's email & name, subject, and the
- * sent date.
+ * The base class for all email messages. This class sets the sender's email & name, receiver's email & name, subject, and the sent date.
* <p>
* Subclasses are responsible for setting the message body.
*
* @since 1.0
*/
-public abstract class Email
-{
+public abstract class Email {
private static final InternetAddress[] EMPTY_INTERNET_ADDRESS_ARRAY = {};
/** @deprecated since 1.3, use {@link EmailConstants#SENDER_EMAIL} instead */
@@ -201,26 +198,22 @@ public abstract class Email
protected Date sentDate;
/**
- * Instance of an {@code Authenticator} object that will be used
- * when authentication is requested from the mail server.
+ * Instance of an {@code Authenticator} object that will be used when authentication is requested from the mail server.
*/
protected Authenticator authenticator;
/**
- * The hostname of the mail server with which to connect. If null will try
- * to get property from system.properties. If still null, quit.
+ * The hostname of the mail server with which to connect. If null will try to get property from system.properties. If still null, quit.
*/
protected String hostName;
/**
- * The port number of the mail server to connect to.
- * Defaults to the standard port ( 25 ).
+ * The port number of the mail server to connect to. Defaults to the standard port ( 25 ).
*/
protected String smtpPort = "25";
/**
- * The port number of the SSL enabled SMTP server;
- * defaults to the standard port, 465.
+ * The port number of the SSL enabled SMTP server; defaults to the standard port, 465.
*/
protected String sslSmtpPort = "465";
@@ -237,19 +230,15 @@ public abstract class Email
protected List<InternetAddress> replyList = new ArrayList<>();
/**
- * Address to which undeliverable mail should be sent.
- * Because this is handled by JavaMail as a String property
- * in the mail session, this property is of type {@code String}
- * rather than {@code InternetAddress}.
+ * Address to which undeliverable mail should be sent. Because this is handled by JavaMail as a String property in the mail session, this property is of
+ * type {@code String} rather than {@code InternetAddress}.
*/
protected String bounceAddress;
/**
- * Used to specify the mail headers. Example:
+ * Used to specify the mail headers. Example:
*
- * X-Mailer: Sendmail, X-Priority: 1( highest )
- * or 2( high ) 3( normal ) 4( low ) and 5( lowest )
- * Disposition-Notification-To: user@domain.net
+ * X-Mailer: Sendmail, X-Priority: 1( highest ) or 2( high ) 3( normal ) 4( low ) and 5( lowest ) Disposition-Notification-To: user@domain.net
*/
protected Map<String, String> headers = new HashMap<>();
@@ -269,13 +258,15 @@ public abstract class Email
/**
* Does server require TLS encryption for authentication?
- * @deprecated since 1.3, use setStartTLSEnabled() instead
+ *
+ * @deprecated since 1.3, use setStartTLSEnabled() instead
*/
@Deprecated
protected boolean tls;
/**
* Does the current transport use SSL/TLS encryption upon connection?
+ *
* @deprecated since 1.3, use setSSLOnConnect() instead
*/
@Deprecated
@@ -288,20 +279,14 @@ public abstract class Email
protected int socketConnectionTimeout = EmailConstants.SOCKET_TIMEOUT_MS;
/**
- * If true, enables the use of the STARTTLS command (if supported by
- * the server) to switch the connection to a TLS-protected connection
- * before issuing any login commands. Note that an appropriate trust
- * store must configured so that the client will trust the server's
- * certificate.
- * Defaults to false.
+ * If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any
+ * login commands. Note that an appropriate trust store must configured so that the client will trust the server's certificate. Defaults to false.
*/
private boolean startTlsEnabled;
/**
- * If true, requires the use of the STARTTLS command. If the server doesn't
- * support the STARTTLS command, or the command fails, the connect method
- * will fail.
- * Defaults to false.
+ * If true, requires the use of the STARTTLS command. If the server doesn't support the STARTTLS command, or the command fails, the connect method will
+ * fail. Defaults to false.
*/
private boolean startTlsRequired;
@@ -309,19 +294,15 @@ public abstract class Email
private boolean sslOnConnect;
/**
- * If set to true, check the server identity as specified by RFC 2595. These
- * additional checks based on the content of the server's certificate are
- * intended to prevent man-in-the-middle attacks.
- * Defaults to false.
+ * If set to true, check the server identity as specified by RFC 2595. These additional checks based on the content of the server's certificate are intended
+ * to prevent man-in-the-middle attacks. Defaults to false.
*/
private boolean sslCheckServerIdentity;
/**
- * If set to true, and a message has some valid and some invalid addresses, send the message anyway,
- * reporting the partial failure with a SendFailedException.
- * If set to false (the default), the message is not sent to any of the recipients
- * if there is an invalid recipient address.
- * Defaults to false.
+ * If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a
+ * SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address. Defaults
+ * to false.
*/
private boolean sendPartial;
@@ -334,17 +315,14 @@ public abstract class Email
* @param d A boolean.
* @since 1.0
*/
- public void setDebug(final boolean d)
- {
+ public void setDebug(final boolean d) {
this.debug = d;
}
/**
- * Sets the userName and password if authentication is needed. If this
- * method is not used, no authentication will be performed.
+ * Sets the userName and password if authentication is needed. If this method is not used, no authentication will be performed.
* <p>
- * This method will create a new instance of
- * {@code DefaultAuthenticator} using the supplied parameters.
+ * This method will create a new instance of {@code DefaultAuthenticator} using the supplied parameters.
*
* @param userName User name for the SMTP server
* @param password password for the SMTP server
@@ -352,39 +330,32 @@ public abstract class Email
* @see #setAuthenticator
* @since 1.0
*/
- public void setAuthentication(final String userName, final String password)
- {
+ public void setAuthentication(final String userName, final String password) {
this.setAuthenticator(new DefaultAuthenticator(userName, password));
}
/**
- * Sets the {@code Authenticator} to be used when authentication
- * is requested from the mail server.
+ * Sets the {@code Authenticator} to be used when authentication is requested from the mail server.
* <p>
- * This method should be used when your outgoing mail server requires
- * authentication. Your mail server must also support RFC2554.
+ * This method should be used when your outgoing mail server requires authentication. Your mail server must also support RFC2554.
*
* @param newAuthenticator the {@code Authenticator} object.
* @see Authenticator
* @since 1.0
*/
- public void setAuthenticator(final Authenticator newAuthenticator)
- {
+ public void setAuthenticator(final Authenticator newAuthenticator) {
this.authenticator = newAuthenticator;
}
/**
- * Sets the charset of the message. Please note that you should set the charset before
- * adding the message content.
+ * Sets the charset of the message. Please note that you should set the charset before adding the message content.
*
* @param newCharset A String.
* @throws java.nio.charset.IllegalCharsetNameException if the charset name is invalid
- * @throws java.nio.charset.UnsupportedCharsetException if no support for the named charset
- * exists in the current JVM
+ * @throws java.nio.charset.UnsupportedCharsetException if no support for the named charset exists in the current JVM
* @since 1.0
*/
- public void setCharset(final String newCharset)
- {
+ public void setCharset(final String newCharset) {
final Charset set = Charset.forName(newCharset);
this.charset = set.name();
}
@@ -395,20 +366,18 @@ public abstract class Email
* @param aMimeMultipart aMimeMultipart
* @since 1.0
*/
- public void setContent(final MimeMultipart aMimeMultipart)
- {
+ public void setContent(final MimeMultipart aMimeMultipart) {
this.emailBody = aMimeMultipart;
}
/**
* Sets the content and contentType.
*
- * @param aObject aObject
- * @param aContentType aContentType
+ * @param aObject aObject
+ * @param aContentType aContentType
* @since 1.0
*/
- public void setContent(final Object aObject, final String aContentType)
- {
+ public void setContent(final Object aObject, final String aContentType) {
this.content = aObject;
this.updateContentType(aContentType);
}
@@ -416,17 +385,13 @@ public abstract class Email
/**
* Update the contentType.
*
- * @param aContentType aContentType
+ * @param aContentType aContentType
* @since 1.2
*/
- public void updateContentType(final String aContentType)
- {
- if (EmailUtils.isEmpty(aContentType))
- {
+ public void updateContentType(final String aContentType) {
+ if (EmailUtils.isEmpty(aContentType)) {
this.contentType = null;
- }
- else
- {
+ } else {
// set the content type
this.contentType = aContentType;
@@ -434,29 +399,20 @@ public abstract class Email
final String strMarker = "; charset=";
int charsetPos = aContentType.toLowerCase().indexOf(strMarker);
- if (charsetPos != -1)
- {
+ if (charsetPos != -1) {
// find the next space (after the marker)
charsetPos += strMarker.length();
- final int intCharsetEnd =
- aContentType.toLowerCase().indexOf(" ", charsetPos);
+ final int intCharsetEnd = aContentType.toLowerCase().indexOf(" ", charsetPos);
- if (intCharsetEnd != -1)
- {
- this.charset =
- aContentType.substring(charsetPos, intCharsetEnd);
- }
- else
- {
+ if (intCharsetEnd != -1) {
+ this.charset = aContentType.substring(charsetPos, intCharsetEnd);
+ } else {
this.charset = aContentType.substring(charsetPos);
}
- }
- else
- {
+ } else {
// use the default charset, if one exists, for messages
// whose content-type is some form of text.
- if (this.contentType.startsWith("text/") && EmailUtils.isNotEmpty(this.charset))
- {
+ if (this.contentType.startsWith("text/") && EmailUtils.isNotEmpty(this.charset)) {
final StringBuilder contentTypeBuf = new StringBuilder(this.contentType);
contentTypeBuf.append(strMarker);
contentTypeBuf.append(this.charset);
@@ -469,27 +425,24 @@ public abstract class Email
/**
* Sets the hostname of the outgoing mail server.
*
- * @param aHostName aHostName
+ * @param aHostName aHostName
* @throws IllegalStateException if the mail session is already initialized
* @since 1.0
*/
- public void setHostName(final String aHostName)
- {
+ public void setHostName(final String aHostName) {
checkSessionAlreadyInitialized();
this.hostName = aHostName;
}
/**
- * Sets or disable the STARTTLS encryption. Please see EMAIL-105
- * for the reasons of deprecation.
+ * Sets or disable the STARTTLS encryption. Please see EMAIL-105 for the reasons of deprecation.
*
* @deprecated since 1.3, use setStartTLSEnabled() instead
* @param withTLS true if STARTTLS requested, false otherwise
* @since 1.1
*/
@Deprecated
- public void setTLS(final boolean withTLS)
- {
+ public void setTLS(final boolean withTLS) {
setStartTLSEnabled(withTLS);
}
@@ -501,8 +454,7 @@ public abstract class Email
* @throws IllegalStateException if the mail session is already initialized
* @since 1.3
*/
- public Email setStartTLSEnabled(final boolean startTlsEnabled)
- {
+ public Email setStartTLSEnabled(final boolean startTlsEnabled) {
checkSessionAlreadyInitialized();
this.startTlsEnabled = startTlsEnabled;
this.tls = startTlsEnabled;
@@ -519,8 +471,7 @@ public abstract class Email
* @throws IllegalStateException if the mail session is already initialized
* @since 1.3
*/
- public Email setStartTLSRequired(final boolean startTlsRequired)
- {
+ public Email setStartTLSRequired(final boolean startTlsRequired) {
checkSessionAlreadyInitialized();
this.startTlsRequired = startTlsRequired;
return this;
@@ -529,68 +480,53 @@ public abstract class Email
/**
* Sets the non-SSL port number of the outgoing mail server.
*
- * @param aPortNumber aPortNumber
+ * @param aPortNumber aPortNumber
* @throws IllegalArgumentException if the port number is < 1
- * @throws IllegalStateException if the mail session is already initialized
+ * @throws IllegalStateException if the mail session is already initialized
* @since 1.0
* @see #setSslSmtpPort(String)
*/
- public void setSmtpPort(final int aPortNumber)
- {
+ public void setSmtpPort(final int aPortNumber) {
checkSessionAlreadyInitialized();
- if (aPortNumber < 1)
- {
- throw new IllegalArgumentException(
- "Cannot connect to a port number that is less than 1 ( "
- + aPortNumber
- + " )");
+ if (aPortNumber < 1) {
+ throw new IllegalArgumentException("Cannot connect to a port number that is less than 1 ( " + aPortNumber + " )");
}
this.smtpPort = Integer.toString(aPortNumber);
}
/**
- * Supply a mail Session object to use. Please note that passing
- * a user name and password (in the case of mail authentication) will
- * create a new mail session with a DefaultAuthenticator. This is a
- * convenience but might come unexpected.
+ * Supply a mail Session object to use. Please note that passing a user name and password (in the case of mail authentication) will create a new mail
+ * session with a DefaultAuthenticator. This is a convenience but might come unexpected.
*
- * If mail authentication is used but NO username and password
- * is supplied the implementation assumes that you have set a
- * authenticator and will use the existing mail session (as expected).
+ * If mail authentication is used but NO username and password is supplied the implementation assumes that you have set a authenticator and will use the
+ * existing mail session (as expected).
*
* @param session mail session to be used
* @throws NullPointerException if {@code aSession} is {@code null}
* @since 1.0
*/
- public void setMailSession(final Session session)
- {
+ public void setMailSession(final Session session) {
Objects.requireNonNull(session, "no mail session supplied");
final Properties sessionProperties = session.getProperties();
final String auth = sessionProperties.getProperty(EmailConstants.MAIL_SMTP_AUTH);
- if ("true".equalsIgnoreCase(auth))
- {
+ if ("true".equalsIgnoreCase(auth)) {
final String userName = sessionProperties.getProperty(EmailConstants.MAIL_SMTP_USER);
final String password = sessionProperties.getProperty(EmailConstants.MAIL_SMTP_PASSWORD);
- if (EmailUtils.isNotEmpty(userName) && EmailUtils.isNotEmpty(password))
- {
+ if (EmailUtils.isNotEmpty(userName) && EmailUtils.isNotEmpty(password)) {
// only create a new mail session with an authenticator if
// authentication is required and no user name is given
this.authenticator = new DefaultAuthenticator(userName, password);
this.session = Session.getInstance(sessionProperties, this.authenticator);
- }
- else
- {
+ } else {
// assume that the given mail session contains a working authenticator
this.session = session;
}
- }
- else
- {
+ } else {
this.session = session;
}
}
@@ -598,25 +534,19 @@ public abstract class Email
/**
* Supply a mail Session object from a JNDI directory.
*
- * @param jndiName name of JNDI resource (javax.mail.Session type), resource
- * if searched in java:comp/env if name does not start with "java:"
+ * @param jndiName name of JNDI resource (javax.mail.Session type), resource if searched in java:comp/env if name does not start with "java:"
* @throws IllegalArgumentException if the JNDI name is null or empty
- * @throws NamingException if the resource cannot be retrieved from JNDI directory
+ * @throws NamingException if the resource cannot be retrieved from JNDI directory
* @since 1.1
*/
- public void setMailSessionFromJNDI(final String jndiName) throws NamingException
- {
- if (EmailUtils.isEmpty(jndiName))
- {
+ public void setMailSessionFromJNDI(final String jndiName) throws NamingException {
+ if (EmailUtils.isEmpty(jndiName)) {
throw new IllegalArgumentException("JNDI name missing");
}
Context ctx = null;
- if (jndiName.startsWith("java:"))
- {
+ if (jndiName.startsWith("java:")) {
ctx = new InitialContext();
- }
- else
- {
+ } else {
ctx = (Context) new InitialContext().lookup("java:comp/env");
}
@@ -624,29 +554,23 @@ public abstract class Email
}
/**
- * Determines the mail session used when sending this Email, creating
- * the Session if necessary. When a mail session is already
- * initialized setting the session related properties will cause
- * an IllegalStateException.
+ * Determines the mail session used when sending this Email, creating the Session if necessary. When a mail session is already initialized setting the
+ * session related properties will cause an IllegalStateException.
*
* @return A Session.
* @throws EmailException if the host name was not set
* @since 1.0
*/
- public Session getMailSession() throws EmailException
- {
- if (this.session == null)
- {
+ public Session getMailSession() throws EmailException {
+ if (this.session == null) {
final Properties properties = new Properties(System.getProperties());
properties.setProperty(EmailConstants.MAIL_TRANSPORT_PROTOCOL, EmailConstants.SMTP);
- if (EmailUtils.isEmpty(this.hostName))
- {
+ if (EmailUtils.isEmpty(this.hostName)) {
this.hostName = properties.getProperty(EmailConstants.MAIL_HOST);
}
- if (EmailUtils.isEmpty(this.hostName))
- {
+ if (EmailUtils.isEmpty(this.hostName)) {
throw new EmailException("Cannot find valid hostname for mail session");
}
@@ -654,46 +578,36 @@ public abstract class Email
properties.setProperty(EmailConstants.MAIL_HOST, this.hostName);
properties.setProperty(EmailConstants.MAIL_DEBUG, String.valueOf(this.debug));
- properties.setProperty(EmailConstants.MAIL_TRANSPORT_STARTTLS_ENABLE,
- isStartTLSEnabled() ? "true" : "false");
- properties.setProperty(EmailConstants.MAIL_TRANSPORT_STARTTLS_REQUIRED,
- isStartTLSRequired() ? "true" : "false");
+ properties.setProperty(EmailConstants.MAIL_TRANSPORT_STARTTLS_ENABLE, isStartTLSEnabled() ? "true" : "false");
+ properties.setProperty(EmailConstants.MAIL_TRANSPORT_STARTTLS_REQUIRED, isStartTLSRequired() ? "true" : "false");
- properties.setProperty(EmailConstants.MAIL_SMTP_SEND_PARTIAL,
- isSendPartial() ? "true" : "false");
- properties.setProperty(EmailConstants.MAIL_SMTPS_SEND_PARTIAL,
- isSendPartial() ? "true" : "false");
+ properties.setProperty(EmailConstants.MAIL_SMTP_SEND_PARTIAL, isSendPartial() ? "true" : "false");
+ properties.setProperty(EmailConstants.MAIL_SMTPS_SEND_PARTIAL, isSendPartial() ? "true" : "false");
- if (this.authenticator != null)
- {
+ if (this.authenticator != null) {
properties.setProperty(EmailConstants.MAIL_SMTP_AUTH, "true");
}
- if (isSSLOnConnect())
- {
+ if (isSSLOnConnect()) {
properties.setProperty(EmailConstants.MAIL_PORT, this.sslSmtpPort);
properties.setProperty(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_PORT, this.sslSmtpPort);
properties.setProperty(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
properties.setProperty(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_FALLBACK, "false");
}
- if ((isSSLOnConnect() || isStartTLSEnabled()) && isSSLCheckServerIdentity())
- {
+ if ((isSSLOnConnect() || isStartTLSEnabled()) && isSSLCheckServerIdentity()) {
properties.setProperty(EmailConstants.MAIL_SMTP_SSL_CHECKSERVERIDENTITY, "true");
}
- if (this.bounceAddress != null)
- {
+ if (this.bounceAddress != null) {
properties.setProperty(EmailConstants.MAIL_SMTP_FROM, this.bounceAddress);
}
- if (this.socketTimeout > 0)
- {
+ if (this.socketTimeout > 0) {
properties.setProperty(EmailConstants.MAIL_SMTP_TIMEOUT, Integer.toString(this.socketTimeout));
}
- if (this.socketConnectionTimeout > 0)
- {
+ if (this.socketConnectionTimeout > 0) {
properties.setProperty(EmailConstants.MAIL_SMTP_CONNECTIONTIMEOUT, Integer.toString(this.socketConnectionTimeout));
}
@@ -705,69 +619,52 @@ public abstract class Email
}
/**
- * Sets the FROM field of the email to use the specified address. The email
- * address will also be used as the personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Sets the FROM field of the email to use the specified address. The email address will also be used as the personal name. The name will be encoded by the
+ * charset of {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if
+ * it contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address.
* @since 1.0
*/
- public Email setFrom(final String email)
- throws EmailException
- {
+ public Email setFrom(final String email) throws EmailException {
return setFrom(email, null);
}
/**
- * Sets the FROM field of the email to use the specified address and the
- * specified personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Sets the FROM field of the email to use the specified address and the specified personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
- * @param name A String.
+ * @param name A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address.
* @since 1.0
*/
- public Email setFrom(final String email, final String name)
- throws EmailException
- {
+ public Email setFrom(final String email, final String name) throws EmailException {
return setFrom(email, name, this.charset);
}
/**
- * Sets the FROM field of the email to use the specified address, personal
- * name, and charset encoding for the name.
+ * Sets the FROM field of the email to use the specified address, personal name, and charset encoding for the name.
*
- * @param email A String.
- * @param name A String.
+ * @param email A String.
+ * @param name A String.
* @param charset The charset to encode the name with.
* @return An Email.
* @throws EmailException Indicates an invalid email address or charset.
* @since 1.1
*/
- public Email setFrom(final String email, final String name, final String charset)
- throws EmailException
- {
+ public Email setFrom(final String email, final String name, final String charset) throws EmailException {
this.fromAddress = createInternetAddress(email, name, charset);
return this;
}
/**
- * Add a recipient TO to the email. The email
- * address will also be used as the personal name.
- * The name will be encoded by the charset of
- * {@link #setCharset(String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
+ * Add a recipient TO to the email. The email address will also be used as the personal name. The name will be encoded by the charset of
+ * {@link #setCharset(String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it contains
* non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
@@ -775,19 +672,13 @@ public abstract class Email
* @throws EmailException Indicates an invalid email address.
* @since 1.0
*/
- public Email addTo(final String email)
- throws EmailException
- {
+ public Email addTo(final String email) throws EmailException {
return addTo(email, null);
}
/**
- * Add a list of TO recipients to the email. The email
- * addresses will also be used as the personal names.
- * The names will be encoded by the charset of
- * {@link #setCharset(String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
+ * Add a list of TO recipients to the email. The email addresses will also be used as the personal names. The names will be encoded by the charset of
+ * {@link #setCharset(String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it contains
* non-ASCII characters; otherwise, it is used as is.
*
* @param emails A String array.
@@ -795,16 +686,12 @@ public abstract class Email
* @throws EmailException Indicates an invalid email address.
* @since 1.3
*/
- public Email addTo(final String... emails)
- throws EmailException
- {
- if (emails == null || emails.length == 0)
- {
+ public Email addTo(final String... emails) throws EmailException {
+ if (emails == null || emails.length == 0) {
throw new EmailException("Address List provided was invalid");
}
- for (final String email : emails)
- {
+ for (final String email : emails) {
addTo(email, null);
}
@@ -812,59 +699,46 @@ public abstract class Email
}
/**
- * Add a recipient TO to the email using the specified address and the
- * specified personal name.
- * The name will be encoded by the charset of
- * {@link #setCharset(String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
+ * Add a recipient TO to the email using the specified address and the specified personal name. The name will be encoded by the charset of
+ * {@link #setCharset(String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it contains
* non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
- * @param name A String.
+ * @param name A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address.
* @since 1.0
*/
- public Email addTo(final String email, final String name)
- throws EmailException
- {
+ public Email addTo(final String email, final String name) throws EmailException {
return addTo(email, name, this.charset);
}
/**
- * Add a recipient TO to the email using the specified address, personal
- * name, and charset encoding for the name.
+ * Add a recipient TO to the email using the specified address, personal name, and charset encoding for the name.
*
- * @param email A String.
- * @param name A String.
+ * @param email A String.
+ * @param name A String.
* @param charset The charset to encode the name with.
* @return An Email.
* @throws EmailException Indicates an invalid email address or charset.
* @since 1.1
*/
- public Email addTo(final String email, final String name, final String charset)
- throws EmailException
- {
+ public Email addTo(final String email, final String name, final String charset) throws EmailException {
this.toList.add(createInternetAddress(email, name, charset));
return this;
}
/**
- * Sets a list of "TO" addresses. All elements in the specified
- * {@code Collection} are expected to be of type
- * {@code java.mail.internet.InternetAddress}.
+ * Sets a list of "TO" addresses. All elements in the specified {@code Collection} are expected to be of type {@code java.mail.internet.InternetAddress}.
*
- * @param aCollection collection of {@code InternetAddress} objects.
+ * @param aCollection collection of {@code InternetAddress} objects.
* @return An Email.
* @throws EmailException Indicates an invalid email address.
* @see javax.mail.internet.InternetAddress
* @since 1.0
*/
- public Email setTo(final Collection<InternetAddress> aCollection) throws EmailException
- {
- if (aCollection == null || aCollection.isEmpty())
- {
+ public Email setTo(final Collection<InternetAddress> aCollection) throws EmailException {
+ if (aCollection == null || aCollection.isEmpty()) {
throw new EmailException("Address List provided was invalid");
}
@@ -873,31 +747,22 @@ public abstract class Email
}
/**
- * Add a recipient CC to the email. The email
- * address will also be used as the personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Add a recipient CC to the email. The email address will also be used as the personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address.
* @since 1.0
*/
- public Email addCc(final String email)
- throws EmailException
- {
+ public Email addCc(final String email) throws EmailException {
return this.addCc(email, null);
}
/**
- * Add an array of CC recipients to the email. The email
- * addresses will also be used as the personal name.
- * The names will be encoded by the charset of
- * {@link #setCharset(String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
+ * Add an array of CC recipients to the email. The email addresses will also be used as the personal name. The names will be encoded by the charset of
+ * {@link #setCharset(String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it contains
* non-ASCII characters; otherwise, it is used as is.
*
* @param emails A String array.
@@ -905,16 +770,12 @@ public abstract class Email
* @throws EmailException Indicates an invalid email address.
* @since 1.3
*/
- public Email addCc(final String... emails)
- throws EmailException
- {
- if (emails == null || emails.length == 0)
- {
+ public Email addCc(final String... emails) throws EmailException {
+ if (emails == null || emails.length == 0) {
throw new EmailException("Address List provided was invalid");
}
- for (final String email : emails)
- {
+ for (final String email : emails) {
addCc(email, null);
}
@@ -922,47 +783,37 @@ public abstract class Email
}
/**
- * Add a recipient CC to the email using the specified address and the
- * specified personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Add a recipient CC to the email using the specified address and the specified personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
- * @param name A String.
+ * @param name A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address.
* @since 1.0
*/
- public Email addCc(final String email, final String name)
- throws EmailException
- {
+ public Email addCc(final String email, final String name) throws EmailException {
return addCc(email, name, this.charset);
}
/**
- * Add a recipient CC to the email using the specified address, personal
- * name, and charset encoding for the name.
+ * Add a recipient CC to the email using the specified address, personal name, and charset encoding for the name.
*
- * @param email A String.
- * @param name A String.
+ * @param email A String.
+ * @param name A String.
* @param charset The charset to encode the name with.
* @return An Email.
* @throws EmailException Indicates an invalid email address or charset.
* @since 1.1
*/
- public Email addCc(final String email, final String name, final String charset)
- throws EmailException
- {
+ public Email addCc(final String email, final String name, final String charset) throws EmailException {
this.ccList.add(createInternetAddress(email, name, charset));
return this;
}
/**
- * Sets a list of "CC" addresses. All elements in the specified
- * {@code Collection} are expected to be of type
- * {@code java.mail.internet.InternetAddress}.
+ * Sets a list of "CC" addresses. All elements in the specified {@code Collection} are expected to be of type {@code java.mail.internet.InternetAddress}.
*
* @param aCollection collection of {@code InternetAddress} objects.
* @return An Email.
@@ -970,10 +821,8 @@ public abstract class Email
* @see javax.mail.internet.InternetAddress
* @since 1.0
*/
- public Email setCc(final Collection<InternetAddress> aCollection) throws EmailException
- {
- if (aCollection == null || aCollection.isEmpty())
- {
+ public Email setCc(final Collection<InternetAddress> aCollection) throws EmailException {
+ if (aCollection == null || aCollection.isEmpty()) {
throw new EmailException("Address List provided was invalid");
}
@@ -982,31 +831,22 @@ public abstract class Email
}
/**
- * Add a blind BCC recipient to the email. The email
- * address will also be used as the personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Add a blind BCC recipient to the email. The email address will also be used as the personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address
* @since 1.0
*/
- public Email addBcc(final String email)
- throws EmailException
- {
+ public Email addBcc(final String email) throws EmailException {
return this.addBcc(email, null);
}
/**
- * Add an array of blind BCC recipients to the email. The email
- * addresses will also be used as the personal name.
- * The names will be encoded by the charset of
- * {@link #setCharset(String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
+ * Add an array of blind BCC recipients to the email. The email addresses will also be used as the personal name. The names will be encoded by the charset
+ * of {@link #setCharset(String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it contains
* non-ASCII characters; otherwise, it is used as is.
*
* @param emails A String array.
@@ -1014,16 +854,12 @@ public abstract class Email
* @throws EmailException Indicates an invalid email address
* @since 1.3
*/
- public Email addBcc(final String... emails)
- throws EmailException
- {
- if (emails == null || emails.length == 0)
- {
+ public Email addBcc(final String... emails) throws EmailException {
+ if (emails == null || emails.length == 0) {
throw new EmailException("Address List provided was invalid");
}
- for (final String email : emails)
- {
+ for (final String email : emails) {
addBcc(email, null);
}
@@ -1031,58 +867,46 @@ public abstract class Email
}
/**
- * Add a blind BCC recipient to the email using the specified address and
- * the specified personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Add a blind BCC recipient to the email using the specified address and the specified personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
- * @param name A String.
+ * @param name A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address
* @since 1.0
*/
- public Email addBcc(final String email, final String name)
- throws EmailException
- {
+ public Email addBcc(final String email, final String name) throws EmailException {
return addBcc(email, name, this.charset);
}
/**
- * Add a blind BCC recipient to the email using the specified address,
- * personal name, and charset encoding for the name.
+ * Add a blind BCC recipient to the email using the specified address, personal name, and charset encoding for the name.
*
- * @param email A String.
- * @param name A String.
+ * @param email A String.
+ * @param name A String.
* @param charset The charset to encode the name with.
* @return An Email.
* @throws EmailException Indicates an invalid email address
* @since 1.1
*/
- public Email addBcc(final String email, final String name, final String charset)
- throws EmailException
- {
+ public Email addBcc(final String email, final String name, final String charset) throws EmailException {
this.bccList.add(createInternetAddress(email, name, charset));
return this;
}
/**
- * Sets a list of "BCC" addresses. All elements in the specified
- * {@code Collection} are expected to be of type
- * {@code java.mail.internet.InternetAddress}.
+ * Sets a list of "BCC" addresses. All elements in the specified {@code Collection} are expected to be of type {@code java.mail.internet.InternetAddress}.
*
- * @param aCollection collection of {@code InternetAddress} objects
+ * @param aCollection collection of {@code InternetAddress} objects
* @return An Email.
* @throws EmailException Indicates an invalid email address
* @see javax.mail.internet.InternetAddress
* @since 1.0
*/
- public Email setBcc(final Collection<InternetAddress> aCollection) throws EmailException
- {
- if (aCollection == null || aCollection.isEmpty())
- {
+ public Email setBcc(final Collection<InternetAddress> aCollection) throws EmailException {
+ if (aCollection == null || aCollection.isEmpty()) {
throw new EmailException("Address List provided was invalid");
}
@@ -1091,77 +915,61 @@ public abstract class Email
}
/**
- * Add a reply to address to the email. The email
- * address will also be used as the personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Add a reply to address to the email. The email address will also be used as the personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address
* @since 1.0
*/
- public Email addReplyTo(final String email)
- throws EmailException
- {
+ public Email addReplyTo(final String email) throws EmailException {
return this.addReplyTo(email, null);
}
/**
- * Add a reply to address to the email using the specified address and
- * the specified personal name.
- * The name will be encoded by the charset of {@link #setCharset(java.lang.String) setCharset()}.
- * If it is not set, it will be encoded using
- * the Java platform's default charset (UTF-16) if it contains
- * non-ASCII characters; otherwise, it is used as is.
+ * Add a reply to address to the email using the specified address and the specified personal name. The name will be encoded by the charset of
+ * {@link #setCharset(java.lang.String) setCharset()}. If it is not set, it will be encoded using the Java platform's default charset (UTF-16) if it
+ * contains non-ASCII characters; otherwise, it is used as is.
*
* @param email A String.
- * @param name A String.
+ * @param name A String.
* @return An Email.
* @throws EmailException Indicates an invalid email address
* @since 1.0
*/
- public Email addReplyTo(final String email, final String name)
- throws EmailException
- {
+ public Email addReplyTo(final String email, final String name) throws EmailException {
return addReplyTo(email, name, this.charset);
}
/**
- * Add a reply to address to the email using the specified address,
- * personal name, and charset encoding for the name.
+ * Add a reply to address to the email using the specified address, personal name, and charset encoding for the name.
*
- * @param email A String.
- * @param name A String.
+ * @param email A String.
+ * @param name A String.
* @param charset The charset to encode the name with.
* @return An Email.
* @throws EmailException Indicates an invalid email address or charset.
* @since 1.1
*/
- public Email addReplyTo(final String email, final String name, final String charset)
- throws EmailException
- {
+ public Email addReplyTo(final String email, final String name, final String charset) throws EmailException {
this.replyList.add(createInternetAddress(email, name, charset));
return this;
}
/**
- * Sets a list of reply to addresses. All elements in the specified
- * {@code Collection} are expected to be of type
+ * Sets a list of reply to addresses. All elements in the specified {@code Collection} are expected to be of type
* {@code java.mail.internet.InternetAddress}.
*
- * @param aCollection collection of {@code InternetAddress} objects
- * @return An Email.
+ * @param aCollection collection of {@code InternetAddress} objects
+ * @return An Email.
* @throws EmailException Indicates an invalid email address
* @see javax.mail.internet.InternetAddress
* @since 1.1
*/
- public Email setReplyTo(final Collection<InternetAddress> aCollection) throws EmailException
- {
- if (aCollection == null || aCollection.isEmpty())
- {
+ public Email setReplyTo(final Collection<InternetAddress> aCollection) throws EmailException {
+ if (aCollection == null || aCollection.isEmpty()) {
throw new EmailException("Address List provided was invalid");
}
@@ -1170,22 +978,18 @@ public abstract class Email
}
/**
- * Used to specify the mail headers. Example:
+ * Used to specify the mail headers. Example:
*
- * X-Mailer: Sendmail, X-Priority: 1( highest )
- * or 2( high ) 3( normal ) 4( low ) and 5( lowest )
- * Disposition-Notification-To: user@domain.net
+ * X-Mailer: Sendmail, X-Priority: 1( highest ) or 2( high ) 3( normal ) 4( low ) and 5( lowest ) Disposition-Notification-To: user@domain.net
*
* @param map A Map.
* @throws IllegalArgumentException if either of the provided header / value is null or empty
* @since 1.0
*/
- public void setHeaders(final Map<String, String> map)
- {
+ public void setHeaders(final Map<String, String> map) {
this.headers.clear();
- for (final Map.Entry<String, String> entry : map.entrySet())
- {
+ for (final Map.Entry<String, String> entry : map.entrySet()) {
addHeader(entry.getKey(), entry.getValue());
}
}
@@ -1193,19 +997,16 @@ public abstract class Email
/**
* Adds a header ( name, value ) to the headers Map.
*
- * @param name A String with the name.
+ * @param name A String with the name.
* @param value A String with the value.
* @since 1.0
* @throws IllegalArgumentException if either {@code name} or {@code value} is null or empty
*/
- public void addHeader(final String name, final String value)
- {
- if (EmailUtils.isEmpty(name))
- {
+ public void addHeader(final String name, final String value) {
+ if (EmailUtils.isEmpty(name)) {
throw new IllegalArgumentException("name can not be null or empty");
}
- if (EmailUtils.isEmpty(value))
- {
+ if (EmailUtils.isEmpty(value)) {
throw new IllegalArgumentException("value can not be null or empty");
}
@@ -1219,8 +1020,7 @@ public abstract class Email
* @return The value of the header, or null if no such header.
* @since 1.5
*/
- public String getHeader(final String header)
- {
+ public String getHeader(final String header) {
return this.headers.get(header);
}
@@ -1230,8 +1030,7 @@ public abstract class Email
* @return a Map of all headers.
* @since 1.5
*/
- public Map<String, String> getHeaders()
- {
+ public Map<String, String> getHeaders() {
return this.headers;
}
@@ -1242,8 +1041,7 @@ public abstract class Email
* @return An Email.
* @since 1.0
*/
- public Email setSubject(final String aSubject)
- {
+ public Email setSubject(final String aSubject) {
this.subject = EmailUtils.replaceEndOfLineCharactersWithSpaces(aSubject);
return this;
}
@@ -1254,40 +1052,30 @@ public abstract class Email
* @return the bounce address as string
* @since 1.4
*/
- public String getBounceAddress()
- {
+ public String getBounceAddress() {
return this.bounceAddress;
}
/**
- * Sets the "bounce address" - the address to which undeliverable messages
- * will be returned. If this value is never set, then the message will be
- * sent to the address specified with the System property "mail.smtp.from",
- * or if that value is not set, then to the "from" address.
+ * Sets the "bounce address" - the address to which undeliverable messages will be returned. If this value is never set, then the message will be sent to
+ * the address specified with the System property "mail.smtp.from", or if that value is not set, then to the "from" address.
*
* @param email A String.
* @return An Email.
* @throws IllegalStateException if the mail session is already initialized
* @since 1.0
*/
- public Email setBounceAddress(final String email)
- {
+ public Email setBounceAddress(final String email) {
checkSessionAlreadyInitialized();
- if (email != null && !email.isEmpty())
- {
- try
- {
+ if (email != null && !email.isEmpty()) {
+ try {
this.bounceAddress = createInternetAddress(email, null, this.charset).getAddress();
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
// Can't throw 'EmailException' to keep backward-compatibility
throw new IllegalArgumentException("Failed to set the bounce address : " + email, e);
}
- }
- else
- {
+ } else {
this.bounceAddress = email;
}
@@ -1295,8 +1083,7 @@ public abstract class Email
}
/**
- * Define the content of the mail. It should be overridden by the
- * subclasses.
+ * Define the content of the mail. It should be overridden by the subclasses.
*
* @param msg A String.
* @return An Email.
@@ -1306,36 +1093,27 @@ public abstract class Email
public abstract Email setMsg(String msg) throws EmailException;
/**
- * Does the work of actually building the MimeMessage. Please note that
- * a user rarely calls this method directly and only if he/she is
- * interested in the sending the underlying MimeMessage without
- * commons-email.
+ * Does the work of actually building the MimeMessage. Please note that a user rarely calls this method directly and only if he/she is interested in the
+ * sending the underlying MimeMessage without commons-email.
*
* @throws IllegalStateException if the MimeMessage was already built
- * @throws EmailException if there was an error.
+ * @throws EmailException if there was an error.
* @since 1.0
*/
- public void buildMimeMessage() throws EmailException
- {
- if (this.message != null)
- {
+ public void buildMimeMessage() throws EmailException {
+ if (this.message != null) {
// [EMAIL-95] we assume that an email is not reused therefore invoking
// buildMimeMessage() more than once is illegal.
throw new IllegalStateException("The MimeMessage is already built.");
}
- try
- {
+ try {
this.message = this.createMimeMessage(this.getMailSession());
- if (EmailUtils.isNotEmpty(this.subject))
- {
- if (EmailUtils.isNotEmpty(this.charset))
- {
+ if (EmailUtils.isNotEmpty(this.subject)) {
+ if (EmailUtils.isNotEmpty(this.charset)) {
this.message.setSubject(this.subject, this.charset);
- }
- else
- {
+ } else {
this.message.setSubject(this.subject);
}
}
@@ -1343,104 +1121,69 @@ public abstract class Email
// update content type (and encoding)
this.updateContentType(this.contentType);
- if (this.content != null)
- {
- if (EmailConstants.TEXT_PLAIN.equalsIgnoreCase(this.contentType)
- && this.content instanceof String)
- {
+ if (this.content != null) {
+ if (EmailConstants.TEXT_PLAIN.equalsIgnoreCase(this.contentType) && this.content instanceof String) {
// EMAIL-104: call explicitly setText to use default mime charset
- // (property "mail.mime.charset") in case none has been set
+ // (property "mail.mime.charset") in case none has been set
this.message.setText(this.content.toString(), this.charset);
- }
- else
- {
+ } else {
this.message.setContent(this.content, this.contentType);
}
- }
- else if (this.emailBody != null)
- {
- if (this.contentType == null)
- {
+ } else if (this.emailBody != null) {
+ if (this.contentType == null) {
this.message.setContent(this.emailBody);
- }
- else
- {
+ } else {
this.message.setContent(this.emailBody, this.contentType);
}
- }
- else
- {
+ } else {
this.message.setText("");
}
- if (this.fromAddress != null)
- {
+ if (this.fromAddress != null) {
this.message.setFrom(this.fromAddress);
- }
- else
- {
- if (session.getProperty(EmailConstants.MAIL_SMTP_FROM) == null
- && session.getProperty(EmailConstants.MAIL_FROM) == null)
- {
+ } else {
+ if (session.getProperty(EmailConstants.MAIL_SMTP_FROM) == null && session.getProperty(EmailConstants.MAIL_FROM) == null) {
throw new EmailException("From address required");
}
}
- if (this.toList.size() + this.ccList.size() + this.bccList.size() == 0)
- {
+ if (this.toList.size() + this.ccList.size() + this.bccList.size() == 0) {
throw new EmailException("At least one receiver address required");
}
- if (!this.toList.isEmpty())
- {
- this.message.setRecipients(
- Message.RecipientType.TO,
- this.toInternetAddressArray(this.toList));
+ if (!this.toList.isEmpty()) {
+ this.message.setRecipients(Message.RecipientType.TO, this.toInternetAddressArray(this.toList));
}
- if (!this.ccList.isEmpty())
- {
- this.message.setRecipients(
- Message.RecipientType.CC,
- this.toInternetAddressArray(this.ccList));
+ if (!this.ccList.isEmpty()) {
+ this.message.setRecipients(Message.RecipientType.CC, this.toInternetAddressArray(this.ccList));
}
- if (!this.bccList.isEmpty())
- {
- this.message.setRecipients(
- Message.RecipientType.BCC,
- this.toInternetAddressArray(this.bccList));
+ if (!this.bccList.isEmpty()) {
+ this.message.setRecipients(Message.RecipientType.BCC, this.toInternetAddressArray(this.bccList));
}
- if (!this.replyList.isEmpty())
- {
- this.message.setReplyTo(
- this.toInternetAddressArray(this.replyList));
+ if (!this.replyList.isEmpty()) {
+ this.message.setReplyTo(this.toInternetAddressArray(this.replyList));
}
- if (!this.headers.isEmpty())
- {
- for (final Map.Entry<String, String> entry : this.headers.entrySet())
- {
+ if (!this.headers.isEmpty()) {
+ for (final Map.Entry<String, String> entry : this.headers.entrySet()) {
final String foldedValue = createFoldedHeaderValue(entry.getKey(), entry.getValue());
this.message.addHeader(entry.getKey(), foldedValue);
}
}
- if (this.message.getSentDate() == null)
- {
+ if (this.message.getSentDate() == null) {
this.message.setSentDate(getSentDate());
}
- if (this.popBeforeSmtp)
- {
+ if (this.popBeforeSmtp) {
// TODO Why is this not a Store leak? When to close?
final Store store = session.getStore("pop3");
store.connect(this.popHost, this.popUsername, this.popPassword);
}
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
}
@@ -1450,67 +1193,51 @@ public abstract class Email
*
* @return the message id of the underlying MimeMessage
* @throws IllegalArgumentException if the MimeMessage has not been created
- * @throws EmailException the sending failed
+ * @throws EmailException the sending failed
*/
- public String sendMimeMessage()
- throws EmailException
- {
+ public String sendMimeMessage() throws EmailException {
final Object object = this.message;
Objects.requireNonNull(object, "MimeMessage has not been created yet");
- try
- {
+ try {
Transport.send(this.message);
return this.message.getMessageID();
- }
- catch (final Throwable t)
- {
- final String msg = "Sending the email to the following server failed : "
- + this.getHostName()
- + ":"
- + this.getSmtpPort();
+ } catch (final Throwable t) {
+ final String msg = "Sending the email to the following server failed : " + this.getHostName() + ":" + this.getSmtpPort();
throw new EmailException(msg, t);
}
}
/**
- * Returns the internal MimeMessage. Please note that the
- * MimeMessage is built by the buildMimeMessage() method.
+ * Returns the internal MimeMessage. Please note that the MimeMessage is built by the buildMimeMessage() method.
*
* @return the MimeMessage
*/
- public MimeMessage getMimeMessage()
- {
+ public MimeMessage getMimeMessage() {
return this.message;
}
/**
- * Sends the email. Internally we build a MimeMessage
- * which is afterwards sent to the SMTP server.
+ * Sends the email. Internally we build a MimeMessage which is afterwards sent to the SMTP server.
*
* @return the message id of the underlying MimeMessage
- * @throws IllegalStateException if the MimeMessage was already built, that is, {@link #buildMimeMessage()}
- * was already called
- * @throws EmailException the sending failed
+ * @throws IllegalStateException if the MimeMessage was already built, that is, {@link #buildMimeMessage()} was already called
+ * @throws EmailException the sending failed
*/
- public String send() throws EmailException
- {
+ public String send() throws EmailException {
this.buildMimeMessage();
return this.sendMimeMessage();
}
/**
- * Sets the sent date for the email. The sent date will default to the
- * current date if not explicitly set.
+ * Sets the sent date for the email. The sent date will default to the current date if not explicitly set.
*
* @param date Date to use as the sent date on the email
* @since 1.0
*/
- public void setSentDate(final Date date)
- {
- if (date != null)
- {
+ public void setSentDate(final Date date) {
+ if (date != null) {
// create a separate instance to keep findbugs happy
this.sentDate = new Date(date.getTime());
}
@@ -1522,10 +1249,8 @@ public abstract class Email
* @return date to be used as the sent date for the email
* @since 1.0
*/
- public Date getSentDate()
- {
- if (this.sentDate == null)
- {
+ public Date getSentDate() {
+ if (this.sentDate == null) {
return new Date();
}
return new Date(this.sentDate.getTime());
@@ -1536,8 +1261,7 @@ public abstract class Email
*
* @return email subject
*/
- public String getSubject()
- {
+ public String getSubject() {
return this.subject;
}
@@ -1546,8 +1270,7 @@ public abstract class Email
*
* @return from address
*/
- public InternetAddress getFromAddress()
- {
+ public InternetAddress getFromAddress() {
return this.fromAddress;
}
@@ -1556,14 +1279,11 @@ public abstract class Email
*
* @return host name
*/
- public String getHostName()
- {
- if (this.session != null)
- {
+ public String getHostName() {
+ if (this.session != null) {
return this.session.getProperty(EmailConstants.MAIL_HOST);
}
- if (EmailUtils.isNotEmpty(this.hostName))
- {
+ if (EmailUtils.isNotEmpty(this.hostName)) {
return this.hostName;
}
return null;
@@ -1574,14 +1294,11 @@ public abstract class Email
*
* @return SMTP port
*/
- public String getSmtpPort()
- {
- if (this.session != null)
- {
+ public String getSmtpPort() {
+ if (this.session != null) {
return this.session.getProperty(EmailConstants.MAIL_PORT);
}
- if (EmailUtils.isNotEmpty(this.smtpPort))
- {
+ if (EmailUtils.isNotEmpty(this.smtpPort)) {
return this.smtpPort;
}
return null;
@@ -1593,8 +1310,7 @@ public abstract class Email
* @return true if using STARTTLS for authentication, false otherwise
* @since 1.3
*/
- public boolean isStartTLSRequired()
- {
+ public boolean isStartTLSRequired() {
return this.startTlsRequired;
}
@@ -1604,35 +1320,30 @@ public abstract class Email
* @return true if using STARTTLS for authentication, false otherwise
* @since 1.3
*/
- public boolean isStartTLSEnabled()
- {
+ public boolean isStartTLSEnabled() {
return this.startTlsEnabled || tls;
}
/**
- * Gets whether the client is configured to try to enable STARTTLS.
- * See EMAIL-105 for reason of deprecation.
+ * Gets whether the client is configured to try to enable STARTTLS. See EMAIL-105 for reason of deprecation.
*
* @deprecated since 1.3, use isStartTLSEnabled() instead
* @return true if using STARTTLS for authentication, false otherwise
* @since 1.1
*/
@Deprecated
- public boolean isTLS()
- {
+ public boolean isTLS() {
return isStartTLSEnabled();
}
/**
- * Utility to copy List of known InternetAddress objects into an
- * array.
+ * Utility to copy List of known InternetAddress objects into an array.
*
* @param list A List.
* @return An InternetAddress[].
* @since 1.0
*/
- protected InternetAddress[] toInternetAddressArray(final List<InternetAddress> list)
- {
+ protected InternetAddress[] toInternetAddressArray(final List<InternetAddress> list) {
return list.toArray(EMPTY_INTERNET_ADDRESS_ARRAY);
}
@@ -1640,17 +1351,12 @@ public abstract class Email
* Sets details regarding "pop3 before SMTP" authentication.
*
* @param newPopBeforeSmtp Whether or not to log into pop3 server before sending mail.
- * @param newPopHost The pop3 host to use.
- * @param newPopUsername The pop3 username.
- * @param newPopPassword The pop3 password.
+ * @param newPopHost The pop3 host to use.
+ * @param newPopUsername The pop3 username.
+ * @param newPopPassword The pop3 password.
* @since 1.0
*/
- public void setPopBeforeSmtp(
- final boolean newPopBeforeSmtp,
- final String newPopHost,
- final String newPopUsername,
- final String newPopPassword)
- {
+ public void setPopBeforeSmtp(final boolean newPopBeforeSmtp, final String newPopHost, final String newPopUsername, final String newPopPassword) {
this.popBeforeSmtp = newPopBeforeSmtp;
this.popHost = newPopHost;
this.popUsername = newPopUsername;
@@ -1658,15 +1364,13 @@ public abstract class Email
}
/**
- * Returns whether SSL/TLS encryption for the transport is currently enabled (SMTPS/POPS).
- * See EMAIL-105 for reason of deprecation.
+ * Returns whether SSL/TLS encryption for the transport is currently enabled (SMTPS/POPS). See EMAIL-105 for reason of deprecation.
*
* @deprecated since 1.3, use isSSLOnConnect() instead
* @return true if SSL enabled for the transport
*/
@Deprecated
- public boolean isSSL()
- {
+ public boolean isSSL() {
return isSSLOnConnect();
}
@@ -1676,27 +1380,24 @@ public abstract class Email
* @return true if SSL enabled for the transport
* @since 1.3
*/
- public boolean isSSLOnConnect()
- {
+ public boolean isSSLOnConnect() {
return sslOnConnect || ssl;
}
/**
- * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS).
- * See EMAIL-105 for reason of deprecation.
+ * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). See EMAIL-105 for reason of deprecation.
*
* @deprecated since 1.3, use setSSLOnConnect() instead
* @param ssl whether to enable the SSL transport
*/
@Deprecated
- public void setSSL(final boolean ssl)
- {
+ public void setSSL(final boolean ssl) {
setSSLOnConnect(ssl);
}
/**
- * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS).
- * Takes precedence over {@link #setStartTLSRequired(boolean)}
+ * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). Takes precedence over
+ * {@link #setStartTLSRequired(boolean)}
* <p>
* Defaults to {@link #sslSmtpPort}; can be overridden by using {@link #setSslSmtpPort(String)}
*
@@ -1705,8 +1406,7 @@ public abstract class Email
* @throws IllegalStateException if the mail session is already initialized
* @since 1.3
*/
- public Email setSSLOnConnect(final boolean ssl)
- {
+ public Email setSSLOnConnect(final boolean ssl) {
checkSessionAlreadyInitialized();
this.sslOnConnect = ssl;
this.ssl = ssl;
@@ -1714,13 +1414,12 @@ public abstract class Email
}
/**
- * Is the server identity checked as specified by RFC 2595
- *
- * @return true if the server identity is checked
- * @since 1.3
- */
- public boolean isSSLCheckServerIdentity()
- {
+ * Is the server identity checked as specified by RFC 2595
+ *
+ * @return true if the server identity is checked
+ * @since 1.3
+ */
+ public boolean isSSLCheckServerIdentity() {
return sslCheckServerIdentity;
}
@@ -1732,8 +1431,7 @@ public abstract class Email
* @throws IllegalStateException if the mail session is already initialized
* @since 1.3
*/
- public Email setSSLCheckServerIdentity(final boolean sslCheckServerIdentity)
- {
+ public Email setSSLCheckServerIdentity(final boolean sslCheckServerIdentity) {
checkSessionAlreadyInitialized();
this.sslCheckServerIdentity = sslCheckServerIdentity;
return this;
@@ -1744,60 +1442,51 @@ public abstract class Email
*
* @return the current SSL port used by the SMTP transport
*/
- public String getSslSmtpPort()
- {
- if (this.session != null)
- {
+ public String getSslSmtpPort() {
+ if (this.session != null) {
return this.session.getProperty(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_PORT);
}
- if (EmailUtils.isNotEmpty(this.sslSmtpPort))
- {
+ if (EmailUtils.isNotEmpty(this.sslSmtpPort)) {
return this.sslSmtpPort;
}
return null;
}
/**
- * Sets the SSL port to use for the SMTP transport. Defaults to the standard
- * port, 465.
+ * Sets the SSL port to use for the SMTP transport. Defaults to the standard port, 465.
*
* @param sslSmtpPort the SSL port to use for the SMTP transport
* @throws IllegalStateException if the mail session is already initialized
* @see #setSmtpPort(int)
*/
- public void setSslSmtpPort(final String sslSmtpPort)
- {
+ public void setSslSmtpPort(final String sslSmtpPort) {
checkSessionAlreadyInitialized();
this.sslSmtpPort = sslSmtpPort;
}
/**
- * If partial sending of email enabled.
- *
- * @return true if sending partial email is enabled
- * @since 1.3.2
- */
- public boolean isSendPartial()
- {
+ * If partial sending of email enabled.
+ *
+ * @return true if sending partial email is enabled
+ * @since 1.3.2
+ */
+ public boolean isSendPartial() {
return sendPartial;
}
/**
* Sets whether the email is partially send in case of invalid addresses.
* <p>
- * In case the mail server rejects an address as invalid, the call to {@link #send()}
- * may throw a {@link javax.mail.SendFailedException}, even if partial send mode is enabled (emails
- * to valid addresses will be transmitted). In case the email server does not reject
- * invalid addresses immediately, but return a bounce message, no exception will be thrown
- * by the {@link #send()} method.
+ * In case the mail server rejects an address as invalid, the call to {@link #send()} may throw a {@link javax.mail.SendFailedException}, even if partial
+ * send mode is enabled (emails to valid addresses will be transmitted). In case the email server does not reject invalid addresses immediately, but return
+ * a bounce message, no exception will be thrown by the {@link #send()} method.
*
* @param sendPartial whether to enable partial send mode
* @return An Email.
* @throws IllegalStateException if the mail session is already initialized
* @since 1.3.2
*/
- public Email setSendPartial(final boolean sendPartial)
- {
+ public Email setSendPartial(final boolean sendPartial) {
checkSessionAlreadyInitialized();
this.sendPartial = sendPartial;
return this;
@@ -1808,8 +1497,7 @@ public abstract class Email
*
* @return List addresses
*/
- public List<InternetAddress> getToAddresses()
- {
+ public List<InternetAddress> getToAddresses() {
return this.toList;
}
@@ -1818,8 +1506,7 @@ public abstract class Email
*
* @return List addresses
*/
- public List<InternetAddress> getCcAddresses()
- {
+ public List<InternetAddress> getCcAddresses() {
return this.ccList;
}
@@ -1828,8 +1515,7 @@ public abstract class Email
*
* @return List addresses
*/
- public List<InternetAddress> getBccAddresses()
- {
+ public List<InternetAddress> getBccAddresses() {
return this.bccList;
}
@@ -1838,8 +1524,7 @@ public abstract class Email
*
* @return List addresses
*/
- public List<InternetAddress> getReplyToAddresses()
- {
+ public List<InternetAddress> getReplyToAddresses() {
return this.replyList;
}
@@ -1849,21 +1534,18 @@ public abstract class Email
* @return the timeout in milliseconds.
* @since 1.2
*/
- public int getSocketConnectionTimeout()
- {
+ public int getSocketConnectionTimeout() {
return this.socketConnectionTimeout;
}
/**
- * Sets the socket connection timeout value in milliseconds.
- * Default is a 60 second timeout.
+ * Sets the socket connection timeout value in milliseconds. Default is a 60 second timeout.
*
* @param socketConnectionTimeout the connection timeout
* @throws IllegalStateException if the mail session is already initialized
* @since 1.2
*/
- public void setSocketConnectionTimeout(final int socketConnectionTimeout)
- {
+ public void setSocketConnectionTimeout(final int socketConnectionTimeout) {
checkSessionAlreadyInitialized();
this.socketConnectionTimeout = socketConnectionTimeout;
}
@@ -1874,62 +1556,51 @@ public abstract class Email
* @return the socket I/O timeout
* @since 1.2
*/
- public int getSocketTimeout()
- {
+ public int getSocketTimeout() {
return this.socketTimeout;
}
/**
- * Sets the socket I/O timeout value in milliseconds.
- * Default is 60 second timeout.
+ * Sets the socket I/O timeout value in milliseconds. Default is 60 second timeout.
*
* @param socketTimeout the socket I/O timeout
* @throws IllegalStateException if the mail session is already initialized
* @since 1.2
*/
- public void setSocketTimeout(final int socketTimeout)
- {
+ public void setSocketTimeout(final int socketTimeout) {
checkSessionAlreadyInitialized();
this.socketTimeout = socketTimeout;
}
/**
- * Factory method to create a customized MimeMessage which can be
- * implemented by a derived class, e.g. to set the message id.
+ * Factory method to create a customized MimeMessage which can be implemented by a derived class, e.g. to set the message id.
*
* @param aSession mail session to be used
* @return the newly created message
*/
- protected MimeMessage createMimeMessage(final Session aSession)
- {
+ protected MimeMessage createMimeMessage(final Session aSession) {
return new MimeMessage(aSession);
}
/**
* Create a folded header value containing 76 character chunks.
*
- * @param name the name of the header
+ * @param name the name of the header
* @param value the value of the header
* @return the folded header value
* @throws IllegalArgumentException if either the name or value is null or empty
*/
- private String createFoldedHeaderValue(final String name, final String value)
- {
- if (EmailUtils.isEmpty(name))
- {
+ private String createFoldedHeaderValue(final String name, final String value) {
+ if (EmailUtils.isEmpty(name)) {
throw new IllegalArgumentException("name can not be null or empty");
}
- if (EmailUtils.isEmpty(value))
- {
+ if (EmailUtils.isEmpty(value)) {
throw new IllegalArgumentException("value can not be null or empty");
}
- try
- {
+ try {
return MimeUtility.fold(name.length() + 2, MimeUtility.encodeText(value, this.charset, null));
- }
- catch (final UnsupportedEncodingException e)
- {
+ } catch (final UnsupportedEncodingException e) {
return value;
}
}
@@ -1937,31 +1608,24 @@ public abstract class Email
/**
* Creates a InternetAddress.
*
- * @param email An email address.
- * @param name A name.
+ * @param email An email address.
+ * @param name A name.
* @param charsetName The name of the charset to encode the name with.
* @return An internet address.
* @throws EmailException Thrown when the supplied address, name or charset were invalid.
*/
- private InternetAddress createInternetAddress(final String email, final String name, final String charsetName)
- throws EmailException
- {
+ private InternetAddress createInternetAddress(final String email, final String name, final String charsetName) throws EmailException {
InternetAddress address;
- try
- {
+ try {
address = new InternetAddress(new IDNEmailAddressConverter().toASCII(email));
// check name input
- if (EmailUtils.isNotEmpty(name))
- {
+ if (EmailUtils.isNotEmpty(name)) {
// check charset input.
- if (EmailUtils.isEmpty(charsetName))
- {
+ if (EmailUtils.isEmpty(charsetName)) {
address.setPersonal(name);
- }
- else
- {
+ } else {
// canonicalize the charset name and make sure
// the current platform supports it.
final Charset set = Charset.forName(charsetName);
@@ -1972,25 +1636,19 @@ public abstract class Email
// run sanity check on new InternetAddress object; if this fails
// it will throw AddressException.
address.validate();
- }
- catch (final AddressException | UnsupportedEncodingException e)
- {
+ } catch (final AddressException | UnsupportedEncodingException e) {
throw new EmailException(e);
}
return address;
}
/**
- * When a mail session is already initialized setting the
- * session properties has no effect. In order to flag the
- * problem throw an IllegalStateException.
+ * When a mail session is already initialized setting the session properties has no effect. In order to flag the problem throw an IllegalStateException.
*
* @throws IllegalStateException when the mail session is already initialized
*/
- private void checkSessionAlreadyInitialized()
- {
- if (this.session != null)
- {
+ private void checkSessionAlreadyInitialized() {
+ if (this.session != null) {
throw new IllegalStateException("The mail session is already initialized");
}
}
diff --git a/src/main/java/org/apache/commons/mail/EmailAttachment.java b/src/main/java/org/apache/commons/mail/EmailAttachment.java
index 83c4149..e46f635 100644
--- a/src/main/java/org/apache/commons/mail/EmailAttachment.java
+++ b/src/main/java/org/apache/commons/mail/EmailAttachment.java
@@ -23,8 +23,7 @@ import java.net.URL;
*
* @since 1.0
*/
-public class EmailAttachment
-{
+public class EmailAttachment {
/** Definition of the part being an attachment. */
public static final String ATTACHMENT = javax.mail.Part.ATTACHMENT;
@@ -52,8 +51,7 @@ public class EmailAttachment
* @return A String.
* @since 1.0
*/
- public String getDescription()
- {
+ public String getDescription() {
return description;
}
@@ -63,8 +61,7 @@ public class EmailAttachment
* @return A String.
* @since 1.0
*/
- public String getName()
- {
+ public String getName() {
return name;
}
@@ -74,8 +71,7 @@ public class EmailAttachment
* @return A String.
* @since 1.0
*/
- public String getPath()
- {
+ public String getPath() {
return path;
}
@@ -85,8 +81,7 @@ public class EmailAttachment
* @return A URL.
* @since 1.0
*/
- public URL getURL()
- {
+ public URL getURL() {
return url;
}
@@ -96,8 +91,7 @@ public class EmailAttachment
* @return A String.
* @since 1.0
*/
- public String getDisposition()
- {
+ public String getDisposition() {
return disposition;
}
@@ -107,8 +101,7 @@ public class EmailAttachment
* @param desc A String.
* @since 1.0
*/
- public void setDescription(final String desc)
- {
+ public void setDescription(final String desc) {
this.description = desc;
}
@@ -118,14 +111,12 @@ public class EmailAttachment
* @param aName A String.
* @since 1.0
*/
- public void setName(final String aName)
- {
+ public void setName(final String aName) {
this.name = aName;
}
/**
- * Sets the path to the attachment. The path can be absolute or relative
- * and should include the file name.
+ * Sets the path to the attachment. The path can be absolute or relative and should include the file name.
* <p>
* Example: /home/user/images/image.jpg<br>
* Example: images/image.jpg
@@ -133,8 +124,7 @@ public class EmailAttachment
* @param aPath A String.
* @since 1.0
*/
- public void setPath(final String aPath)
- {
+ public void setPath(final String aPath) {
this.path = aPath;
}
@@ -144,8 +134,7 @@ public class EmailAttachment
* @param aUrl A URL.
* @since 1.0
*/
- public void setURL(final URL aUrl)
- {
+ public void setURL(final URL aUrl) {
this.url = aUrl;
}
@@ -155,8 +144,7 @@ public class EmailAttachment
* @param aDisposition A String.
* @since 1.0
*/
- public void setDisposition(final String aDisposition)
- {
+ public void setDisposition(final String aDisposition) {
this.disposition = aDisposition;
}
}
diff --git a/src/main/java/org/apache/commons/mail/EmailConstants.java b/src/main/java/org/apache/commons/mail/EmailConstants.java
index 64fa316..4363ae8 100644
--- a/src/main/java/org/apache/commons/mail/EmailConstants.java
+++ b/src/main/java/org/apache/commons/mail/EmailConstants.java
@@ -19,14 +19,12 @@ package org.apache.commons.mail;
/**
* Constants used by Email classes.
*
- * A description of the mail session parameter you find at
- * <a href="http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html">
+ * A description of the mail session parameter you find at <a href="http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html">
* http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html</a>.
*
* @since 1.3
*/
-public final class EmailConstants
-{
+public final class EmailConstants {
/** @deprecated since 1.3, not in use since 1.0 */
@Deprecated
public static final String SENDER_EMAIL = "sender.email";
@@ -123,24 +121,28 @@ public final class EmailConstants
/**
* Indicates if the STARTTLS command shall be used to initiate a TLS-secured connection.
+ *
* @since 1.1
*/
public static final String MAIL_TRANSPORT_STARTTLS_ENABLE = "mail.smtp.starttls.enable";
/**
* Whether to use {@link java.net.Socket} as a fallback if the initial connection fails or not.
+ *
* @since 1.1
*/
public static final String MAIL_SMTP_SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback";
/**
* Specifies the {@link javax.net.SocketFactory} class to create smtp sockets.
+ *
* @since 1.1
*/
public static final String MAIL_SMTP_SOCKET_FACTORY_CLASS = "mail.smtp.socketFactory.class";
/**
* Specifies the port to connect to when using a socket factory.
+ *
* @since 1.1
*/
public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "mail.smtp.socketFactory.port";
@@ -151,12 +153,14 @@ public final class EmailConstants
/**
* Socket connection timeout value in milliseconds. Default is infinite timeout.
+ *
* @since 1.2
*/
public static final String MAIL_SMTP_CONNECTIONTIMEOUT = "mail.smtp.connectiontimeout";
/**
* Socket I/O timeout value in milliseconds. Default is infinite timeout.
+ *
* @since 1.2
*/
public static final String MAIL_SMTP_TIMEOUT = "mail.smtp.timeout";
@@ -167,37 +171,42 @@ public final class EmailConstants
/**
* Default socket timeout.
+ *
* @since 1.3
*/
public static final int SOCKET_TIMEOUT_MS = 60000;
/**
- * If true, requires the use of the STARTTLS command. If the server doesn't support
- * the STARTTLS command, the connection will fail.
+ * If true, requires the use of the STARTTLS command. If the server doesn't support the STARTTLS command, the connection will fail.
+ *
* @since 1.3
*/
public static final String MAIL_TRANSPORT_STARTTLS_REQUIRED = "mail.smtp.starttls.required";
/**
* If set to true, use SSL to connect and use the SSL port by default.
+ *
* @since 1.3
*/
public static final String MAIL_SMTP_SSL_ENABLE = "mail.smtp.ssl.enable";
/**
* If set to true, check the server identity as specified in RFC 2595.
+ *
* @since 1.3
*/
public static final String MAIL_SMTP_SSL_CHECKSERVERIDENTITY = "mail.smtp.ssl.checkserveridentity";
/**
* Specifies the {@link javax.net.ssl.SSLSocketFactory} class to use to create SMTP SSL sockets.
+ *
* @since 1.3
*/
public static final String MAIL_SMTP_SSL_SOCKET_FACTORY_CLASS = "mail.smtp.ssl.socketFactory.class";
/**
* Specifies the port to connect to when using the SMTP SSL socket factory.
+ *
* @since 1.3
*/
public static final String MAIL_SMTP_SSL_SOCKET_FACTORY_PORT = "mail.smtp.ssl.socketFactory.port";
@@ -207,25 +216,24 @@ public final class EmailConstants
/////////////////////////////////////////////////////////////////////////
/**
- * If set to true, and a message has some valid and some invalid addresses, send the message anyway,
- * reporting the partial failure with a SendFailedException.
- * If set to false (the default), the message is not sent to any of the recipients
- * if there is an invalid recipient address.
+ * If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a
+ * SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address.
+ *
* @since 1.3.2
*/
public static final String MAIL_SMTP_SEND_PARTIAL = "mail.smtp.sendpartial";
/**
- * If set to true, and a message has some valid and some invalid addresses, send the message anyway,
- * reporting the partial failure with a SendFailedException.
- * If set to false (the default), the message is not sent to any of the recipients
- * if there is an invalid recipient address.
+ * If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a
+ * SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address.
+ *
* @since 1.3.2
*/
public static final String MAIL_SMTPS_SEND_PARTIAL = "mail.smtps.sendpartial";
/**
* Defines the default mime charset to use when none has been specified for the message.
+ *
* @since 1.3.2
*/
public static final String MAIL_MIME_CHARSET = "mail.mime.charset";
@@ -236,13 +244,13 @@ public final class EmailConstants
/**
* The from email address.
+ *
* @since 1.4
*/
public static final String MAIL_FROM = "mail.from";
/** Hide constructor. */
- private EmailConstants()
- {
+ private EmailConstants() {
// do nothing
}
diff --git a/src/main/java/org/apache/commons/mail/EmailException.java b/src/main/java/org/apache/commons/mail/EmailException.java
index c702390..ee50c8d 100644
--- a/src/main/java/org/apache/commons/mail/EmailException.java
+++ b/src/main/java/org/apache/commons/mail/EmailException.java
@@ -27,58 +27,45 @@ import java.nio.charset.Charset;
* <p>
* Adapted from FunctorException in Commons Collections.
* <p>
- * Emulation support for nested exceptions has been removed in {@code Email 1.3},
- * supported by JDK ≥ 1.4.
+ * Emulation support for nested exceptions has been removed in {@code Email 1.3}, supported by JDK ≥ 1.4.
*
* @since 1.0
*/
-public class EmailException
- extends Exception
-{
+public class EmailException extends Exception {
/** Serializable version identifier. */
private static final long serialVersionUID = 5550674499282474616L;
/**
- * Constructs a new {@code EmailException} with no
- * detail message.
+ * Constructs a new {@code EmailException} with no detail message.
*/
- public EmailException()
- {
+ public EmailException() {
}
/**
- * Constructs a new {@code EmailException} with specified
- * detail message.
+ * Constructs a new {@code EmailException} with specified detail message.
*
- * @param msg the error message.
+ * @param msg the error message.
*/
- public EmailException(final String msg)
- {
+ public EmailException(final String msg) {
super(msg);
}
/**
- * Constructs a new {@code EmailException} with specified
- * nested {@code Throwable} root cause.
+ * Constructs a new {@code EmailException} with specified nested {@code Throwable} root cause.
*
- * @param rootCause the exception or error that caused this exception
- * to be thrown.
+ * @param rootCause the exception or error that caused this exception to be thrown.
*/
- public EmailException(final Throwable rootCause)
- {
+ public EmailException(final Throwable rootCause) {
super(rootCause);
}
/**
- * Constructs a new {@code EmailException} with specified
- * detail message and nested {@code Throwable} root cause.
+ * Constructs a new {@code EmailException} with specified detail message and nested {@code Throwable} root cause.
*
- * @param msg the error message.
- * @param rootCause the exception or error that caused this exception
- * to be thrown.
+ * @param msg the error message.
+ * @param rootCause the exception or error that caused this exception to be thrown.
*/
- public EmailException(final String msg, final Throwable rootCause)
- {
+ public EmailException(final String msg, final Throwable rootCause) {
super(msg, rootCause);
}
@@ -86,21 +73,18 @@ public class EmailException
* Prints the stack trace of this exception to the standard error stream.
*/
@Override
- public void printStackTrace()
- {
+ public void printStackTrace() {
printStackTrace(System.err);
}
/**
* Prints the stack trace of this exception to the specified stream.
*
- * @param out the {@code PrintStream} to use for output
+ * @param out the {@code PrintStream} to use for output
*/
@Override
- public void printStackTrace(final PrintStream out)
- {
- synchronized (out)
- {
+ public void printStackTrace(final PrintStream out) {
+ synchronized (out) {
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, Charset.defaultCharset()), false);
printStackTrace(pw);
@@ -112,13 +96,11 @@ public class EmailException
/**
* Prints the stack trace of this exception to the specified writer.
*
- * @param out the {@code PrintWriter} to use for output
+ * @param out the {@code PrintWriter} to use for output
*/
@Override
- public void printStackTrace(final PrintWriter out)
- {
- synchronized (out)
- {
+ public void printStackTrace(final PrintWriter out) {
+ synchronized (out) {
super.printStackTrace(out);
}
}
diff --git a/src/main/java/org/apache/commons/mail/EmailUtils.java b/src/main/java/org/apache/commons/mail/EmailUtils.java
index fb0033f..4fec3ef 100644
--- a/src/main/java/org/apache/commons/mail/EmailUtils.java
+++ b/src/main/java/org/apache/commons/mail/EmailUtils.java
@@ -32,8 +32,7 @@ import org.apache.commons.mail.util.MimeMessageUtils;
* Utility methods used by commons-email.
*
* <p>
- * These methods are copied from other commons components (commons-lang) to avoid creating
- * a dependency for such a small component.
+ * These methods are copied from other commons components (commons-lang) to avoid creating a dependency for such a small component.
* </p>
*
* <p>
@@ -42,11 +41,9 @@ import org.apache.commons.mail.util.MimeMessageUtils;
*
* @since 1.0
*/
-final class EmailUtils
-{
+final class EmailUtils {
/**
- * Random object used by random method. This has to be not local to the random method
- * so as to not return the same value in the same millisecond.
+ * Random object used by random method. This has to be not local to the random method so as to not return the same value in the same millisecond.
*/
private static final Random RANDOM = new Random();
@@ -68,17 +65,14 @@ final class EmailUtils
// Static initializer for safe_uri
static {
// alpha characters
- for (int i = 'a'; i <= 'z'; i++)
- {
+ for (int i = 'a'; i <= 'z'; i++) {
SAFE_URL.set(i);
}
- for (int i = 'A'; i <= 'Z'; i++)
- {
+ for (int i = 'A'; i <= 'Z'; i++) {
SAFE_URL.set(i);
}
// numeric characters
- for (int i = '0'; i <= '9'; i++)
- {
+ for (int i = '0'; i <= '9'; i++) {
SAFE_URL.set(i);
}
@@ -100,8 +94,7 @@ final class EmailUtils
/**
* Constructs a new {@code EmailException} with no detail message.
*/
- private EmailUtils()
- {
+ private EmailUtils() {
}
/**
@@ -113,8 +106,7 @@ final class EmailUtils
* @param str the String to check, may be null
* @return {@code true} if the String is empty or null
*/
- static boolean isEmpty(final String str)
- {
+ static boolean isEmpty(final String str) {
return str == null || str.isEmpty();
}
@@ -127,8 +119,7 @@ final class EmailUtils
* @param str the String to check, may be null
* @return {@code true} if the String is not empty and not null
*/
- static boolean isNotEmpty(final String str)
- {
+ static boolean isNotEmpty(final String str) {
return str != null && !str.isEmpty();
}
@@ -140,11 +131,11 @@ final class EmailUtils
* <p>
* Copied from Commons Lang v2.1, svn 201930
* </p>
+ *
* @param count the length of random string to create
* @return the random string
*/
- static String randomAlphabetic(final int count)
- {
+ static String randomAlphabetic(final int count) {
return random(count, 0, 0, true, false, null, RANDOM);
}
@@ -152,9 +143,8 @@ final class EmailUtils
* Creates a random string based on a variety of options, using supplied source of randomness.
*
* <p>
- * If start and end are both {@code 0}, start and end are set to {@code ' '} and {@code 'z'},
- * the ASCII printable characters, will be used, unless letters and numbers are both {@code false},
- * in which case, start and end are set to {@code 0} and {@code Integer.MAX_VALUE}.
+ * If start and end are both {@code 0}, start and end are set to {@code ' '} and {@code 'z'}, the ASCII printable characters, will be used, unless letters
+ * and numbers are both {@code false}, in which case, start and end are set to {@code 0} and {@code Integer.MAX_VALUE}.
* </p>
*
* <p>
@@ -162,50 +152,36 @@ final class EmailUtils
* </p>
*
* <p>
- * This method accepts a user-supplied {@link Random} instance to use as a source of randomness. By seeding a
- * single {@link Random} instance with a fixed seed and using it for each call, the same random sequence of strings
- * can be generated repeatedly and predictably.
+ * This method accepts a user-supplied {@link Random} instance to use as a source of randomness. By seeding a single {@link Random} instance with a fixed
+ * seed and using it for each call, the same random sequence of strings can be generated repeatedly and predictably.
* </p>
* <p>
* Copied from Commons Lang v2.1, svn 201930
* </p>
*
- * @param count the length of random string to create
- * @param start the position in set of chars to start at
- * @param end the position in set of chars to end before
+ * @param count the length of random string to create
+ * @param start the position in set of chars to start at
+ * @param end the position in set of chars to end before
* @param letters only allow letters?
* @param numbers only allow numbers?
- * @param chars the set of chars to choose randoms from. If {@code null},
- * then it will use the set of all chars.
- * @param random a source of randomness.
+ * @param chars the set of chars to choose randoms from. If {@code null}, then it will use the set of all chars.
+ * @param random a source of randomness.
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
*/
- private static String random(
- int count,
- int start,
- int end,
- final boolean letters,
- final boolean numbers,
- final char [] chars,
- final Random random)
- {
- if (count == 0)
- {
+ private static String random(int count, int start, int end, final boolean letters, final boolean numbers, final char[] chars, final Random random) {
+ if (count == 0) {
return "";
}
- if (count < 0)
- {
+ if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
- if (start == 0 && end == 0)
- {
+ if (start == 0 && end == 0) {
end = 'z' + 1;
start = ' ';
- if (!letters && !numbers)
- {
+ if (!letters && !numbers) {
start = 0;
end = Integer.MAX_VALUE;
}
@@ -214,26 +190,19 @@ final class EmailUtils
final StringBuilder buffer = new StringBuilder();
final int gap = end - start;
- while (count-- != 0)
- {
+ while (count-- != 0) {
char ch;
- if (chars == null)
- {
+ if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
- }
- else
- {
+ } else {
ch = chars[random.nextInt(gap) + start];
}
- if (letters && numbers && Character.isLetterOrDigit(ch) || letters && Character.isLetter(ch)
- || numbers && Character.isDigit(ch) || !letters && !numbers)
- {
+ if (letters && numbers && Character.isLetterOrDigit(ch) || letters && Character.isLetter(ch) || numbers && Character.isDigit(ch)
+ || !letters && !numbers) {
buffer.append(ch);
- }
- else
- {
+ } else {
count++;
}
}
@@ -247,8 +216,7 @@ final class EmailUtils
* @param input the input string to be scanned.
* @return a clean string
*/
- static String replaceEndOfLineCharactersWithSpaces(final String input)
- {
+ static String replaceEndOfLineCharactersWithSpaces(final String input) {
return input == null ? null : input.replace('\n', ' ').replace('\r', ' ');
}
@@ -259,23 +227,17 @@ final class EmailUtils
* @return a URL encoded string
* @see <a href="http://tools.ietf.org/html/rfc2392">RFC 2392</a>
*/
- static String encodeUrl(final String input)
- {
- if (input == null)
- {
+ static String encodeUrl(final String input) {
+ if (input == null) {
return null;
}
final StringBuilder builder = new StringBuilder();
- for (final byte c : input.getBytes(StandardCharsets.US_ASCII))
- {
+ for (final byte c : input.getBytes(StandardCharsets.US_ASCII)) {
final int b = c & 0xff;
- if (SAFE_URL.get(b))
- {
+ if (SAFE_URL.get(b)) {
builder.append((char) b);
- }
- else
- {
+ } else {
builder.append(ESCAPE_CHAR);
final char hex1 = Character.toUpperCase(Character.forDigit(b >> 4 & 0xF, RADIX));
final char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
@@ -289,14 +251,12 @@ final class EmailUtils
/**
* Convenience method to write a MimeMessage into a file.
*
- * @param resultFile the file containing the MimeMessage
+ * @param resultFile the file containing the MimeMessage
* @param mimeMessage the MimeMessage to write
- * @throws IOException writing the MimeMessage failed
+ * @throws IOException writing the MimeMessage failed
* @throws MessagingException writing the MimeMessage failed
*/
- static void writeMimeMessage(final File resultFile, final MimeMessage mimeMessage)
- throws IOException, MessagingException
- {
+ static void writeMimeMessage(final File resultFile, final MimeMessage mimeMessage) throws IOException, MessagingException {
MimeMessageUtils.writeMimeMessage(mimeMessage, resultFile);
}
}
diff --git a/src/main/java/org/apache/commons/mail/HtmlEmail.java b/src/main/java/org/apache/commons/mail/HtmlEmail.java
index b3e4e9e..96ec021 100644
--- a/src/main/java/org/apache/commons/mail/HtmlEmail.java
+++ b/src/main/java/org/apache/commons/mail/HtmlEmail.java
@@ -38,26 +38,25 @@ import javax.mail.internet.MimeMultipart;
/**
* An HTML multipart email.
*
- * <p>This class is used to send HTML formatted email. A text message
- * can also be set for HTML unaware email clients, such as text-based
- * email clients.
+ * <p>
+ * This class is used to send HTML formatted email. A text message can also be set for HTML unaware email clients, such as text-based email clients.
*
- * <p>This class also inherits from {@link MultiPartEmail}, so it is easy to
- * add attachments to the email.
+ * <p>
+ * This class also inherits from {@link MultiPartEmail}, so it is easy to add attachments to the email.
*
- * <p>To send an email in HTML, one should create a {@code HtmlEmail}, then
- * use the {@link #setFrom(String)}, {@link #addTo(String)} etc. methods.
- * The HTML content can be set with the {@link #setHtmlMsg(String)} method. The
- * alternative text content can be set with {@link #setTextMsg(String)}.
+ * <p>
+ * To send an email in HTML, one should create a {@code HtmlEmail}, then use the {@link #setFrom(String)}, {@link #addTo(String)} etc. methods. The HTML content
+ * can be set with the {@link #setHtmlMsg(String)} method. The alternative text content can be set with {@link #setTextMsg(String)}.
*
- * <p>Either the text or HTML can be omitted, in which case the "main"
- * part of the multipart becomes whichever is supplied rather than a
+ * <p>
+ * Either the text or HTML can be omitted, in which case the "main" part of the multipart becomes whichever is supplied rather than a
* {@code multipart/alternative}.
*
* <h2>Embedding Images and Media</h2>
*
- * <p>It is also possible to embed URLs, files, or arbitrary
- * {@code DataSource}s directly into the body of the mail:
+ * <p>
+ * It is also possible to embed URLs, files, or arbitrary {@code DataSource}s directly into the body of the mail:
+ *
* <pre>
* HtmlEmail he = new HtmlEmail();
* File img = new File("my/image.gif");
@@ -71,17 +70,14 @@ import javax.mail.internet.MimeMultipart;
* // code to set the other email fields (not shown)
* </pre>
*
- * <p>Embedded entities are tracked by their name, which for {@code File}s is
- * the file name itself and for {@code URL}s is the canonical path. It is
- * an error to bind the same name to more than one entity, and this class will
- * attempt to validate that for {@code File}s and {@code URL}s. When
- * embedding a {@code DataSource}, the code uses the {@code equals()}
- * method defined on the {@code DataSource}s to make the determination.
+ * <p>
+ * Embedded entities are tracked by their name, which for {@code File}s is the file name itself and for {@code URL}s is the canonical path. It is an error to
+ * bind the same name to more than one entity, and this class will attempt to validate that for {@code File}s and {@code URL}s. When embedding a
+ * {@code DataSource}, the code uses the {@code equals()} method defined on the {@code DataSource}s to make the determination.
*
* @since 1.0
*/
-public class HtmlEmail extends MultiPartEmail
-{
+public class HtmlEmail extends MultiPartEmail {
/** Definition of the length of generated CID's. */
public static final int CID_LENGTH = 10;
@@ -91,8 +87,7 @@ public class HtmlEmail extends MultiPartEmail
private static final String HTML_MESSAGE_END = "</pre></body></html>";
/**
- * Text part of the message. This will be used as alternative text if
- * the email client does not support HTML messages.
+ * Text part of the message. This will be used as alternative text if the email client does not support HTML messages.
*/
protected String text;
@@ -100,15 +95,13 @@ public class HtmlEmail extends MultiPartEmail
protected String html;
/**
- * @deprecated As of commons-email 1.1, no longer used. Inline embedded
- * objects are now stored in {@link #inlineEmbeds}.
+ * @deprecated As of commons-email 1.1, no longer used. Inline embedded objects are now stored in {@link #inlineEmbeds}.
*/
@Deprecated
protected List<InlineImage> inlineImages;
/**
- * Embedded images Map<String, InlineImage> where the key is the
- * user-defined image name.
+ * Embedded images Map<String, InlineImage> where the key is the user-defined image name.
*/
protected Map<String, InlineImage> inlineEmbeds = new HashMap<>();
@@ -117,14 +110,11 @@ public class HtmlEmail extends MultiPartEmail
*
* @param aText A String.
* @return An HtmlEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public HtmlEmail setTextMsg(final String aText) throws EmailException
- {
- if (EmailUtils.isEmpty(aText))
- {
+ public HtmlEmail setTextMsg(final String aText) throws EmailException {
+ if (EmailUtils.isEmpty(aText)) {
throw new EmailException("Invalid message supplied");
}
@@ -137,14 +127,11 @@ public class HtmlEmail extends MultiPartEmail
*
* @param aHtml A String.
* @return An HtmlEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public HtmlEmail setHtmlMsg(final String aHtml) throws EmailException
- {
- if (EmailUtils.isEmpty(aHtml))
- {
+ public HtmlEmail setHtmlMsg(final String aHtml) throws EmailException {
+ if (EmailUtils.isEmpty(aHtml)) {
throw new EmailException("Invalid message supplied");
}
@@ -155,37 +142,26 @@ public class HtmlEmail extends MultiPartEmail
/**
* Sets the message.
*
- * <p>This method overrides {@link MultiPartEmail#setMsg(String)} in
- * order to send an HTML message instead of a plain text message in
- * the mail body. The message is formatted in HTML for the HTML
- * part of the message; it is left as is in the alternate text
- * part.
+ * <p>
+ * This method overrides {@link MultiPartEmail#setMsg(String)} in order to send an HTML message instead of a plain text message in the mail body. The
+ * message is formatted in HTML for the HTML part of the message; it is left as is in the alternate text part.
*
* @param msg the message text to use
* @return this {@code HtmlEmail}
- * @throws EmailException if msg is null or empty;
- * see javax.mail.internet.MimeBodyPart for definitions
+ * @throws EmailException if msg is null or empty; see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
@Override
- public Email setMsg(final String msg) throws EmailException
- {
- if (EmailUtils.isEmpty(msg))
- {
+ public Email setMsg(final String msg) throws EmailException {
+ if (EmailUtils.isEmpty(msg)) {
throw new EmailException("Invalid message supplied");
}
setTextMsg(msg);
- final StringBuilder htmlMsgBuf = new StringBuilder(
- msg.length()
- + HTML_MESSAGE_START.length()
- + HTML_MESSAGE_END.length()
- );
+ final StringBuilder htmlMsgBuf = new StringBuilder(msg.length() + HTML_MESSAGE_START.length() + HTML_MESSAGE_END.length());
- htmlMsgBuf.append(HTML_MESSAGE_START)
- .append(msg)
- .append(HTML_MESSAGE_END);
+ htmlMsgBuf.append(HTML_MESSAGE_START).append(msg).append(HTML_MESSAGE_END);
setHtmlMsg(htmlMsgBuf.toString());
@@ -193,26 +169,21 @@ public class HtmlEmail extends MultiPartEmail
}
/**
- * Attempts to parse the specified {@code String} as a URL that will
- * then be embedded in the message.
+ * Attempts to parse the specified {@code String} as a URL that will then be embedded in the message.
*
* @param urlString String representation of the URL.
- * @param name The name that will be set in the file name header field.
+ * @param name The name that will be set in the file name header field.
* @return A String with the Content-ID of the URL.
- * @throws EmailException when URL supplied is invalid or if {@code name} is null
- * or empty; also see {@link javax.mail.internet.MimeBodyPart} for definitions
+ * @throws EmailException when URL supplied is invalid or if {@code name} is null or empty; also see {@link javax.mail.internet.MimeBodyPart} for
+ * definitions
*
* @see #embed(URL, String)
* @since 1.1
*/
- public String embed(final String urlString, final String name) throws EmailException
- {
- try
- {
+ public String embed(final String urlString, final String name) throws EmailException {
+ try {
return embed(new URL(urlString), name);
- }
- catch (final MalformedURLException e)
- {
+ } catch (final MalformedURLException e) {
throw new EmailException("Invalid URL", e);
}
}
@@ -220,102 +191,79 @@ public class HtmlEmail extends MultiPartEmail
/**
* Embeds an URL in the HTML.
*
- * <p>This method embeds a file located by an URL into
- * the mail body. It allows, for instance, to add inline images
- * to the email. Inline files may be referenced with a
- * {@code cid:xxxxxx} URL, where xxxxxx is the Content-ID
- * returned by the embed function. It is an error to bind the same name
- * to more than one URL; if the same URL is embedded multiple times, the
- * same Content-ID is guaranteed to be returned.
+ * <p>
+ * This method embeds a file located by an URL into the mail body. It allows, for instance, to add inline images to the email. Inline files may be
+ * referenced with a {@code cid:xxxxxx} URL, where xxxxxx is the Content-ID returned by the embed function. It is an error to bind the same name to more
+ * than one URL; if the same URL is embedded multiple times, the same Content-ID is guaranteed to be returned.
*
- * <p>While functionally the same as passing {@code URLDataSource} to
- * {@link #embed(DataSource, String, String)}, this method attempts
- * to validate the URL before embedding it in the message and will throw
- * {@code EmailException} if the validation fails. In this case, the
- * {@code HtmlEmail} object will not be changed.
+ * <p>
+ * While functionally the same as passing {@code URLDataSource} to {@link #embed(DataSource, String, String)}, this method attempts to validate the URL
+ * before embedding it in the message and will throw {@code EmailException} if the validation fails. In this case, the {@code HtmlEmail} object will not be
+ * changed.
*
* <p>
- * NOTE: Clients should take care to ensure that different URLs are bound to
- * different names. This implementation tries to detect this and throw
- * {@code EmailException}. However, it is not guaranteed to catch
- * all cases, especially when the URL refers to a remote HTTP host that
- * may be part of a virtual host cluster.
+ * NOTE: Clients should take care to ensure that different URLs are bound to different names. This implementation tries to detect this and throw
+ * {@code EmailException}. However, it is not guaranteed to catch all cases, especially when the URL refers to a remote HTTP host that may be part of a
+ * virtual host cluster.
*
- * @param url The URL of the file.
- * @param name The name that will be set in the file name header
- * field.
+ * @param url The URL of the file.
+ * @param name The name that will be set in the file name header field.
* @return A String with the Content-ID of the file.
- * @throws EmailException when URL supplied is invalid or if {@code name} is null
- * or empty; also see {@link javax.mail.internet.MimeBodyPart} for definitions
+ * @throws EmailException when URL supplied is invalid or if {@code name} is null or empty; also see {@link javax.mail.internet.MimeBodyPart} for
+ * definitions
* @since 1.0
*/
- public String embed(final URL url, final String name) throws EmailException
- {
- if (EmailUtils.isEmpty(name))
- {
+ public String embed(final URL url, final String name) throws EmailException {
+ if (EmailUtils.isEmpty(name)) {
throw new EmailException("name cannot be null or empty");
}
// check if a URLDataSource for this name has already been attached;
// if so, return the cached CID value.
final InlineImage ii = inlineEmbeds.get(name);
- if (ii != null)
- {
+ if (ii != null) {
final URLDataSource urlDataSource = (URLDataSource) ii.getDataSource();
// make sure the supplied URL points to the same thing
// as the one already associated with this name.
// NOTE: Comparing URLs with URL.equals() is a blocking operation
// in the case of a network failure therefore we use
// url.toExternalForm().equals() here.
- if (url.toExternalForm().equals(urlDataSource.getURL().toExternalForm()))
- {
+ if (url.toExternalForm().equals(urlDataSource.getURL().toExternalForm())) {
return ii.getCid();
}
- throw new EmailException("embedded name '" + name
- + "' is already bound to URL " + urlDataSource.getURL()
- + "; existing names cannot be rebound");
+ throw new EmailException("embedded name '" + name + "' is already bound to URL " + urlDataSource.getURL() + "; existing names cannot be rebound");
}
// verify that the URL is valid
InputStream is = null;
- try
- {
+ try {
is = url.openStream();
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new EmailException("Invalid URL", e);
- }
- finally
- {
- try
- {
- if (is != null)
- {
+ } finally {
+ try {
+ if (is != null) {
is.close();
}
- }
- catch (final IOException ioe) // NOPMD
- { /* sigh */ }
+ } catch (final IOException ioe) // NOPMD
+ {
+ /* sigh */ }
}
return embed(new URLDataSource(url), name);
}
/**
- * Embeds a file in the HTML. This implementation delegates to
- * {@link #embed(File, String)}.
+ * Embeds a file in the HTML. This implementation delegates to {@link #embed(File, String)}.
*
* @param file The {@code File} object to embed
* @return A String with the Content-ID of the file.
- * @throws EmailException when the supplied {@code File} cannot be
- * used; also see {@link javax.mail.internet.MimeBodyPart} for definitions
+ * @throws EmailException when the supplied {@code File} cannot be used; also see {@link javax.mail.internet.MimeBodyPart} for definitions
*
* @see #embed(File, String)
* @since 1.1
*/
- public String embed(final File file) throws EmailException
- {
+ public String embed(final File file) throws EmailException {
final String cid = EmailUtils.randomAlphabetic(HtmlEmail.CID_LENGTH).toLowerCase(Locale.ENGLISH);
return embed(file, cid);
}
@@ -323,86 +271,64 @@ public class HtmlEmail extends MultiPartEmail
/**
* Embeds a file in the HTML.
*
- * <p>This method embeds a file located by an URL into
- * the mail body. It allows, for instance, to add inline images
- * to the email. Inline files may be referenced with a
- * {@code cid:xxxxxx} URL, where xxxxxx is the Content-ID
- * returned by the embed function. Files are bound to their names, which is
- * the value returned by {@link java.io.File#getName()}. If the same file
- * is embedded multiple times, the same CID is guaranteed to be returned.
+ * <p>
+ * This method embeds a file located by an URL into the mail body. It allows, for instance, to add inline images to the email. Inline files may be
+ * referenced with a {@code cid:xxxxxx} URL, where xxxxxx is the Content-ID returned by the embed function. Files are bound to their names, which is the
+ * value returned by {@link java.io.File#getName()}. If the same file is embedded multiple times, the same CID is guaranteed to be returned.
*
- * <p>While functionally the same as passing {@code FileDataSource} to
- * {@link #embed(DataSource, String, String)}, this method attempts
- * to validate the file before embedding it in the message and will throw
- * {@code EmailException} if the validation fails. In this case, the
- * {@code HtmlEmail} object will not be changed.
+ * <p>
+ * While functionally the same as passing {@code FileDataSource} to {@link #embed(DataSource, String, String)}, this method attempts to validate the file
+ * before embedding it in the message and will throw {@code EmailException} if the validation fails. In this case, the {@code HtmlEmail} object will not be
+ * changed.
*
* @param file The {@code File} to embed
- * @param cid the Content-ID to use for the embedded {@code File}
+ * @param cid the Content-ID to use for the embedded {@code File}
* @return A String with the Content-ID of the file.
- * @throws EmailException when the supplied {@code File} cannot be used
- * or if the file has already been embedded;
- * also see {@link javax.mail.internet.MimeBodyPart} for definitions
+ * @throws EmailException when the supplied {@code File} cannot be used or if the file has already been embedded; also see
+ * {@link javax.mail.internet.MimeBodyPart} for definitions
* @since 1.1
*/
- public String embed(final File file, final String cid) throws EmailException
- {
- if (EmailUtils.isEmpty(file.getName()))
- {
+ public String embed(final File file, final String cid) throws EmailException {
+ if (EmailUtils.isEmpty(file.getName())) {
throw new EmailException("file name cannot be null or empty");
}
// verify that the File can provide a canonical path
String filePath = null;
- try
- {
+ try {
filePath = file.getCanonicalPath();
- }
- catch (final IOException ioe)
- {
- throw new EmailException("couldn't get canonical path for "
- + file.getName(), ioe);
+ } catch (final IOException ioe) {
+ throw new EmailException("couldn't get canonical path for " + file.getName(), ioe);
}
// check if a FileDataSource for this name has already been attached;
// if so, return the cached CID value.
final InlineImage ii = inlineEmbeds.get(file.getName());
- if (ii != null)
- {
+ if (ii != null) {
final FileDataSource fileDataSource = (FileDataSource) ii.getDataSource();
// make sure the supplied file has the same canonical path
// as the one already associated with this name.
String existingFilePath = null;
- try
- {
+ try {
existingFilePath = fileDataSource.getFile().getCanonicalPath();
+ } catch (final IOException ioe) {
+ throw new EmailException("couldn't get canonical path for file " + fileDataSource.getFile().getName() + "which has already been embedded", ioe);
}
- catch (final IOException ioe)
- {
- throw new EmailException("couldn't get canonical path for file "
- + fileDataSource.getFile().getName()
- + "which has already been embedded", ioe);
- }
- if (filePath.equals(existingFilePath))
- {
+ if (filePath.equals(existingFilePath)) {
return ii.getCid();
}
- throw new EmailException("embedded name '" + file.getName()
- + "' is already bound to file " + existingFilePath
- + "; existing names cannot be rebound");
+ throw new EmailException(
+ "embedded name '" + file.getName() + "' is already bound to file " + existingFilePath + "; existing names cannot be rebound");
}
// verify that the file is valid
- if (!file.exists())
- {
+ if (!file.exists()) {
throw new EmailException("file " + filePath + " doesn't exist");
}
- if (!file.isFile())
- {
+ if (!file.isFile()) {
throw new EmailException("file " + filePath + " isn't a normal file");
}
- if (!file.canRead())
- {
+ if (!file.canRead()) {
throw new EmailException("file " + filePath + " isn't readable");
}
@@ -410,33 +336,27 @@ public class HtmlEmail extends MultiPartEmail
}
/**
- * Embeds the specified {@code DataSource} in the HTML using a
- * randomly generated Content-ID. Returns the generated Content-ID string.
+ * Embeds the specified {@code DataSource} in the HTML using a randomly generated Content-ID. Returns the generated Content-ID string.
*
* @param dataSource the {@code DataSource} to embed
- * @param name the name that will be set in the file name header field
+ * @param name the name that will be set in the file name header field
* @return the generated Content-ID for this {@code DataSource}
- * @throws EmailException if the embedding fails or if {@code name} is
- * null or empty
+ * @throws EmailException if the embedding fails or if {@code name} is null or empty
* @see #embed(DataSource, String, String)
* @since 1.1
*/
- public String embed(final DataSource dataSource, final String name) throws EmailException
- {
+ public String embed(final DataSource dataSource, final String name) throws EmailException {
// check if the DataSource has already been attached;
// if so, return the cached CID value.
final InlineImage ii = inlineEmbeds.get(name);
- if (ii != null)
- {
+ if (ii != null) {
// make sure the supplied URL points to the same thing
// as the one already associated with this name.
- if (dataSource.equals(ii.getDataSource()))
- {
+ if (dataSource.equals(ii.getDataSource())) {
return ii.getCid();
}
- throw new EmailException("embedded DataSource '" + name
- + "' is already bound to name " + ii.getDataSource().toString()
- + "; existing names cannot be rebound");
+ throw new EmailException(
+ "embedded DataSource '" + name + "' is already bound to name " + ii.getDataSource().toString() + "; existing names cannot be rebound");
}
final String cid = EmailUtils.randomAlphabetic(HtmlEmail.CID_LENGTH).toLowerCase();
@@ -444,29 +364,23 @@ public class HtmlEmail extends MultiPartEmail
}
/**
- * Embeds the specified {@code DataSource} in the HTML using the
- * specified Content-ID. Returns the specified Content-ID string.
+ * Embeds the specified {@code DataSource} in the HTML using the specified Content-ID. Returns the specified Content-ID string.
*
* @param dataSource the {@code DataSource} to embed
- * @param name the name that will be set in the file name header field
- * @param cid the Content-ID to use for this {@code DataSource}
+ * @param name the name that will be set in the file name header field
+ * @param cid the Content-ID to use for this {@code DataSource}
* @return the URL encoded Content-ID for this {@code DataSource}
- * @throws EmailException if the embedding fails or if {@code name} is
- * null or empty
+ * @throws EmailException if the embedding fails or if {@code name} is null or empty
* @since 1.1
*/
- public String embed(final DataSource dataSource, final String name, final String cid)
- throws EmailException
- {
- if (EmailUtils.isEmpty(name))
- {
+ public String embed(final DataSource dataSource, final String name, final String cid) throws EmailException {
+ if (EmailUtils.isEmpty(name)) {
throw new EmailException("name cannot be null or empty");
}
final MimeBodyPart mbp = new MimeBodyPart();
- try
- {
+ try {
// URL encode the cid according to RFC 2392
final String encodedCid = EmailUtils.encodeUrl(cid);
@@ -479,42 +393,33 @@ public class HtmlEmail extends MultiPartEmail
this.inlineEmbeds.put(name, ii);
return encodedCid;
- }
- catch (final MessagingException uee)
- {
+ } catch (final MessagingException uee) {
throw new EmailException(uee);
}
}
/**
- * Does the work of actually building the MimeMessage. Please note that
- * a user rarely calls this method directly and only if he/she is
- * interested in the sending the underlying MimeMessage without
- * commons-email.
+ * Does the work of actually building the MimeMessage. Please note that a user rarely calls this method directly and only if he/she is interested in the
+ * sending the underlying MimeMessage without commons-email.
*
* @throws EmailException if there was an error.
* @since 1.0
*/
@Override
- public void buildMimeMessage() throws EmailException
- {
- try
- {
+ public void buildMimeMessage() throws EmailException {
+ try {
build();
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
super.buildMimeMessage();
}
/**
- * @throws EmailException EmailException
+ * @throws EmailException EmailException
* @throws MessagingException MessagingException
*/
- private void build() throws MessagingException, EmailException
- {
+ private void build() throws MessagingException, EmailException {
final MimeMultipart rootContainer = this.getContainer();
MimeMultipart bodyEmbedsContainer = rootContainer;
MimeMultipart bodyContainer = rootContainer;
@@ -525,72 +430,57 @@ public class HtmlEmail extends MultiPartEmail
// determine how to form multiparts of email
- if (EmailUtils.isNotEmpty(this.html) && !this.inlineEmbeds.isEmpty())
- {
- //If HTML body and embeds are used, create a related container and add it to the root container
+ if (EmailUtils.isNotEmpty(this.html) && !this.inlineEmbeds.isEmpty()) {
+ // If HTML body and embeds are used, create a related container and add it to the root container
bodyEmbedsContainer = new MimeMultipart("related");
bodyContainer = bodyEmbedsContainer;
this.addPart(bodyEmbedsContainer, 0);
// If TEXT body was specified, create a alternative container and add it to the embeds container
- if (EmailUtils.isNotEmpty(this.text))
- {
+ if (EmailUtils.isNotEmpty(this.text)) {
bodyContainer = new MimeMultipart("alternative");
final BodyPart bodyPart = createBodyPart();
- try
- {
+ try {
bodyPart.setContent(bodyContainer);
bodyEmbedsContainer.addBodyPart(bodyPart, 0);
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
}
- }
- else if (EmailUtils.isNotEmpty(this.text) && EmailUtils.isNotEmpty(this.html))
- {
+ } else if (EmailUtils.isNotEmpty(this.text) && EmailUtils.isNotEmpty(this.html)) {
// EMAIL-142: if we have both an HTML and TEXT body, but no attachments or
- // inline images, the root container should have mimetype
- // "multipart/alternative".
+ // inline images, the root container should have mimetype
+ // "multipart/alternative".
// reference: http://tools.ietf.org/html/rfc2046#section-5.1.4
- if (!this.inlineEmbeds.isEmpty() || isBoolHasAttachments())
- {
+ if (!this.inlineEmbeds.isEmpty() || isBoolHasAttachments()) {
// If both HTML and TEXT bodies are provided, create an alternative
// container and add it to the root container
bodyContainer = new MimeMultipart("alternative");
this.addPart(bodyContainer, 0);
- }
- else
- {
+ } else {
// no attachments or embedded images present, change the mimetype
// of the root container (= body container)
rootContainer.setSubType("alternative");
}
}
- if (EmailUtils.isNotEmpty(this.html))
- {
+ if (EmailUtils.isNotEmpty(this.html)) {
msgHtml = new MimeBodyPart();
bodyContainer.addBodyPart(msgHtml, 0);
// EMAIL-104: call explicitly setText to use default mime charset
- // (property "mail.mime.charset") in case none has been set
+ // (property "mail.mime.charset") in case none has been set
msgHtml.setText(this.html, this.charset, EmailConstants.TEXT_SUBTYPE_HTML);
// EMAIL-147: work-around for buggy JavaMail implementations;
- // in case setText(...) does not set the correct content type,
- // use the setContent() method instead.
+ // in case setText(...) does not set the correct content type,
+ // use the setContent() method instead.
final String contentType = msgHtml.getContentType();
- if (contentType == null || !contentType.equals(EmailConstants.TEXT_HTML))
- {
+ if (contentType == null || !contentType.equals(EmailConstants.TEXT_HTML)) {
// apply default charset if one has been set
- if (EmailUtils.isNotEmpty(this.charset))
- {
+ if (EmailUtils.isNotEmpty(this.charset)) {
msgHtml.setContent(this.html, EmailConstants.TEXT_HTML + "; charset=" + this.charset);
- }
- else
- {
+ } else {
// unfortunately, MimeUtility.getDefaultMIMECharset() is package private
// and thus can not be used to set the default system charset in case
// no charset has been provided by the user
@@ -598,30 +488,27 @@ public class HtmlEmail extends MultiPartEmail
}
}
- for (final InlineImage image : this.inlineEmbeds.values())
- {
+ for (final InlineImage image : this.inlineEmbeds.values()) {
bodyEmbedsContainer.addBodyPart(image.getMbp());
}
}
- if (EmailUtils.isNotEmpty(this.text))
- {
+ if (EmailUtils.isNotEmpty(this.text)) {
msgText = new MimeBodyPart();
bodyContainer.addBodyPart(msgText, 0);
// EMAIL-104: call explicitly setText to use default mime charset
- // (property "mail.mime.charset") in case none has been set
+ // (property "mail.mime.charset") in case none has been set
msgText.setText(this.text, this.charset);
}
}
/**
- * Private bean class that encapsulates data about URL contents
- * that are embedded in the final email.
+ * Private bean class that encapsulates data about URL contents that are embedded in the final email.
+ *
* @since 1.1
*/
- private static final class InlineImage
- {
+ private static final class InlineImage {
/** content id. */
private final String cid;
/** {@code DataSource} for the content. */
@@ -630,15 +517,13 @@ public class HtmlEmail extends MultiPartEmail
private final MimeBodyPart mbp;
/**
- * Creates an InlineImage object to represent the
- * specified content ID and {@code MimeBodyPart}.
- * @param cid the generated content ID
+ * Creates an InlineImage object to represent the specified content ID and {@code MimeBodyPart}.
+ *
+ * @param cid the generated content ID
* @param dataSource the {@code DataSource} that represents the content
- * @param mbp the {@code MimeBodyPart} that contains the encoded
- * data
+ * @param mbp the {@code MimeBodyPart} that contains the encoded data
*/
- public InlineImage(final String cid, final DataSource dataSource, final MimeBodyPart mbp)
- {
+ public InlineImage(final String cid, final DataSource dataSource, final MimeBodyPart mbp) {
this.cid = cid;
this.dataSource = dataSource;
this.mbp = mbp;
@@ -646,30 +531,28 @@ public class HtmlEmail extends MultiPartEmail
/**
* Returns the unique content ID of this InlineImage.
+ *
* @return the unique content ID of this InlineImage
*/
- public String getCid()
- {
+ public String getCid() {
return cid;
}
/**
* Returns the {@code DataSource} that represents the encoded content.
+ *
* @return the {@code DataSource} representing the encoded content
*/
- public DataSource getDataSource()
- {
+ public DataSource getDataSource() {
return dataSource;
}
/**
- * Returns the {@code MimeBodyPart} that contains the
- * encoded InlineImage data.
- * @return the {@code MimeBodyPart} containing the encoded
- * InlineImage data
+ * Returns the {@code MimeBodyPart} that contains the encoded InlineImage data.
+ *
+ * @return the {@code MimeBodyPart} containing the encoded InlineImage data
*/
- public MimeBodyPart getMbp()
- {
+ public MimeBodyPart getMbp() {
return mbp;
}
@@ -677,17 +560,15 @@ public class HtmlEmail extends MultiPartEmail
// is stored as a entry in a Map.
/**
* {@inheritDoc}
+ *
* @return true if the other object is also an InlineImage with the same cid.
*/
@Override
- public boolean equals(final Object obj)
- {
- if (this == obj)
- {
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (!(obj instanceof InlineImage))
- {
+ if (!(obj instanceof InlineImage)) {
return false;
}
@@ -698,11 +579,11 @@ public class HtmlEmail extends MultiPartEmail
/**
* {@inheritDoc}
+ *
* @return the cid hashCode.
*/
@Override
- public int hashCode()
- {
+ public int hashCode() {
return cid.hashCode();
}
}
diff --git a/src/main/java/org/apache/commons/mail/ImageHtmlEmail.java b/src/main/java/org/apache/commons/mail/ImageHtmlEmail.java
index 3c455c8..37629c5 100644
--- a/src/main/java/org/apache/commons/mail/ImageHtmlEmail.java
+++ b/src/main/java/org/apache/commons/mail/ImageHtmlEmail.java
@@ -24,38 +24,31 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
- * <p>Small wrapper class on top of HtmlEmail which encapsulates the required logic
- * to retrieve images that are contained in "<img src=../>" elements in the HTML
- * code. This is done by replacing all img-src-elements with "cid:"-entries and
- * embedding images in the email.
+ * <p>
+ * Small wrapper class on top of HtmlEmail which encapsulates the required logic to retrieve images that are contained in "<img src=../>" elements in the
+ * HTML code. This is done by replacing all img-src-elements with "cid:"-entries and embedding images in the email.
* </p>
* <p>
- * For local files the class tries to either load them via an absolute path or -
- * if available - use a relative path starting from a base directory. For files
- * that are not found locally, the implementation tries to download
- * the element and link it in.
+ * For local files the class tries to either load them via an absolute path or - if available - use a relative path starting from a base directory. For files
+ * that are not found locally, the implementation tries to download the element and link it in.
* </p>
* <p>
- * The image loading is done by an instance of {@code DataSourceResolver}
- * which has to be provided by the caller.
+ * The image loading is done by an instance of {@code DataSourceResolver} which has to be provided by the caller.
* </p>
*
* @since 1.3
*/
-public class ImageHtmlEmail extends HtmlEmail
-{
+public class ImageHtmlEmail extends HtmlEmail {
// Regular Expression to find all <IMG SRC="..."> entries in an HTML
// document.It needs to cater for various things, like more whitespaces
// including newlines on any place, HTML is not case sensitive and there
// can be arbitrary text between "IMG" and "SRC" like IDs and other things.
/** Regexp for extracting {@code <img>} tags */
- public static final String REGEX_IMG_SRC =
- "(<[Ii][Mm][Gg]\\s*[^>]*?\\s+[Ss][Rr][Cc]\\s*=\\s*[\"'])([^\"']+?)([\"'])";
+ public static final String REGEX_IMG_SRC = "(<[Ii][Mm][Gg]\\s*[^>]*?\\s+[Ss][Rr][Cc]\\s*=\\s*[\"'])([^\"']+?)([\"'])";
/** regexp for extracting {@code <script>} tags */
- public static final String REGEX_SCRIPT_SRC =
- "(<[Ss][Cc][Rr][Ii][Pp][Tt]\\s*.*?\\s+[Ss][Rr][Cc]\\s*=\\s*[\"'])([^\"']+?)([\"'])";
+ public static final String REGEX_SCRIPT_SRC = "(<[Ss][Cc][Rr][Ii][Pp][Tt]\\s*.*?\\s+[Ss][Rr][Cc]\\s*=\\s*[\"'])([^\"']+?)([\"'])";
// this pattern looks for the HTML image tag which indicates embedded images,
// the grouping is necessary to allow to replace the element with the CID
@@ -74,8 +67,7 @@ public class ImageHtmlEmail extends HtmlEmail
*
* @return the resolver
*/
- public DataSourceResolver getDataSourceResolver()
- {
+ public DataSourceResolver getDataSourceResolver() {
return dataSourceResolver;
}
@@ -84,30 +76,25 @@ public class ImageHtmlEmail extends HtmlEmail
*
* @param dataSourceResolver the resolver
*/
- public void setDataSourceResolver(final DataSourceResolver dataSourceResolver)
- {
+ public void setDataSourceResolver(final DataSourceResolver dataSourceResolver) {
this.dataSourceResolver = dataSourceResolver;
}
- /**
- * Does the work of actually building the MimeMessage.
- *
- * @see org.apache.commons.mail.HtmlEmail#buildMimeMessage()
- * @throws EmailException building the MimeMessage failed
- */
+ /**
+ * Does the work of actually building the MimeMessage.
+ *
+ * @see org.apache.commons.mail.HtmlEmail#buildMimeMessage()
+ * @throws EmailException building the MimeMessage failed
+ */
@Override
- public void buildMimeMessage() throws EmailException
- {
- try
- {
+ public void buildMimeMessage() throws EmailException {
+ try {
// embed all the matching image and script resources within the email
String temp = replacePattern(super.html, IMG_PATTERN);
temp = replacePattern(temp, SCRIPT_PATTERN);
setHtmlMsg(temp);
super.buildMimeMessage();
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new EmailException("Building the MimeMessage failed", e);
}
}
@@ -116,14 +103,12 @@ public class ImageHtmlEmail extends HtmlEmail
* Replace the regexp matching resource locations with "cid:..." references.
*
* @param htmlMessage the HTML message to analyze
- * @param pattern the regular expression to find resources
+ * @param pattern the regular expression to find resources
* @return the HTML message containing "cid" references
* @throws EmailException creating the email failed
- * @throws IOException resolving the resources failed
+ * @throws IOException resolving the resources failed
*/
- private String replacePattern(final String htmlMessage, final Pattern pattern)
- throws EmailException, IOException
- {
+ private String replacePattern(final String htmlMessage, final Pattern pattern) throws EmailException, IOException {
DataSource dataSource;
final StringBuffer stringBuffer = new StringBuffer();
@@ -138,39 +123,31 @@ public class ImageHtmlEmail extends HtmlEmail
final Matcher matcher = pattern.matcher(htmlMessage);
// the matcher returns all instances one by one
- while (matcher.find())
- {
+ while (matcher.find()) {
// in the RegEx we have the <src> element as second "group"
final String resourceLocation = matcher.group(2);
// avoid loading the same data source more than once
- if (dataSourceCache.get(resourceLocation) == null)
- {
+ if (dataSourceCache.get(resourceLocation) == null) {
// in lenient mode we might get a 'null' data source if the resource was not found
dataSource = getDataSourceResolver().resolve(resourceLocation);
- if (dataSource != null)
- {
+ if (dataSource != null) {
dataSourceCache.put(resourceLocation, dataSource);
}
- }
- else
- {
+ } else {
dataSource = dataSourceCache.get(resourceLocation);
}
- if (dataSource != null)
- {
+ if (dataSource != null) {
String name = dataSource.getName();
- if (EmailUtils.isEmpty(name))
- {
+ if (EmailUtils.isEmpty(name)) {
name = resourceLocation;
}
String cid = cidCache.get(name);
- if (cid == null)
- {
+ if (cid == null) {
cid = embed(dataSource, name);
cidCache.put(name, cid);
}
@@ -178,8 +155,7 @@ public class ImageHtmlEmail extends HtmlEmail
// if we embedded something, then we need to replace the URL with
// the CID, otherwise the Matcher takes care of adding the
// non-replaced text afterwards, so no else is necessary here!
- matcher.appendReplacement(stringBuffer,
- Matcher.quoteReplacement(matcher.group(1) + "cid:" + cid + matcher.group(3)));
+ matcher.appendReplacement(stringBuffer, Matcher.quoteReplacement(matcher.group(1) + "cid:" + cid + matcher.group(3)));
}
}
diff --git a/src/main/java/org/apache/commons/mail/InputStreamDataSource.java b/src/main/java/org/apache/commons/mail/InputStreamDataSource.java
index 5bfc002..7a5fec9 100644
--- a/src/main/java/org/apache/commons/mail/InputStreamDataSource.java
+++ b/src/main/java/org/apache/commons/mail/InputStreamDataSource.java
@@ -28,6 +28,7 @@ import javax.activation.DataSource;
* <p>
* Copied from <a href="https://cxf.apache.org/">Apache CXF</a> and modified.
* </p>
+ *
* @since 1.6.0
*/
public final class InputStreamDataSource implements DataSource {
@@ -52,7 +53,7 @@ public final class InputStreamDataSource implements DataSource {
*
* @param inputStream An input stream.
* @param contentType A content type.
- * @param name A name.
+ * @param name A name.
*/
public InputStreamDataSource(final InputStream inputStream, final String contentType, final String name) {
this.inputStream = inputStream;
diff --git a/src/main/java/org/apache/commons/mail/MultiPartEmail.java b/src/main/java/org/apache/commons/mail/MultiPartEmail.java
index ae0dcc4..e39662b 100644
--- a/src/main/java/org/apache/commons/mail/MultiPartEmail.java
+++ b/src/main/java/org/apache/commons/mail/MultiPartEmail.java
@@ -36,17 +36,15 @@ import javax.mail.internet.MimeUtility;
/**
* A multipart email.
*
- * <p>This class is used to send multi-part internet email like
- * messages with attachments.
+ * <p>
+ * This class is used to send multi-part internet email like messages with attachments.
*
- * <p>To create a multi-part email, call the default constructor and
- * then you can call setMsg() to set the message and call the
- * different attach() methods.
+ * <p>
+ * To create a multi-part email, call the default constructor and then you can call setMsg() to set the message and call the different attach() methods.
*
* @since 1.0
*/
-public class MultiPartEmail extends Email
-{
+public class MultiPartEmail extends Email {
/** Body portion of the email. */
private MimeMultipart container;
@@ -68,8 +66,7 @@ public class MultiPartEmail extends Email
* @param aSubType MIME subtype of the email
* @since 1.0
*/
- public void setSubType(final String aSubType)
- {
+ public void setSubType(final String aSubType) {
this.subType = aSubType;
}
@@ -79,32 +76,25 @@ public class MultiPartEmail extends Email
* @return MIME subtype of the email
* @since 1.0
*/
- public String getSubType()
- {
+ public String getSubType() {
return subType;
}
/**
* Add a new part to the email.
*
- * @param partContent The content.
+ * @param partContent The content.
* @param partContentType The content type.
* @return An Email.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public Email addPart(final String partContent, final String partContentType)
- throws EmailException
- {
- final BodyPart bodyPart = createBodyPart();
- try
- {
+ public Email addPart(final String partContent, final String partContentType) throws EmailException {
+ final BodyPart bodyPart = createBodyPart();
+ try {
bodyPart.setContent(partContent, partContentType);
getContainer().addBodyPart(bodyPart);
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
@@ -116,18 +106,13 @@ public class MultiPartEmail extends Email
*
* @param multipart The MimeMultipart.
* @return An Email.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
- * @since 1.0
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
+ * @since 1.0
*/
- public Email addPart(final MimeMultipart multipart) throws EmailException
- {
- try
- {
+ public Email addPart(final MimeMultipart multipart) throws EmailException {
+ try {
return addPart(multipart, getContainer().getCount());
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
}
@@ -136,21 +121,17 @@ public class MultiPartEmail extends Email
* Add a new part to the email.
*
* @param multipart The part to add.
- * @param index The index to add at.
+ * @param index The index to add at.
* @return The email.
* @throws EmailException An error occurred while adding the part.
* @since 1.0
*/
- public Email addPart(final MimeMultipart multipart, final int index) throws EmailException
- {
+ public Email addPart(final MimeMultipart multipart, final int index) throws EmailException {
final BodyPart bodyPart = createBodyPart();
- try
- {
+ try {
bodyPart.setContent(multipart);
getContainer().addBodyPart(bodyPart, index);
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
@@ -159,12 +140,11 @@ public class MultiPartEmail extends Email
/**
* Initialize the multipart email.
+ *
* @since 1.0
*/
- protected void init()
- {
- if (initialized)
- {
+ protected void init() {
+ if (initialized) {
throw new IllegalStateException("Already initialized");
}
@@ -179,64 +159,48 @@ public class MultiPartEmail extends Email
*
* @param msg A String.
* @return An Email.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
@Override
- public Email setMsg(final String msg) throws EmailException
- {
+ public Email setMsg(final String msg) throws EmailException {
// throw exception on null message
- if (EmailUtils.isEmpty(msg))
- {
+ if (EmailUtils.isEmpty(msg)) {
throw new EmailException("Invalid message supplied");
}
- try
- {
+ try {
final BodyPart primary = getPrimaryBodyPart();
- if (primary instanceof MimePart && EmailUtils.isNotEmpty(charset))
- {
+ if (primary instanceof MimePart && EmailUtils.isNotEmpty(charset)) {
((MimePart) primary).setText(msg, charset);
- }
- else
- {
+ } else {
primary.setText(msg);
}
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
return this;
}
/**
- * Does the work of actually building the MimeMessage. Please note that
- * a user rarely calls this method directly and only if he/she is
- * interested in the sending the underlying MimeMessage without
- * commons-email.
+ * Does the work of actually building the MimeMessage. Please note that a user rarely calls this method directly and only if he/she is interested in the
+ * sending the underlying MimeMessage without commons-email.
*
* @throws EmailException if there was an error.
* @since 1.0
*/
@Override
- public void buildMimeMessage() throws EmailException
- {
- try
- {
- if (primaryBodyPart != null)
- {
+ public void buildMimeMessage() throws EmailException {
+ try {
+ if (primaryBodyPart != null) {
// before a multipart message can be sent, we must make sure that
- // the content for the main body part was actually set. If not,
+ // the content for the main body part was actually set. If not,
// an IOException will be thrown during super.send().
final BodyPart body = this.getPrimaryBodyPart();
- try
- {
+ try {
body.getContent();
- }
- catch (final IOException e) // NOPMD
+ } catch (final IOException e) // NOPMD
{
// do nothing here.
// content will be set to an empty string as a result.
@@ -245,15 +209,12 @@ public class MultiPartEmail extends Email
}
}
- if (subType != null)
- {
+ if (subType != null) {
getContainer().setSubType(subType);
}
super.buildMimeMessage();
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
throw new EmailException(me);
}
}
@@ -263,28 +224,21 @@ public class MultiPartEmail extends Email
*
* @param file A file attachment
* @return A MultiPartEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.3
*/
- public MultiPartEmail attach(final File file)
- throws EmailException
- {
+ public MultiPartEmail attach(final File file) throws EmailException {
final String fileName = file.getAbsolutePath();
- try
- {
- if (!file.exists())
- {
+ try {
+ if (!file.exists()) {
throw new IOException("\"" + fileName + "\" does not exist");
}
final FileDataSource fds = new FileDataSource(file);
return attach(fds, file.getName(), null, EmailAttachment.ATTACHMENT);
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new EmailException("Cannot attach file \"" + fileName + "\"", e);
}
}
@@ -294,139 +248,93 @@ public class MultiPartEmail extends Email
*
* @param attachment An EmailAttachment.
* @return A MultiPartEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public MultiPartEmail attach(final EmailAttachment attachment)
- throws EmailException
- {
+ public MultiPartEmail attach(final EmailAttachment attachment) throws EmailException {
MultiPartEmail result = null;
- if (attachment == null)
- {
+ if (attachment == null) {
throw new EmailException("Invalid attachment supplied");
}
final URL url = attachment.getURL();
- if (url == null)
- {
+ if (url == null) {
String fileName = null;
- try
- {
+ try {
fileName = attachment.getPath();
final File file = new File(fileName);
- if (!file.exists())
- {
+ if (!file.exists()) {
throw new IOException("\"" + fileName + "\" does not exist");
}
- result =
- attach(
- new FileDataSource(file),
- attachment.getName(),
- attachment.getDescription(),
- attachment.getDisposition());
- }
- catch (final IOException e)
- {
+ result = attach(new FileDataSource(file), attachment.getName(), attachment.getDescription(), attachment.getDisposition());
+ } catch (final IOException e) {
throw new EmailException("Cannot attach file \"" + fileName + "\"", e);
}
- }
- else
- {
- result =
- attach(
- url,
- attachment.getName(),
- attachment.getDescription(),
- attachment.getDisposition());
+ } else {
+ result = attach(url, attachment.getName(), attachment.getDescription(), attachment.getDisposition());
}
return result;
}
/**
- * Attach a file located by its URL. The disposition of the file
- * is set to mixed.
+ * Attach a file located by its URL. The disposition of the file is set to mixed.
*
- * @param url The URL of the file (may be any valid URL).
- * @param name The name field for the attachment.
+ * @param url The URL of the file (may be any valid URL).
+ * @param name The name field for the attachment.
* @param description A description for the attachment.
* @return A MultiPartEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public MultiPartEmail attach(final URL url, final String name, final String description)
- throws EmailException
- {
+ public MultiPartEmail attach(final URL url, final String name, final String description) throws EmailException {
return attach(url, name, description, EmailAttachment.ATTACHMENT);
}
/**
* Attach a file located by its URL.
*
- * @param url The URL of the file (may be any valid URL).
- * @param name The name field for the attachment.
+ * @param url The URL of the file (may be any valid URL).
+ * @param name The name field for the attachment.
* @param description A description for the attachment.
* @param disposition Either mixed or inline.
* @return A MultiPartEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public MultiPartEmail attach(
- final URL url,
- final String name,
- final String description,
- final String disposition)
- throws EmailException
- {
+ public MultiPartEmail attach(final URL url, final String name, final String description, final String disposition) throws EmailException {
// verify that the URL is valid
- try
- {
- url.openStream().close();
- }
- catch (final IOException e)
- {
- throw new EmailException("Invalid URL set:" + url, e);
- }
-
- return attach(new URLDataSource(url), name, description, disposition);
+ try {
+ url.openStream().close();
+ } catch (final IOException e) {
+ throw new EmailException("Invalid URL set:" + url, e);
+ }
+
+ return attach(new URLDataSource(url), name, description, disposition);
}
/**
* Attach a file specified as a DataSource interface.
*
- * @param ds A DataSource interface for the file.
- * @param name The name field for the attachment.
+ * @param ds A DataSource interface for the file.
+ * @param name The name field for the attachment.
* @param description A description for the attachment.
* @return A MultiPartEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public MultiPartEmail attach(
- final DataSource ds,
- final String name,
- final String description)
- throws EmailException
- {
- if (ds == null)
- {
+ public MultiPartEmail attach(final DataSource ds, final String name, final String description) throws EmailException {
+ if (ds == null) {
throw new EmailException("Invalid Datasource");
}
// verify that the DataSource is valid
- try (InputStream is = ds.getInputStream())
- {
- if (is == null)
- {
+ try (InputStream is = ds.getInputStream()) {
+ if (is == null) {
throw new EmailException("Invalid Datasource");
}
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new EmailException("Invalid Datasource", e);
}
return attach(ds, name, description, EmailAttachment.ATTACHMENT);
@@ -435,38 +343,27 @@ public class MultiPartEmail extends Email
/**
* Attach a file specified as a DataSource interface.
*
- * @param ds A DataSource interface for the file.
- * @param name The name field for the attachment.
+ * @param ds A DataSource interface for the file.
+ * @param name The name field for the attachment.
* @param description A description for the attachment.
* @param disposition Either mixed or inline.
* @return A MultiPartEmail.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
- public MultiPartEmail attach(
- final DataSource ds,
- String name,
- final String description,
- final String disposition)
- throws EmailException
- {
- if (EmailUtils.isEmpty(name))
- {
+ public MultiPartEmail attach(final DataSource ds, String name, final String description, final String disposition) throws EmailException {
+ if (EmailUtils.isEmpty(name)) {
name = ds.getName();
}
final BodyPart bodyPart = createBodyPart();
- try
- {
+ try {
bodyPart.setDisposition(disposition);
bodyPart.setFileName(MimeUtility.encodeText(name));
bodyPart.setDescription(description);
bodyPart.setDataHandler(new DataHandler(ds));
getContainer().addBodyPart(bodyPart);
- }
- catch (final UnsupportedEncodingException | MessagingException me)
- {
+ } catch (final UnsupportedEncodingException | MessagingException me) {
// in case the file name could not be encoded
throw new EmailException(me);
}
@@ -482,16 +379,13 @@ public class MultiPartEmail extends Email
* @throws MessagingException An error occurred while getting the primary body part.
* @since 1.0
*/
- protected BodyPart getPrimaryBodyPart() throws MessagingException
- {
- if (!initialized)
- {
+ protected BodyPart getPrimaryBodyPart() throws MessagingException {
+ if (!initialized) {
init();
}
- // Add the first body part to the message. The fist body part must be
- if (this.primaryBodyPart == null)
- {
+ // Add the first body part to the message. The fist body part must be
+ if (this.primaryBodyPart == null) {
primaryBodyPart = createBodyPart();
getContainer().addBodyPart(primaryBodyPart, 0);
}
@@ -505,23 +399,19 @@ public class MultiPartEmail extends Email
* @return The message container.
* @since 1.0
*/
- protected MimeMultipart getContainer()
- {
- if (!initialized)
- {
+ protected MimeMultipart getContainer() {
+ if (!initialized) {
init();
}
return container;
}
/**
- * Creates a body part object.
- * Can be overridden if you don't want to create a BodyPart.
+ * Creates a body part object. Can be overridden if you don't want to create a BodyPart.
*
* @return the created body part
*/
- protected BodyPart createBodyPart()
- {
+ protected BodyPart createBodyPart() {
return new MimeBodyPart();
}
@@ -530,8 +420,7 @@ public class MultiPartEmail extends Email
*
* @return the created mime part
*/
- protected MimeMultipart createMimeMultipart()
- {
+ protected MimeMultipart createMimeMultipart() {
return new MimeMultipart();
}
@@ -541,19 +430,17 @@ public class MultiPartEmail extends Email
* @return true if there are attachments
* @since 1.0
*/
- public boolean isBoolHasAttachments()
- {
+ public boolean isBoolHasAttachments() {
return boolHasAttachments;
}
/**
* Sets whether there are attachments.
*
- * @param b the attachments flag
+ * @param b the attachments flag
* @since 1.0
*/
- public void setBoolHasAttachments(final boolean b)
- {
+ public void setBoolHasAttachments(final boolean b) {
boolHasAttachments = b;
}
@@ -562,18 +449,16 @@ public class MultiPartEmail extends Email
*
* @return true if initialized
*/
- protected boolean isInitialized()
- {
+ protected boolean isInitialized() {
return initialized;
}
/**
* Sets the initialized status of this object.
*
- * @param b the initialized status flag
+ * @param b the initialized status flag
*/
- protected void setInitialized(final boolean b)
- {
+ protected void setInitialized(final boolean b) {
initialized = b;
}
diff --git a/src/main/java/org/apache/commons/mail/SimpleEmail.java b/src/main/java/org/apache/commons/mail/SimpleEmail.java
index a273920..f605191 100644
--- a/src/main/java/org/apache/commons/mail/SimpleEmail.java
+++ b/src/main/java/org/apache/commons/mail/SimpleEmail.java
@@ -17,27 +17,22 @@
package org.apache.commons.mail;
/**
- * This class is used to send simple internet email messages without
- * attachments.
+ * This class is used to send simple internet email messages without attachments.
*
* @since 1.0
-*/
-public class SimpleEmail extends Email
-{
+ */
+public class SimpleEmail extends Email {
/**
* Sets the content of the mail.
*
* @param msg A String.
* @return An Email.
- * @throws EmailException see javax.mail.internet.MimeBodyPart
- * for definitions
+ * @throws EmailException see javax.mail.internet.MimeBodyPart for definitions
* @since 1.0
*/
@Override
- public Email setMsg(final String msg) throws EmailException
- {
- if (EmailUtils.isEmpty(msg))
- {
+ public Email setMsg(final String msg) throws EmailException {
+ if (EmailUtils.isEmpty(msg)) {
throw new EmailException("Invalid message supplied");
}
diff --git a/src/main/java/org/apache/commons/mail/package-info.java b/src/main/java/org/apache/commons/mail/package-info.java
index dba8f40..8bac3d7 100644
--- a/src/main/java/org/apache/commons/mail/package-info.java
+++ b/src/main/java/org/apache/commons/mail/package-info.java
@@ -15,8 +15,6 @@
* limitations under the License.
*/
/**
- * Commons-Email aims to provide a API for sending email.
- * It is built on top of the Java Mail API, which it aims to simplify.
- * All help is gratefully received.
+ * Commons-Email aims to provide a API for sending email. It is built on top of the Java Mail API, which it aims to simplify. All help is gratefully received.
*/
package org.apache.commons.mail;
diff --git a/src/main/java/org/apache/commons/mail/resolver/DataSourceBaseResolver.java b/src/main/java/org/apache/commons/mail/resolver/DataSourceBaseResolver.java
index 7d8e2b1..2f156b3 100644
--- a/src/main/java/org/apache/commons/mail/resolver/DataSourceBaseResolver.java
+++ b/src/main/java/org/apache/commons/mail/resolver/DataSourceBaseResolver.java
@@ -23,16 +23,14 @@ import org.apache.commons.mail.DataSourceResolver;
*
* @since 1.3
*/
-public abstract class DataSourceBaseResolver implements DataSourceResolver
-{
+public abstract class DataSourceBaseResolver implements DataSourceResolver {
/** shall we ignore resources not found or complain with an exception */
private final boolean lenient;
/**
* Constructor.
*/
- public DataSourceBaseResolver()
- {
+ public DataSourceBaseResolver() {
this.lenient = false;
}
@@ -41,8 +39,7 @@ public abstract class DataSourceBaseResolver implements DataSourceResolver
*
* @param lenient shall we ignore resources not found or throw an exception?
*/
- public DataSourceBaseResolver(final boolean lenient)
- {
+ public DataSourceBaseResolver(final boolean lenient) {
this.lenient = lenient;
}
@@ -51,8 +48,7 @@ public abstract class DataSourceBaseResolver implements DataSourceResolver
*
* @return the lenient flag
*/
- public boolean isLenient()
- {
+ public boolean isLenient() {
return lenient;
}
@@ -62,8 +58,7 @@ public abstract class DataSourceBaseResolver implements DataSourceResolver
* @param resourceLocation the resource location
* @return true if it is a CID
*/
- protected boolean isCid(final String resourceLocation)
- {
+ protected boolean isCid(final String resourceLocation) {
return resourceLocation.startsWith("cid:");
}
@@ -73,8 +68,7 @@ public abstract class DataSourceBaseResolver implements DataSourceResolver
* @param urlString the URL string
* @return true if it is a file URL
*/
- protected boolean isFileUrl(final String urlString)
- {
+ protected boolean isFileUrl(final String urlString) {
return urlString.startsWith("file:/");
}
@@ -84,8 +78,7 @@ public abstract class DataSourceBaseResolver implements DataSourceResolver
* @param urlString the URL string
* @return true if it is a HTTP/HTTPS URL
*/
- protected boolean isHttpUrl(final String urlString)
- {
+ protected boolean isHttpUrl(final String urlString) {
return urlString.startsWith("http://") || urlString.startsWith("https://");
}
}
diff --git a/src/main/java/org/apache/commons/mail/resolver/DataSourceClassPathResolver.java b/src/main/java/org/apache/commons/mail/resolver/DataSourceClassPathResolver.java
index 7a302c2..3b25ccf 100644
--- a/src/main/java/org/apache/commons/mail/resolver/DataSourceClassPathResolver.java
+++ b/src/main/java/org/apache/commons/mail/resolver/DataSourceClassPathResolver.java
@@ -29,16 +29,14 @@ import java.net.URL;
*
* @since 1.3
*/
-public class DataSourceClassPathResolver extends DataSourceBaseResolver
-{
+public class DataSourceClassPathResolver extends DataSourceBaseResolver {
/** the base string of the resource relative to the classpath when resolving relative paths */
private final String classPathBase;
/**
* Constructs a new instance.
*/
- public DataSourceClassPathResolver()
- {
+ public DataSourceClassPathResolver() {
this.classPathBase = "/";
}
@@ -47,8 +45,7 @@ public class DataSourceClassPathResolver extends DataSourceBaseResolver
*
* @param classPathBase a base class path
*/
- public DataSourceClassPathResolver(final String classPathBase)
- {
+ public DataSourceClassPathResolver(final String classPathBase) {
this.classPathBase = classPathBase.endsWith("/") ? classPathBase : classPathBase + "/";
}
@@ -56,10 +53,9 @@ public class DataSourceClassPathResolver extends DataSourceBaseResolver
* Constructs a new instance.
*
* @param classPathBase a base class path
- * @param lenient shall we ignore resources not found or throw an exception?
+ * @param lenient shall we ignore resources not found or throw an exception?
*/
- public DataSourceClassPathResolver(final String classPathBase, final boolean lenient)
- {
+ public DataSourceClassPathResolver(final String classPathBase, final boolean lenient) {
super(lenient);
this.classPathBase = classPathBase.endsWith("/") ? classPathBase : classPathBase + "/";
}
@@ -69,15 +65,13 @@ public class DataSourceClassPathResolver extends DataSourceBaseResolver
*
* @return the classPathBase
*/
- public String getClassPathBase()
- {
+ public String getClassPathBase() {
return classPathBase;
}
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation) throws IOException
- {
+ public DataSource resolve(final String resourceLocation) throws IOException {
return resolve(resourceLocation, isLenient());
}
@@ -125,8 +119,7 @@ public class DataSourceClassPathResolver extends DataSourceBaseResolver
* @return {@link #getClassPathBase()} + {@code resourceLocation}
* @see #getClassPathBase()
*/
- private String getResourceName(final String resourceLocation)
- {
+ private String getResourceName(final String resourceLocation) {
return (getClassPathBase() + resourceLocation).replace("//", "/");
}
}
diff --git a/src/main/java/org/apache/commons/mail/resolver/DataSourceCompositeResolver.java b/src/main/java/org/apache/commons/mail/resolver/DataSourceCompositeResolver.java
index a056981..3dafb90 100644
--- a/src/main/java/org/apache/commons/mail/resolver/DataSourceCompositeResolver.java
+++ b/src/main/java/org/apache/commons/mail/resolver/DataSourceCompositeResolver.java
@@ -22,13 +22,11 @@ import javax.activation.DataSource;
import java.io.IOException;
/**
- * A composite data source resolver. It allows to resolve data sources coming from
- * multiple locations such as the classpath, the file system or an URL.
+ * A composite data source resolver. It allows to resolve data sources coming from multiple locations such as the classpath, the file system or an URL.
*
* @since 1.3
*/
-public class DataSourceCompositeResolver extends DataSourceBaseResolver
-{
+public class DataSourceCompositeResolver extends DataSourceBaseResolver {
/** the list of resolvers */
private final DataSourceResolver[] dataSourceResolvers;
@@ -37,8 +35,7 @@ public class DataSourceCompositeResolver extends DataSourceBaseResolver
*
* @param dataSourceResolvers a list of resolvers being used
*/
- public DataSourceCompositeResolver(final DataSourceResolver[] dataSourceResolvers)
- {
+ public DataSourceCompositeResolver(final DataSourceResolver[] dataSourceResolvers) {
this.dataSourceResolvers = dataSourceResolvers.clone();
}
@@ -46,10 +43,9 @@ public class DataSourceCompositeResolver extends DataSourceBaseResolver
* Constructor.
*
* @param dataSourceResolvers a list of resolvers being used
- * @param isLenient shall we ignore resources not found or throw an exception?
+ * @param isLenient shall we ignore resources not found or throw an exception?
*/
- public DataSourceCompositeResolver(final DataSourceResolver[] dataSourceResolvers, final boolean isLenient)
- {
+ public DataSourceCompositeResolver(final DataSourceResolver[] dataSourceResolvers, final boolean isLenient) {
super(isLenient);
this.dataSourceResolvers = dataSourceResolvers.clone();
}
@@ -59,20 +55,17 @@ public class DataSourceCompositeResolver extends DataSourceBaseResolver
*
* @return underlying data source resolvers
*/
- public DataSourceResolver[] getDataSourceResolvers()
- {
+ public DataSourceResolver[] getDataSourceResolvers() {
// clone the internal array to prevent external modification (see EMAIL-116)
return dataSourceResolvers.clone();
}
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation) throws IOException
- {
+ public DataSource resolve(final String resourceLocation) throws IOException {
final DataSource result = resolve(resourceLocation, true);
- if (isLenient() || result != null)
- {
+ if (isLenient() || result != null) {
return result;
}
throw new IOException("The following resource was not found : " + resourceLocation);
@@ -81,21 +74,17 @@ public class DataSourceCompositeResolver extends DataSourceBaseResolver
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException
- {
- for (int i = 0; i < getDataSourceResolvers().length; i++)
- {
+ public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException {
+ for (int i = 0; i < getDataSourceResolvers().length; i++) {
final DataSourceResolver dataSourceResolver = getDataSourceResolvers()[i];
final DataSource dataSource = dataSourceResolver.resolve(resourceLocation, isLenient);
- if (dataSource != null)
- {
+ if (dataSource != null) {
return dataSource;
}
}
- if (isLenient)
- {
+ if (isLenient) {
return null;
}
throw new IOException("The following resource was not found : " + resourceLocation);
diff --git a/src/main/java/org/apache/commons/mail/resolver/DataSourceFileResolver.java b/src/main/java/org/apache/commons/mail/resolver/DataSourceFileResolver.java
index 576966a..52bf338 100644
--- a/src/main/java/org/apache/commons/mail/resolver/DataSourceFileResolver.java
+++ b/src/main/java/org/apache/commons/mail/resolver/DataSourceFileResolver.java
@@ -22,21 +22,18 @@ import java.io.File;
import java.io.IOException;
/**
- * Creates a {@code DataSource} based on an URL. The implementation
- * also resolves file resources.
+ * Creates a {@code DataSource} based on an URL. The implementation also resolves file resources.
*
* @since 1.3
*/
-public class DataSourceFileResolver extends DataSourceBaseResolver
-{
+public class DataSourceFileResolver extends DataSourceBaseResolver {
/** the base directory of the resource when resolving relative paths */
private final File baseDir;
/**
* Constructor.
*/
- public DataSourceFileResolver()
- {
+ public DataSourceFileResolver() {
baseDir = new File(".");
}
@@ -45,8 +42,7 @@ public class DataSourceFileResolver extends DataSourceBaseResolver
*
* @param baseDir the base directory of the resource when resolving relative paths
*/
- public DataSourceFileResolver(final File baseDir)
- {
+ public DataSourceFileResolver(final File baseDir) {
this.baseDir = baseDir;
}
@@ -56,8 +52,7 @@ public class DataSourceFileResolver extends DataSourceBaseResolver
* @param baseDir the base directory of the resource when resolving relative paths
* @param lenient shall we ignore resources not found or complain with an exception
*/
- public DataSourceFileResolver(final File baseDir, final boolean lenient)
- {
+ public DataSourceFileResolver(final File baseDir, final boolean lenient) {
super(lenient);
this.baseDir = baseDir;
}
@@ -67,42 +62,33 @@ public class DataSourceFileResolver extends DataSourceBaseResolver
*
* @return the baseUrl
*/
- public File getBaseDir()
- {
+ public File getBaseDir() {
return baseDir;
}
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation) throws IOException
- {
+ public DataSource resolve(final String resourceLocation) throws IOException {
return resolve(resourceLocation, isLenient());
}
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException
- {
+ public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException {
File file;
DataSource result = null;
- if (!isCid(resourceLocation))
- {
+ if (!isCid(resourceLocation)) {
file = new File(resourceLocation);
- if (!file.isAbsolute())
- {
+ if (!file.isAbsolute()) {
file = getBaseDir() != null ? new File(getBaseDir(), resourceLocation) : new File(resourceLocation);
}
- if (file.exists())
- {
+ if (file.exists()) {
result = new FileDataSource(file);
- }
- else
- {
- if (!isLenient)
- {
+ } else {
+ if (!isLenient) {
throw new IOException("Cant resolve the following file resource :" + file.getAbsolutePath());
}
}
diff --git a/src/main/java/org/apache/commons/mail/resolver/DataSourceUrlResolver.java b/src/main/java/org/apache/commons/mail/resolver/DataSourceUrlResolver.java
index 3fd0ba7..a522b1b 100644
--- a/src/main/java/org/apache/commons/mail/resolver/DataSourceUrlResolver.java
+++ b/src/main/java/org/apache/commons/mail/resolver/DataSourceUrlResolver.java
@@ -27,8 +27,7 @@ import java.net.URL;
*
* @since 1.3
*/
-public class DataSourceUrlResolver extends DataSourceBaseResolver
-{
+public class DataSourceUrlResolver extends DataSourceBaseResolver {
/** the base url of the resource when resolving relative paths */
private final URL baseUrl;
@@ -37,8 +36,7 @@ public class DataSourceUrlResolver extends DataSourceBaseResolver
*
* @param baseUrl the base URL used for resolving relative resource locations
*/
- public DataSourceUrlResolver(final URL baseUrl)
- {
+ public DataSourceUrlResolver(final URL baseUrl) {
this.baseUrl = baseUrl;
}
@@ -48,8 +46,7 @@ public class DataSourceUrlResolver extends DataSourceBaseResolver
* @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 DataSourceUrlResolver(final URL baseUrl, final boolean lenient)
- {
+ public DataSourceUrlResolver(final URL baseUrl, final boolean lenient) {
super(lenient);
this.baseUrl = baseUrl;
}
@@ -59,39 +56,31 @@ public class DataSourceUrlResolver extends DataSourceBaseResolver
*
* @return the baseUrl
*/
- public URL getBaseUrl()
- {
+ public URL getBaseUrl() {
return baseUrl;
}
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation) throws IOException
- {
+ public DataSource resolve(final String resourceLocation) throws IOException {
return resolve(resourceLocation, isLenient());
}
/** {@inheritDoc} */
@Override
- public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException
- {
+ public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException {
DataSource result = null;
- try
- {
- if (!isCid(resourceLocation))
- {
+ try {
+ if (!isCid(resourceLocation)) {
final URL url = createUrl(resourceLocation);
result = new URLDataSource(url);
result.getInputStream();
}
return result;
- }
- catch (final IOException e)
- {
- if (isLenient)
- {
+ } catch (final IOException e) {
+ if (isLenient) {
return null;
}
throw e;
@@ -99,31 +88,26 @@ public class DataSourceUrlResolver extends DataSourceBaseResolver
}
/**
- * Create an URL based on a base URL and a resource location suitable for loading
- * the resource.
+ * Create an URL based on a base URL and a resource location suitable for loading the resource.
*
* @param resourceLocation a resource location
* @return the corresponding URL
* @throws java.net.MalformedURLException creating the URL failed
*/
- protected URL createUrl(final String resourceLocation) throws MalformedURLException
- {
+ protected URL createUrl(final String resourceLocation) throws MalformedURLException {
// if we get an non-existing base url than the resource can
// be directly used to create an URL
- if (baseUrl == null)
- {
+ if (baseUrl == null) {
return new URL(resourceLocation);
}
// if we get an non-existing location what we shall do?
- if (resourceLocation == null || resourceLocation.isEmpty())
- {
+ if (resourceLocation == null || resourceLocation.isEmpty()) {
throw new IllegalArgumentException("No resource defined");
}
// if we get a stand-alone resource than ignore the base url
- if (isFileUrl(resourceLocation) || isHttpUrl(resourceLocation))
- {
+ if (isFileUrl(resourceLocation) || isHttpUrl(resourceLocation)) {
return new URL(resourceLocation);
}
diff --git a/src/main/java/org/apache/commons/mail/resolver/package-info.java b/src/main/java/org/apache/commons/mail/resolver/package-info.java
index 683edc6..05b7fec 100644
--- a/src/main/java/org/apache/commons/mail/resolver/package-info.java
+++ b/src/main/java/org/apache/commons/mail/resolver/package-info.java
@@ -17,9 +17,9 @@
/**
* Contains implementation classes to resolve data sources from the following locations:
* <ul>
- * <li>class path</li>
- * <li>file system</li>
- * <li>URL</li>
+ * <li>class path</li>
+ * <li>file system</li>
+ * <li>URL</li>
* </ul>
*/
package org.apache.commons.mail.resolver;
diff --git a/src/main/java/org/apache/commons/mail/util/IDNEmailAddressConverter.java b/src/main/java/org/apache/commons/mail/util/IDNEmailAddressConverter.java
index 4078598..64c4543 100644
--- a/src/main/java/org/apache/commons/mail/util/IDNEmailAddressConverter.java
+++ b/src/main/java/org/apache/commons/mail/util/IDNEmailAddressConverter.java
@@ -20,8 +20,7 @@ import javax.mail.internet.InternetAddress;
import java.net.IDN;
/**
- * Converts email addresses containing International Domain Names into an ASCII
- * representation suitable for sending an email.
+ * Converts email addresses containing International Domain Names into an ASCII representation suitable for sending an email.
*
* @see <a href="https://docs.oracle.com/javase/tutorial/i18n/network/idn.html">https://docs.oracle.com/javase/tutorial/i18n/network/idn.html</a>
* @see <a href="https://en.wikipedia.org/wiki/Punycode">https://en.wikipedia.org/wiki/Punycode</a>
@@ -30,20 +29,17 @@ import java.net.IDN;
*
* @since 1.5
*/
-public class IDNEmailAddressConverter
-{
+public class IDNEmailAddressConverter {
/**
* Convert an email address to its ASCII representation using "Punycode".
*
* @param email email address.
* @return The ASCII representation
*/
- public String toASCII(final String email)
- {
+ public String toASCII(final String email) {
final int idx = findAtSymbolIndex(email);
- if (idx < 0)
- {
+ if (idx < 0) {
return email;
}
@@ -56,8 +52,7 @@ public class IDNEmailAddressConverter
* @param address email address.
* @return The Unicode representation
*/
- String toUnicode(final InternetAddress address)
- {
+ String toUnicode(final InternetAddress address) {
return address != null ? toUnicode(address.getAddress()) : null;
}
@@ -67,12 +62,10 @@ public class IDNEmailAddressConverter
* @param email email address.
* @return The Unicode representation
*/
- String toUnicode(final String email)
- {
+ String toUnicode(final String email) {
final int idx = findAtSymbolIndex(email);
- if (idx < 0)
- {
+ if (idx < 0) {
return email;
}
@@ -83,11 +76,10 @@ public class IDNEmailAddressConverter
* Extracts the local part of the email address.
*
* @param email email address.
- * @param idx index of '@' character.
+ * @param idx index of '@' character.
* @return local part of email
*/
- private String getLocalPart(final String email, final int idx)
- {
+ private String getLocalPart(final String email, final int idx) {
return email.substring(0, idx);
}
@@ -95,11 +87,10 @@ public class IDNEmailAddressConverter
* Extracts the domain part of the email address.
*
* @param email email address.
- * @param idx index of '@' character.
+ * @param idx index of '@' character.
* @return domain part of email
*/
- private String getDomainPart(final String email, final int idx)
- {
+ private String getDomainPart(final String email, final int idx) {
return email.substring(idx + 1);
}
@@ -109,10 +100,8 @@ public class IDNEmailAddressConverter
* @param value String value.
* @return index of first '@' character or {@code -1}
*/
- private int findAtSymbolIndex(final String value)
- {
- if (value == null)
- {
+ private int findAtSymbolIndex(final String value) {
+ if (value == null) {
return -1;
}
diff --git a/src/main/java/org/apache/commons/mail/util/MimeMessageParser.java b/src/main/java/org/apache/commons/mail/util/MimeMessageParser.java
index ebcceac..5f89412 100644
--- a/src/main/java/org/apache/commons/mail/util/MimeMessageParser.java
+++ b/src/main/java/org/apache/commons/mail/util/MimeMessageParser.java
@@ -43,13 +43,11 @@ import javax.mail.internet.ParseException;
import org.apache.commons.mail.InputStreamDataSource;
/**
- * Parses a MimeMessage and stores the individual parts such a plain text,
- * HTML text and attachments.
+ * Parses a MimeMessage and stores the individual parts such a plain text, HTML text and attachments.
*
* @since 1.3
*/
-public class MimeMessageParser
-{
+public class MimeMessageParser {
/** The MimeMessage to convert */
private final MimeMessage mimeMessage;
@@ -73,8 +71,7 @@ public class MimeMessageParser
*
* @param mimeMessage the message to parse
*/
- public MimeMessageParser(final MimeMessage mimeMessage)
- {
+ public MimeMessageParser(final MimeMessage mimeMessage) {
this.attachmentList = new ArrayList<>();
this.cidMap = new HashMap<>();
this.mimeMessage = mimeMessage;
@@ -86,10 +83,9 @@ public class MimeMessageParser
*
* @return this instance
* @throws MessagingException parsing the mime message failed
- * @throws IOException parsing the mime message failed
+ * @throws IOException parsing the mime message failed
*/
- public MimeMessageParser parse() throws MessagingException, IOException
- {
+ public MimeMessageParser parse() throws MessagingException, IOException {
this.parse(null, mimeMessage);
return this;
}
@@ -98,8 +94,7 @@ public class MimeMessageParser
* @return the 'to' recipients of the message
* @throws MessagingException determining the recipients failed
*/
- public List<Address> getTo() throws MessagingException
- {
+ public List<Address> getTo() throws MessagingException {
final Address[] recipients = this.mimeMessage.getRecipients(Message.RecipientType.TO);
return recipients != null ? Arrays.asList(recipients) : new ArrayList<>();
}
@@ -108,8 +103,7 @@ public class MimeMessageParser
* @return the 'cc' recipients of the message
* @throws MessagingException determining the recipients failed
*/
- public List<Address> getCc() throws MessagingException
- {
+ public List<Address> getCc() throws MessagingException {
final Address[] recipients = this.mimeMessage.getRecipients(Message.RecipientType.CC);
return recipients != null ? Arrays.asList(recipients) : new ArrayList<>();
}
@@ -118,8 +112,7 @@ public class MimeMessageParser
* @return the 'bcc' recipients of the message
* @throws MessagingException determining the recipients failed
*/
- public List<Address> getBcc() throws MessagingException
- {
+ public List<Address> getBcc() throws MessagingException {
final Address[] recipients = this.mimeMessage.getRecipients(Message.RecipientType.BCC);
return recipients != null ? Arrays.asList(recipients) : new ArrayList<>();
}
@@ -128,11 +121,9 @@ public class MimeMessageParser
* @return the 'from' field of the message
* @throws MessagingException parsing the mime message failed
*/
- public String getFrom() throws MessagingException
- {
+ public String getFrom() throws MessagingException {
final Address[] addresses = this.mimeMessage.getFrom();
- if (addresses == null || addresses.length == 0)
- {
+ if (addresses == null || addresses.length == 0) {
return null;
}
return ((InternetAddress) addresses[0]).getAddress();
@@ -142,11 +133,9 @@ public class MimeMessageParser
* @return the 'replyTo' address of the email
* @throws MessagingException parsing the mime message failed
*/
- public String getReplyTo() throws MessagingException
- {
+ public String getReplyTo() throws MessagingException {
final Address[] addresses = this.mimeMessage.getReplyTo();
- if (addresses == null || addresses.length == 0)
- {
+ if (addresses == null || addresses.length == 0) {
return null;
}
return ((InternetAddress) addresses[0]).getAddress();
@@ -156,8 +145,7 @@ public class MimeMessageParser
* @return the mail subject
* @throws MessagingException parsing the mime message failed
*/
- public String getSubject() throws MessagingException
- {
+ public String getSubject() throws MessagingException {
return this.mimeMessage.getSubject();
}
@@ -169,42 +157,27 @@ public class MimeMessageParser
* @throws MessagingException parsing the MimeMessage failed
* @throws IOException parsing the MimeMessage failed
*/
- protected void parse(final Multipart parent, final MimePart part)
- throws MessagingException, IOException
- {
- if (isMimeType(part, "text/plain") && plainContent == null
- && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
- {
+ protected void parse(final Multipart parent, final MimePart part) throws MessagingException, IOException {
+ if (isMimeType(part, "text/plain") && plainContent == null && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
plainContent = (String) part.getContent();
- }
- else
- {
- if (isMimeType(part, "text/html") && htmlContent == null
- && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
- {
+ } else {
+ if (isMimeType(part, "text/html") && htmlContent == null && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
htmlContent = (String) part.getContent();
- }
- else
- {
- if (isMimeType(part, "multipart/*"))
- {
+ } else {
+ if (isMimeType(part, "multipart/*")) {
this.isMultiPart = true;
final Multipart mp = (Multipart) part.getContent();
final int count = mp.getCount();
// iterate over all MimeBodyPart
- for (int i = 0; i < count; i++)
- {
+ for (int i = 0; i < count; i++) {
parse(mp, (MimeBodyPart) mp.getBodyPart(i));
}
- }
- else
- {
+ } else {
final String cid = stripContentId(part.getContentID());
final DataSource ds = createDataSource(parent, part);
- if (cid != null)
- {
+ if (cid != null) {
this.cidMap.put(cid, ds);
}
this.attachmentList.add(ds);
@@ -215,13 +188,12 @@ public class MimeMessageParser
/**
* Strips the content id of any whitespace and angle brackets.
+ *
* @param contentId the string to strip
* @return a stripped version of the content id
*/
- private String stripContentId(final String contentId)
- {
- if (contentId == null)
- {
+ private String stripContentId(final String contentId) {
+ if (contentId == null) {
return null;
}
return contentId.trim().replaceAll("[\\<\\>]", "");
@@ -235,18 +207,13 @@ public class MimeMessageParser
* @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise
* @throws MessagingException parsing the MimeMessage failed
*/
- private boolean isMimeType(final MimePart part, final String mimeType)
- throws MessagingException
- {
+ private boolean isMimeType(final MimePart part, final String mimeType) throws MessagingException {
// Do not use part.isMimeType(String) as it is broken for MimeBodyPart
// and does not really check the actual content type.
- try
- {
+ try {
return new ContentType(part.getDataHandler().getContentType()).match(mimeType);
- }
- catch (final ParseException ex)
- {
+ } catch (final ParseException ex) {
return part.getContentType().equalsIgnoreCase(mimeType);
}
}
@@ -261,9 +228,7 @@ public class MimeMessageParser
* @throws IOException error getting InputStream or unsupported encoding
*/
@SuppressWarnings("resource") // Caller closes InputStream
- protected DataSource createDataSource(final Multipart parent, final MimePart part)
- throws MessagingException, IOException
- {
+ protected DataSource createDataSource(final Multipart parent, final MimePart part) throws MessagingException, IOException {
final DataSource dataSource = part.getDataHandler().getDataSource();
final String contentType = getBaseMimeType(dataSource.getContentType());
final String dataSourceName = getDataSourceName(part, dataSource);
@@ -271,64 +236,54 @@ public class MimeMessageParser
}
/** @return Returns the mimeMessage. */
- public MimeMessage getMimeMessage()
- {
+ public MimeMessage getMimeMessage() {
return mimeMessage;
}
/** @return Returns the isMultiPart. */
- public boolean isMultipart()
- {
+ public boolean isMultipart() {
return isMultiPart;
}
/** @return Returns the plainContent if any */
- public String getPlainContent()
- {
+ public String getPlainContent() {
return plainContent;
}
/** @return Returns the attachmentList. */
- public List<DataSource> getAttachmentList()
- {
+ public List<DataSource> getAttachmentList() {
return attachmentList;
}
/**
* Returns a collection of all content-ids in the parsed message.
* <p>
- * The content-ids are stripped of any angle brackets, i.e. "part1" instead
- * of "<part1>".
+ * The content-ids are stripped of any angle brackets, i.e. "part1" instead of "<part1>".
*
* @return the collection of content ids.
* @since 1.3.4
*/
- public Collection<String> getContentIds()
- {
+ public Collection<String> getContentIds() {
return Collections.unmodifiableSet(cidMap.keySet());
}
/** @return Returns the htmlContent if any */
- public String getHtmlContent()
- {
+ public String getHtmlContent() {
return htmlContent;
}
/** @return true if a plain content is available */
- public boolean hasPlainContent()
- {
+ public boolean hasPlainContent() {
return this.plainContent != null;
}
/** @return true if HTML content is available */
- public boolean hasHtmlContent()
- {
+ public boolean hasHtmlContent() {
return this.htmlContent != null;
}
/** @return true if attachments are available */
- public boolean hasAttachments()
- {
+ public boolean hasAttachments() {
return !this.attachmentList.isEmpty();
}
@@ -338,14 +293,12 @@ public class MimeMessageParser
* @param name the name of the attachment
* @return the corresponding datasource or null if nothing was found
*/
- public DataSource findAttachmentByName(final String name)
- {
+ public DataSource findAttachmentByName(final String name) {
DataSource dataSource;
for (final DataSource element : getAttachmentList()) {
dataSource = element;
- if (name.equalsIgnoreCase(dataSource.getName()))
- {
+ if (name.equalsIgnoreCase(dataSource.getName())) {
return dataSource;
}
}
@@ -356,43 +309,35 @@ public class MimeMessageParser
/**
* Find an attachment using its content-id.
* <p>
- * The content-id must be stripped of any angle brackets,
- * i.e. "part1" instead of "<part1>".
+ * The content-id must be stripped of any angle brackets, i.e. "part1" instead of "<part1>".
*
* @param cid the content-id of the attachment
* @return the corresponding datasource or null if nothing was found
* @since 1.3.4
*/
- public DataSource findAttachmentByCid(final String cid)
- {
+ public DataSource findAttachmentByCid(final String cid) {
return cidMap.get(cid);
}
/**
* Determines the name of the data source if it is not already set.
*
- * @param part the mail part
+ * @param part the mail part
* @param dataSource the data source
* @return the name of the data source or {@code null} if no name can be determined
- * @throws MessagingException accessing the part failed
+ * @throws MessagingException accessing the part failed
* @throws UnsupportedEncodingException decoding the text failed
*/
- protected String getDataSourceName(final Part part, final DataSource dataSource)
- throws MessagingException, UnsupportedEncodingException
- {
+ protected String getDataSourceName(final Part part, final DataSource dataSource) throws MessagingException, UnsupportedEncodingException {
String result = dataSource.getName();
- if (result == null || result.isEmpty())
- {
+ if (result == null || result.isEmpty()) {
result = part.getFileName();
}
- if (result != null && !result.isEmpty())
- {
+ if (result != null && !result.isEmpty()) {
result = MimeUtility.decodeText(result);
- }
- else
- {
+ } else {
result = null;
}
@@ -405,11 +350,9 @@ public class MimeMessageParser
* @param fullMimeType the mime type from the mail api
* @return the real mime type
*/
- private String getBaseMimeType(final String fullMimeType)
- {
+ private String getBaseMimeType(final String fullMimeType) {
final int pos = fullMimeType.indexOf(';');
- if (pos >= 0)
- {
+ if (pos >= 0) {
return fullMimeType.substring(0, pos);
}
return fullMimeType;
diff --git a/src/main/java/org/apache/commons/mail/util/MimeMessageUtils.java b/src/main/java/org/apache/commons/mail/util/MimeMessageUtils.java
index 3b56b5d..6783247 100644
--- a/src/main/java/org/apache/commons/mail/util/MimeMessageUtils.java
+++ b/src/main/java/org/apache/commons/mail/util/MimeMessageUtils.java
@@ -33,29 +33,24 @@ import java.nio.charset.Charset;
*
* @since 1.3
*/
-public final class MimeMessageUtils
-{
+public final class MimeMessageUtils {
/**
* Instances should NOT be constructed in standard programming.
*/
- private MimeMessageUtils()
- {
+ private MimeMessageUtils() {
}
/**
* Creates a MimeMessage.
*
* @param session the mail session
- * @param source the input data
+ * @param source the input data
* @return the MimeMessage
* @throws MessagingException creating the MimeMessage failed
- * @throws IOException creating the MimeMessage failed
+ * @throws IOException creating the MimeMessage failed
*/
- public static MimeMessage createMimeMessage(final Session session, final byte[] source)
- throws MessagingException, IOException
- {
- try (ByteArrayInputStream is = new SharedByteArrayInputStream(source))
- {
+ public static MimeMessage createMimeMessage(final Session session, final byte[] source) throws MessagingException, IOException {
+ try (ByteArrayInputStream is = new ByteArrayInputStream(source)) {
return new MimeMessage(session, is);
}
}
@@ -64,16 +59,13 @@ public final class MimeMessageUtils
* Creates a MimeMessage.
*
* @param session the mail session
- * @param source the input data
+ * @param source the input data
* @return the MimeMessage
* @throws MessagingException creating the MimeMessage failed
- * @throws IOException creating the MimeMessage failed
+ * @throws IOException creating the MimeMessage failed
*/
- public static MimeMessage createMimeMessage(final Session session, final File source)
- throws MessagingException, IOException
- {
- try (FileInputStream is = new FileInputStream(source))
- {
+ public static MimeMessage createMimeMessage(final Session session, final File source) throws MessagingException, IOException {
+ try (FileInputStream is = new FileInputStream(source)) {
return createMimeMessage(session, is);
}
}
@@ -82,13 +74,11 @@ public final class MimeMessageUtils
* Creates a MimeMessage.
*
* @param session the mail session
- * @param source the input data
+ * @param source the input data
* @return the MimeMessage
* @throws MessagingException creating the MimeMessage failed
*/
- public static MimeMessage createMimeMessage(final Session session, final InputStream source)
- throws MessagingException
- {
+ public static MimeMessage createMimeMessage(final Session session, final InputStream source) throws MessagingException {
return new MimeMessage(session, source);
}
@@ -96,26 +86,20 @@ public final class MimeMessageUtils
* Creates a MimeMessage using the platform's default character encoding.
*
* @param session the mail session
- * @param source the input data
+ * @param source the input data
* @return the MimeMessage
* @throws MessagingException creating the MimeMessage failed
- * @throws IOException creating the MimeMessage failed
+ * @throws IOException creating the MimeMessage failed
*/
- public static MimeMessage createMimeMessage(final Session session, final String source)
- throws MessagingException, IOException
- {
+ public static MimeMessage createMimeMessage(final Session session, final String source) throws MessagingException, IOException {
ByteArrayInputStream is = null;
- try
- {
+ try {
final byte[] byteSource = source.getBytes(Charset.defaultCharset());
is = new SharedByteArrayInputStream(byteSource);
return createMimeMessage(session, is);
- }
- finally
- {
- if (is != null)
- {
+ } finally {
+ if (is != null) {
is.close();
}
}
@@ -129,14 +113,9 @@ public final class MimeMessageUtils
* @throws MessagingException accessing MimeMessage failed
* @throws IOException writing the MimeMessage failed
*/
- public static void writeMimeMessage(final MimeMessage mimeMessage, final File resultFile)
- throws MessagingException, IOException
- {
- if (!resultFile.getParentFile().exists() && !resultFile.getParentFile().mkdirs())
- {
- throw new IOException(
- "Failed to create the following parent directories: "
- + resultFile.getParentFile());
+ public static void writeMimeMessage(final MimeMessage mimeMessage, final File resultFile) throws MessagingException, IOException {
+ if (!resultFile.getParentFile().exists() && !resultFile.getParentFile().mkdirs()) {
+ throw new IOException("Failed to create the following parent directories: " + resultFile.getParentFile());
}
try (FileOutputStream fos = new FileOutputStream(resultFile)) {
mimeMessage.writeTo(fos);
diff --git a/src/test/java/org/apache/commons/mail/AbstractEmailTest.java b/src/test/java/org/apache/commons/mail/AbstractEmailTest.java
index 22e1894..f6d36ae 100644
--- a/src/test/java/org/apache/commons/mail/AbstractEmailTest.java
+++ b/src/test/java/org/apache/commons/mail/AbstractEmailTest.java
@@ -49,8 +49,7 @@ import org.subethamail.wiser.WiserMessage;
*
* @since 1.0
*/
-public abstract class AbstractEmailTest
-{
+public abstract class AbstractEmailTest {
/** Padding at end of body added by wiser/send */
public static final int BODY_END_PAD = 3;
@@ -85,27 +84,13 @@ public abstract class AbstractEmailTest
protected String strTestURL = EmailConfiguration.TEST_URL;
/** Test characters acceptable to email */
- protected String[] testCharsValid =
- {
- " ",
- "a",
- "A",
- "\uc5ec",
- "0123456789",
- "012345678901234567890"
- };
+ protected String[] testCharsValid = { " ", "a", "A", "\uc5ec", "0123456789", "012345678901234567890" };
/** Test characters not acceptable to email */
- protected String[] endOfLineCombinations =
- {
- "\n",
- "\r",
- "\r\n",
- "\n\r",
- };
+ protected String[] endOfLineCombinations = { "\n", "\r", "\r\n", "\n\r", };
/** Array of test strings */
- protected String[] testCharsNotValid = {"", null};
+ protected String[] testCharsNotValid = { "", null };
/** Where to save email output **/
private File emailOutputDir;
@@ -114,21 +99,17 @@ public abstract class AbstractEmailTest
private static int fileNameCounter;
@Before
- public void setUpAbstractEmailTest()
- {
+ public void setUpAbstractEmailTest() {
emailOutputDir = new File("target/test-emails");
- if (!emailOutputDir.exists())
- {
+ if (!emailOutputDir.exists()) {
emailOutputDir.mkdirs();
}
}
@After
- public void tearDownEmailTest()
- {
- //stop the fake email server (if started)
- if (this.fakeMailServer != null && !isMailServerStopped(fakeMailServer))
- {
+ public void tearDownEmailTest() {
+ // stop the fake email server (if started)
+ if (this.fakeMailServer != null && !isMailServerStopped(fakeMailServer)) {
this.fakeMailServer.stop();
assertTrue("Mail server didn't stop", isMailServerStopped(fakeMailServer));
}
@@ -138,10 +119,10 @@ public abstract class AbstractEmailTest
/**
* Gets the mail server port.
+ *
* @return the port the server is running on.
*/
- protected int getMailServerPort()
- {
+ protected int getMailServerPort() {
return mailServerPort;
}
@@ -149,36 +130,30 @@ public abstract class AbstractEmailTest
* Safe a mail to a file using a more or less unique file name.
*
* @param email email
- * @throws IOException writing the email failed
+ * @throws IOException writing the email failed
* @throws MessagingException writing the email failed
*/
- protected void saveEmailToFile(final WiserMessage email) throws IOException, MessagingException
- {
+ protected void saveEmailToFile(final WiserMessage email) throws IOException, MessagingException {
final int currCounter = fileNameCounter++ % 10;
final String emailFileName = "email" + new Date().getTime() + "-" + currCounter + ".eml";
final File emailFile = new File(emailOutputDir, emailFileName);
- EmailUtils.writeMimeMessage(emailFile, email.getMimeMessage() );
+ EmailUtils.writeMimeMessage(emailFile, email.getMimeMessage());
}
/**
* @param intMsgNo the message to retrieve
* @return message as string
*/
- public String getMessageAsString(final int intMsgNo)
- {
+ public String getMessageAsString(final int intMsgNo) {
final List<?> receivedMessages = fakeMailServer.getMessages();
assertTrue("mail server didn't get enough messages", receivedMessages.size() >= intMsgNo);
final WiserMessage emailMessage = (WiserMessage) receivedMessages.get(intMsgNo);
- if (emailMessage != null)
- {
- try
- {
+ if (emailMessage != null) {
+ try {
return serializeEmailMessage(emailMessage);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
// ignore, since the test will fail on an empty string return
}
}
@@ -187,14 +162,11 @@ public abstract class AbstractEmailTest
}
/**
- * Initializes the stub mail server. Fails if the server cannot be proven
- * to have started. If the server is already started, this method returns
- * without changing the state of the server.
+ * Initializes the stub mail server. Fails if the server cannot be proven to have started. If the server is already started, this method returns without
+ * changing the state of the server.
*/
- public void getMailServer()
- {
- if (this.fakeMailServer == null || isMailServerStopped(fakeMailServer))
- {
+ public void getMailServer() {
+ if (this.fakeMailServer == null || isMailServerStopped(fakeMailServer)) {
mailServerPort++;
this.fakeMailServer = new Wiser();
@@ -204,19 +176,14 @@ public abstract class AbstractEmailTest
assertFalse("fake mail server didn't start", isMailServerStopped(fakeMailServer));
final Date dtStartWait = new Date();
- while (isMailServerStopped(fakeMailServer))
- {
+ while (isMailServerStopped(fakeMailServer)) {
// test for connected
- if (this.fakeMailServer != null
- && !isMailServerStopped(fakeMailServer))
- {
+ if (this.fakeMailServer != null && !isMailServerStopped(fakeMailServer)) {
break;
}
// test for timeout
- if (dtStartWait.getTime() + EmailConfiguration.TIME_OUT
- <= new Date().getTime())
- {
+ if (dtStartWait.getTime() + EmailConfiguration.TIME_OUT <= new Date().getTime()) {
fail("Mail server failed to start");
}
}
@@ -225,80 +192,56 @@ public abstract class AbstractEmailTest
/**
* Validate the message was sent properly
- * @param mailServer reference to the fake mail server
- * @param strSubject expected subject
- * @param fromAdd expected from address
- * @param toAdd list of expected to addresses
- * @param ccAdd list of expected cc addresses
- * @param bccAdd list of expected bcc addresses
+ *
+ * @param mailServer reference to the fake mail server
+ * @param strSubject expected subject
+ * @param fromAdd expected from address
+ * @param toAdd list of expected to addresses
+ * @param ccAdd list of expected cc addresses
+ * @param bccAdd list of expected bcc addresses
* @param boolSaveToFile true will output to file, false doesn't
* @return WiserMessage email to check
* @throws IOException Exception
*/
- protected WiserMessage validateSend(
- final Wiser mailServer,
- final String strSubject,
- final InternetAddress fromAdd,
- final List<InternetAddress> toAdd,
- final List<InternetAddress> ccAdd,
- final List<InternetAddress> bccAdd,
- final boolean boolSaveToFile)
- throws IOException
- {
- assertTrue("mail server doesn't contain expected message",
- mailServer.getMessages().size() == 1);
+ protected WiserMessage validateSend(final Wiser mailServer, final String strSubject, final InternetAddress fromAdd, final List<InternetAddress> toAdd,
+ final List<InternetAddress> ccAdd, final List<InternetAddress> bccAdd, final boolean boolSaveToFile) throws IOException {
+ assertTrue("mail server doesn't contain expected message", mailServer.getMessages().size() == 1);
final WiserMessage emailMessage = mailServer.getMessages().get(0);
- if (boolSaveToFile)
- {
- try
- {
+ if (boolSaveToFile) {
+ try {
this.saveEmailToFile(emailMessage);
- }
- catch (final MessagingException me)
- {
- final IllegalStateException ise =
- new IllegalStateException("caught MessagingException during saving the email");
+ } catch (final MessagingException me) {
+ final IllegalStateException ise = new IllegalStateException("caught MessagingException during saving the email");
ise.initCause(me);
throw ise;
}
}
- try
- {
+ try {
// get the MimeMessage
final MimeMessage mimeMessage = emailMessage.getMimeMessage();
// test subject
- assertEquals("got wrong subject from mail",
- strSubject, mimeMessage.getHeader("Subject", null));
-
- //test from address
- assertEquals("got wrong From: address from mail",
- fromAdd.toString(), mimeMessage.getHeader("From", null));
-
- //test to address
- assertTrue("got wrong To: address from mail",
- toAdd.toString().contains(mimeMessage.getHeader("To", null)));
-
- //test cc address
- if (!ccAdd.isEmpty())
- {
- assertTrue("got wrong Cc: address from mail",
- ccAdd.toString().contains(mimeMessage.getHeader("Cc", null)));
+ assertEquals("got wrong subject from mail", strSubject, mimeMessage.getHeader("Subject", null));
+
+ // test from address
+ assertEquals("got wrong From: address from mail", fromAdd.toString(), mimeMessage.getHeader("From", null));
+
+ // test to address
+ assertTrue("got wrong To: address from mail", toAdd.toString().contains(mimeMessage.getHeader("To", null)));
+
+ // test cc address
+ if (!ccAdd.isEmpty()) {
+ assertTrue("got wrong Cc: address from mail", ccAdd.toString().contains(mimeMessage.getHeader("Cc", null)));
}
- //test bcc address
- if (!bccAdd.isEmpty())
- {
- assertTrue("got wrong Bcc: address from mail",
- bccAdd.toString().contains(mimeMessage.getHeader("Bcc", null)));
+ // test bcc address
+ if (!bccAdd.isEmpty()) {
+ assertTrue("got wrong Bcc: address from mail", bccAdd.toString().contains(mimeMessage.getHeader("Bcc", null)));
}
- }
- catch (final MessagingException me)
- {
- final IllegalStateException ise =
- new IllegalStateException("caught MessagingException in validateSend()");
+ } catch (final MessagingException me) {
+ final IllegalStateException ise = new IllegalStateException("caught MessagingException in validateSend()");
ise.initCause(me);
throw ise;
}
@@ -308,112 +251,69 @@ public abstract class AbstractEmailTest
/**
* Validate the message was sent properly
- * @param mailServer reference to the fake mail server
- * @param strSubject expected subject
- * @param content the expected message content
- * @param fromAdd expected from address
- * @param toAdd list of expected to addresses
- * @param ccAdd list of expected cc addresses
- * @param bccAdd list of expected bcc addresses
+ *
+ * @param mailServer reference to the fake mail server
+ * @param strSubject expected subject
+ * @param content the expected message content
+ * @param fromAdd expected from address
+ * @param toAdd list of expected to addresses
+ * @param ccAdd list of expected cc addresses
+ * @param bccAdd list of expected bcc addresses
* @param boolSaveToFile true will output to file, false doesn't
* @throws IOException Exception
*/
- protected void validateSend(
- final Wiser mailServer,
- final String strSubject,
- final Multipart content,
- final InternetAddress fromAdd,
- final List<InternetAddress> toAdd,
- final List<InternetAddress> ccAdd,
- final List<InternetAddress> bccAdd,
- final boolean boolSaveToFile)
- throws IOException
- {
+ protected void validateSend(final Wiser mailServer, final String strSubject, final Multipart content, final InternetAddress fromAdd,
+ final List<InternetAddress> toAdd, final List<InternetAddress> ccAdd, final List<InternetAddress> bccAdd, final boolean boolSaveToFile)
+ throws IOException {
// test other properties
- final WiserMessage emailMessage = this.validateSend(
- mailServer,
- strSubject,
- fromAdd,
- toAdd,
- ccAdd,
- bccAdd,
- boolSaveToFile);
+ final WiserMessage emailMessage = this.validateSend(mailServer, strSubject, fromAdd, toAdd, ccAdd, bccAdd, boolSaveToFile);
// test message content
// get sent email content
- final String strSentContent =
- content.getContentType();
+ final String strSentContent = content.getContentType();
// get received email content (chop off the auto-added \n
// and -- (front and end)
final String emailMessageBody = getMessageBody(emailMessage);
- final String strMessageBody =
- emailMessageBody.substring(AbstractEmailTest.BODY_START_PAD,
- emailMessageBody.length()
- - AbstractEmailTest.BODY_END_PAD);
- assertTrue("didn't find expected content type in message body",
- strMessageBody.contains(strSentContent));
+ final String strMessageBody = emailMessageBody.substring(AbstractEmailTest.BODY_START_PAD, emailMessageBody.length() - AbstractEmailTest.BODY_END_PAD);
+ assertTrue("didn't find expected content type in message body", strMessageBody.contains(strSentContent));
}
/**
* Validate the message was sent properly
- * @param mailServer reference to the fake mail server
- * @param strSubject expected subject
- * @param strMessage the expected message as a string
- * @param fromAdd expected from address
- * @param toAdd list of expected to addresses
- * @param ccAdd list of expected cc addresses
- * @param bccAdd list of expected bcc addresses
+ *
+ * @param mailServer reference to the fake mail server
+ * @param strSubject expected subject
+ * @param strMessage the expected message as a string
+ * @param fromAdd expected from address
+ * @param toAdd list of expected to addresses
+ * @param ccAdd list of expected cc addresses
+ * @param bccAdd list of expected bcc addresses
* @param boolSaveToFile true will output to file, false doesn't
* @throws IOException Exception
*/
- protected void validateSend(
- final Wiser mailServer,
- final String strSubject,
- final String strMessage,
- final InternetAddress fromAdd,
- final List<InternetAddress> toAdd,
- final List<InternetAddress> ccAdd,
- final List<InternetAddress> bccAdd,
- final boolean boolSaveToFile)
- throws IOException
- {
+ protected void validateSend(final Wiser mailServer, final String strSubject, final String strMessage, final InternetAddress fromAdd,
+ final List<InternetAddress> toAdd, final List<InternetAddress> ccAdd, final List<InternetAddress> bccAdd, final boolean boolSaveToFile)
+ throws IOException {
// test other properties
- final WiserMessage emailMessage = this.validateSend(
- mailServer,
- strSubject,
- fromAdd,
- toAdd,
- ccAdd,
- bccAdd,
- true);
+ final WiserMessage emailMessage = this.validateSend(mailServer, strSubject, fromAdd, toAdd, ccAdd, bccAdd, true);
// test message content
- assertThat("didn't find expected message content in message body",
- getMessageBody(emailMessage), containsString(strMessage));
+ assertThat("didn't find expected message content in message body", getMessageBody(emailMessage), containsString(strMessage));
}
/**
- * Serializes the {@link MimeMessage} from the {@code WiserMessage}
- * passed in. The headers are serialized first followed by the message
- * body.
+ * Serializes the {@link MimeMessage} from the {@code WiserMessage} passed in. The headers are serialized first followed by the message body.
*
* @param wiserMessage The {@code WiserMessage} to serialize.
* @return The string format of the message.
* @throws MessagingException
- * @throws IOException
- * Thrown while serializing the body from
- * {@link DataHandler#writeTo(java.io.OutputStream)}.
- * @throws MessagingException
- * Thrown while getting the body content from
- * {@link MimeMessage#getDataHandler()}
+ * @throws IOException Thrown while serializing the body from {@link DataHandler#writeTo(java.io.OutputStream)}.
+ * @throws MessagingException Thrown while getting the body content from {@link MimeMessage#getDataHandler()}
* @since 1.1
*/
- private String serializeEmailMessage(final WiserMessage wiserMessage)
- throws MessagingException, IOException
- {
- if (wiserMessage == null)
- {
+ private String serializeEmailMessage(final WiserMessage wiserMessage) throws MessagingException, IOException {
+ if (wiserMessage == null) {
return "";
}
@@ -421,9 +321,7 @@ public abstract class AbstractEmailTest
final MimeMessage message = wiserMessage.getMimeMessage();
// Serialize the headers
- for (final Enumeration<?> headers = message.getAllHeaders(); headers
- .hasMoreElements();)
- {
+ for (final Enumeration<?> headers = message.getAllHeaders(); headers.hasMoreElements();) {
final Header header = (Header) headers.nextElement();
serializedEmail.append(header.getName());
serializedEmail.append(": ");
@@ -442,37 +340,27 @@ public abstract class AbstractEmailTest
}
/**
- * Returns a string representation of the message body. If the message body
- * cannot be read, an empty string is returned.
+ * Returns a string representation of the message body. If the message body cannot be read, an empty string is returned.
*
* @param wiserMessage The wiser message from which to extract the message body
* @return The string representation of the message body
- * @throws IOException
- * Thrown while serializing the body from
- * {@link DataHandler#writeTo(java.io.OutputStream)}.
+ * @throws IOException Thrown while serializing the body from {@link DataHandler#writeTo(java.io.OutputStream)}.
* @since 1.1
*/
- private String getMessageBody(final WiserMessage wiserMessage)
- throws IOException
- {
- if (wiserMessage == null)
- {
+ private String getMessageBody(final WiserMessage wiserMessage) throws IOException {
+ if (wiserMessage == null) {
return "";
}
byte[] messageBody = null;
- try
- {
+ try {
final MimeMessage message = wiserMessage.getMimeMessage();
messageBody = getMessageBodyBytes(message);
- }
- catch (final MessagingException me)
- {
+ } catch (final MessagingException me) {
// Thrown while getting the body content from
// {@link MimeMessage#getDataHandler()}
- final IllegalStateException ise =
- new IllegalStateException("couldn't process MimeMessage from WiserMessage in getMessageBody()");
+ final IllegalStateException ise = new IllegalStateException("couldn't process MimeMessage from WiserMessage in getMessageBody()");
ise.initCause(me);
throw ise;
}
@@ -483,24 +371,16 @@ public abstract class AbstractEmailTest
/**
* Gets the byte making up the body of the message.
*
- * @param mimeMessage
- * The mime message from which to extract the body.
+ * @param mimeMessage The mime message from which to extract the body.
* @return A byte array representing the message body
- * @throws IOException
- * Thrown while serializing the body from
- * {@link DataHandler#writeTo(java.io.OutputStream)}.
- * @throws MessagingException
- * Thrown while getting the body content from
- * {@link MimeMessage#getDataHandler()}
+ * @throws IOException Thrown while serializing the body from {@link DataHandler#writeTo(java.io.OutputStream)}.
+ * @throws MessagingException Thrown while getting the body content from {@link MimeMessage#getDataHandler()}
* @since 1.1
*/
- private byte[] getMessageBodyBytes(final MimeMessage mimeMessage)
- throws IOException, MessagingException
- {
+ private byte[] getMessageBodyBytes(final MimeMessage mimeMessage) throws IOException, MessagingException {
final DataHandler dataHandler = mimeMessage.getDataHandler();
final ByteArrayOutputStream byteArrayOutStream = new ByteArrayOutputStream();
- final BufferedOutputStream buffOs = new BufferedOutputStream(
- byteArrayOutStream);
+ final BufferedOutputStream buffOs = new BufferedOutputStream(byteArrayOutStream);
dataHandler.writeTo(buffOs);
buffOs.flush();
@@ -508,11 +388,9 @@ public abstract class AbstractEmailTest
}
/**
- * Checks if an email server is running at the address stored in the
- * {@code fakeMailServer}.
+ * Checks if an email server is running at the address stored in the {@code fakeMailServer}.
*
- * @param fakeMailServer
- * The server from which the address is picked up.
+ * @param fakeMailServer The server from which the address is picked up.
* @return {@code true} if the server claims to be running
* @since 1.1
*/
@@ -521,11 +399,9 @@ public abstract class AbstractEmailTest
}
/**
- * Create a mocked URL object which always throws an IOException
- * when the openStream() method is called.
+ * Create a mocked URL object which always throws an IOException when the openStream() method is called.
* <p>
- * Several ISPs do resolve invalid URLs like {@code http://example.invalid}
- * to some error page causing tests to fail otherwise.
+ * Several ISPs do resolve invalid URLs like {@code http://example.invalid} to some error page causing tests to fail otherwise.
*
* @return an invalid URL
*/
diff --git a/src/test/java/org/apache/commons/mail/DefaultAuthenticatorTest.java b/src/test/java/org/apache/commons/mail/DefaultAuthenticatorTest.java
index a03cd97..a8c66e3 100644
--- a/src/test/java/org/apache/commons/mail/DefaultAuthenticatorTest.java
+++ b/src/test/java/org/apache/commons/mail/DefaultAuthenticatorTest.java
@@ -27,25 +27,17 @@ import org.junit.Test;
*
* @since 1.0
*/
-public class DefaultAuthenticatorTest
-{
+public class DefaultAuthenticatorTest {
@Test
- public void testDefaultAuthenticatorConstructor()
- {
- //insert code testing basic functionality
+ public void testDefaultAuthenticatorConstructor() {
+ // insert code testing basic functionality
final String strUsername = "user.name";
final String strPassword = "user.pwd";
final DefaultAuthenticator authenticator = new DefaultAuthenticator(strUsername, strPassword);
- assertTrue(
- PasswordAuthentication.class.isInstance(
- authenticator.getPasswordAuthentication()));
- assertEquals(
- strUsername,
- authenticator.getPasswordAuthentication().getUserName());
- assertEquals(
- strPassword,
- authenticator.getPasswordAuthentication().getPassword());
+ assertTrue(PasswordAuthentication.class.isInstance(authenticator.getPasswordAuthentication()));
+ assertEquals(strUsername, authenticator.getPasswordAuthentication().getUserName());
+ assertEquals(strPassword, authenticator.getPasswordAuthentication().getPassword());
}
}
diff --git a/src/test/java/org/apache/commons/mail/EmailAttachmentTest.java b/src/test/java/org/apache/commons/mail/EmailAttachmentTest.java
index b7a36d4..46b85f0 100644
--- a/src/test/java/org/apache/commons/mail/EmailAttachmentTest.java
+++ b/src/test/java/org/apache/commons/mail/EmailAttachmentTest.java
@@ -28,57 +28,43 @@ import org.junit.Test;
*
* @since 1.0
*/
-public class EmailAttachmentTest extends AbstractEmailTest
-{
+public class EmailAttachmentTest extends AbstractEmailTest {
private EmailAttachment attachment;
@Before
- public void setUpAttachmentTest()
- {
+ public void setUpAttachmentTest() {
attachment = new EmailAttachment();
}
@Test
- public void testGetSetDescription()
- {
- for (final String validChar : testCharsValid)
- {
+ public void testGetSetDescription() {
+ for (final String validChar : testCharsValid) {
attachment.setDescription(validChar);
assertEquals(validChar, attachment.getDescription());
}
}
@Test
- public void testGetSetName()
- {
- for (final String validChar : testCharsValid)
- {
+ public void testGetSetName() {
+ for (final String validChar : testCharsValid) {
attachment.setName(validChar);
assertEquals(validChar, attachment.getName());
}
}
@Test
- public void testGetSetPath()
- {
- for (final String validChar : testCharsValid)
- {
+ public void testGetSetPath() {
+ for (final String validChar : testCharsValid) {
attachment.setPath(validChar);
assertEquals(validChar, attachment.getPath());
}
}
@Test
- public void testGetSetURL() throws Exception
- {
- final String[] tests =
- {
- "http://localhost/",
- "http://www.apache.org/",
- "http://foo.notexisting.org" };
+ public void testGetSetURL() throws Exception {
+ final String[] tests = { "http://localhost/", "http://www.apache.org/", "http://foo.notexisting.org" };
- for (final String urlString : tests)
- {
+ for (final String urlString : tests) {
final URL testURL = new URL(urlString);
attachment.setURL(testURL);
assertEquals(testURL, attachment.getURL());
@@ -86,10 +72,8 @@ public class EmailAttachmentTest extends AbstractEmailTest
}
@Test
- public void testGetSetDisposition()
- {
- for (final String validChar : testCharsValid)
- {
+ public void testGetSetDisposition() {
+ for (final String validChar : testCharsValid) {
attachment.setDisposition(validChar);
assertEquals(validChar, attachment.getDisposition());
}
diff --git a/src/test/java/org/apache/commons/mail/EmailLiveTest.java b/src/test/java/org/apache/commons/mail/EmailLiveTest.java
index f80c8ad..18220dd 100644
--- a/src/test/java/org/apache/commons/mail/EmailLiveTest.java
+++ b/src/test/java/org/apache/commons/mail/EmailLiveTest.java
@@ -37,18 +37,14 @@ import org.junit.Before;
import org.junit.Test;
/**
- * This are regression test sending REAL email to REAL mail
- * servers using REAL recipients.
+ * This are regression test sending REAL email to REAL mail servers using REAL recipients.
*
- * The intention is to field-test certain aspects
- * of email using a variety of mail clients since I'm not a mockist
- * (see http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting).
+ * The intention is to field-test certain aspects of email using a variety of mail clients since I'm not a mockist (see
+ * http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting).
*/
-public class EmailLiveTest extends AbstractEmailTest
-{
+public class EmailLiveTest extends AbstractEmailTest {
@Before
- public void setUpLiveTest()
- {
+ public void setUpLiveTest() {
// enforce a default charset UTF-8 otherwise non-ASCII attachment names will not work
System.setProperty("mail.mime.charset", "utf-8");
@@ -59,10 +55,9 @@ public class EmailLiveTest extends AbstractEmailTest
protected Email send(final Email email) throws EmailException {
- if ( EmailConfiguration.MAIL_FORCE_SEND ) {
+ if (EmailConfiguration.MAIL_FORCE_SEND) {
email.send();
- }
- else {
+ } else {
email.buildMimeMessage();
}
@@ -117,13 +112,12 @@ public class EmailLiveTest extends AbstractEmailTest
* @throws Exception the test failed
*/
@Test
- public void testSimpleEmail() throws Exception
- {
+ public void testSimpleEmail() throws Exception {
final SimpleEmail email = (SimpleEmail) create(SimpleEmail.class);
email.setSubject("TestSimpleMail");
email.setMsg("This is a test mail ... :-)");
- EmailUtils.writeMimeMessage( new File("./target/test-emails/simplemail.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/simplemail.eml"), send(email).getMimeMessage());
}
/**
@@ -132,14 +126,13 @@ public class EmailLiveTest extends AbstractEmailTest
* @throws Exception the test failed
*/
@Test
- public void testFoldedHeaderValue() throws Exception
- {
+ public void testFoldedHeaderValue() throws Exception {
final SimpleEmail email = (SimpleEmail) create(SimpleEmail.class);
email.setSubject("TestFoldedHeaderMail");
email.setMsg("This is a test mail with a folded header value... :-)");
email.addHeader("X-TestHeader", "This is a very long header value which should be folded into two lines, hopefully");
- EmailUtils.writeMimeMessage( new File("./target/test-emails/foldedheader.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/foldedheader.eml"), send(email).getMimeMessage());
}
/**
@@ -148,14 +141,13 @@ public class EmailLiveTest extends AbstractEmailTest
* @throws Exception the test failed
*/
@Test
- public void testMultiPartEmail() throws Exception
- {
+ public void testMultiPartEmail() throws Exception {
final MultiPartEmail email = (MultiPartEmail) create(MultiPartEmail.class);
email.setSubject("TestMultiPartMail");
email.setMsg("This is a test mail ... :-)");
email.attach(new File("./src/test/resources/attachments/logo.pdf"));
- EmailUtils.writeMimeMessage( new File("./target/test-emails/multipart.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/multipart.eml"), send(email).getMimeMessage());
}
/**
@@ -166,8 +158,7 @@ public class EmailLiveTest extends AbstractEmailTest
* @throws Exception the test failed
*/
@Test
- public void testHtmlMailMimeLayout() throws Exception
- {
+ public void testHtmlMailMimeLayout() throws Exception {
String textMsg;
String htmlMsg;
@@ -190,11 +181,11 @@ public class EmailLiveTest extends AbstractEmailTest
textMsg = "Your email client does not support HTML messages";
htmlMsg = "<html><b>This is a HTML message without any image</b><html>";
- htmlEmail1.setSubject( "[email] 1.Test: text + html content");
+ htmlEmail1.setSubject("[email] 1.Test: text + html content");
htmlEmail1.setTextMsg(textMsg);
htmlEmail1.setHtmlMsg(htmlMsg);
- EmailUtils.writeMimeMessage( new File("./target/test-emails/htmlemail1.eml"), send(htmlEmail1).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/htmlemail1.eml"), send(htmlEmail1).getMimeMessage());
// 2) text + html content + image as attachment
@@ -202,12 +193,12 @@ public class EmailLiveTest extends AbstractEmailTest
textMsg = "Your email client does not support HTML messages";
htmlMsg = "<html><b>This is a HTML message with an image attachment</b><html>";
- htmlEmail2.setSubject( "[email] 2.Test: text + html content + image as attachment");
+ htmlEmail2.setSubject("[email] 2.Test: text + html content + image as attachment");
htmlEmail2.setTextMsg(textMsg);
htmlEmail2.setHtmlMsg(htmlMsg);
- htmlEmail2.attach(url, "Apache Logo", "The official Apache logo" );
+ htmlEmail2.attach(url, "Apache Logo", "The official Apache logo");
- EmailUtils.writeMimeMessage( new File("./target/test-emails/htmlemail2.eml"), send(htmlEmail2).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/htmlemail2.eml"), send(htmlEmail2).getMimeMessage());
// 3) text + html content + inline image
@@ -215,14 +206,13 @@ public class EmailLiveTest extends AbstractEmailTest
textMsg = "Your email client does not support HTML messages";
cid = htmlEmail3.embed(imageFile, "Apache Logo");
- htmlMsg = "<html><b>This is a HTML message with an inline image - <img src=\"cid:"
- + cid + "\"> and NO attachment</b><html>";
+ htmlMsg = "<html><b>This is a HTML message with an inline image - <img src=\"cid:" + cid + "\"> and NO attachment</b><html>";
- htmlEmail3.setSubject( "[email] 3.Test: text + html content + inline image");
+ htmlEmail3.setSubject("[email] 3.Test: text + html content + inline image");
htmlEmail3.setTextMsg(textMsg);
htmlEmail3.setHtmlMsg(htmlMsg);
- EmailUtils.writeMimeMessage( new File("./target/test-emails/htmlemail3.eml"), send(htmlEmail3).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/htmlemail3.eml"), send(htmlEmail3).getMimeMessage());
// 4) text + html content + inline image + attachment
@@ -231,25 +221,23 @@ public class EmailLiveTest extends AbstractEmailTest
cid = htmlEmail4.embed(imageFile, "Apache Logo");
htmlMsg = "<html><b>This is a HTML message with an inline image - <img src=\"cid:" + cid + "\"> and attachment</b><html>";
- htmlEmail4.setSubject( "[email] 4.Test: text + html content + inline image + attachment");
+ htmlEmail4.setSubject("[email] 4.Test: text + html content + inline image + attachment");
htmlEmail4.setTextMsg(textMsg);
htmlEmail4.setHtmlMsg(htmlMsg);
htmlEmail4.attach(attachment);
- EmailUtils.writeMimeMessage( new File("./target/test-emails/htmlemail4.eml"), send(htmlEmail4).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/htmlemail4.eml"), send(htmlEmail4).getMimeMessage());
}
/**
- * This test checks the correct character encoding when sending
- * non-ASCII content using SimpleEmail.
+ * This test checks the correct character encoding when sending non-ASCII content using SimpleEmail.
*
* https://issues.apache.org/jira/browse/EMAIL-79
*
* @throws Exception the test failed
*/
@Test
- public void testCorrectCharacterEncoding() throws Exception
- {
+ public void testCorrectCharacterEncoding() throws Exception {
// U+03B1 : GREEK SMALL LETTER ALPHA
// U+03B2 : GREEK SMALL LETTER BETA
// U+03B3 : GREEK SMALL LETTER GAMMA
@@ -267,7 +255,7 @@ public class EmailLiveTest extends AbstractEmailTest
final DataSource attachment = new javax.mail.util.ByteArrayDataSource(textMsg.getBytes(StandardCharsets.UTF_8), "text/plain");
email.attach(attachment, attachmentName, "Attachment in Greek");
- EmailUtils.writeMimeMessage( new File("./target/test-emails/correct-encoding.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/correct-encoding.eml"), send(email).getMimeMessage());
}
/**
@@ -276,8 +264,7 @@ public class EmailLiveTest extends AbstractEmailTest
* @throws Exception the test failed
*/
@Test
- public void testImageHtmlEmailLocal() throws Exception
- {
+ public void testImageHtmlEmailLocal() throws Exception {
// use a simple HTML page with one image
final File htmlFile = new File("./src/test/resources/html/www.apache.org.html");
@@ -288,22 +275,18 @@ public class EmailLiveTest extends AbstractEmailTest
email.setSubject("[testImageHtmlEmail] 1.Test: simple html content");
email.setHtmlMsg(htmlMsg1);
- EmailUtils.writeMimeMessage( new File("./target/test-emails/testImageHtmlEmailLocal.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/testImageHtmlEmailLocal.eml"), send(email).getMimeMessage());
}
/**
- * Test sending a image HTML mail based on a real world website. We
- * would expect to see the ApacheCon logo at the bottom of the email.
- * Please note that not all major email clients can display the email
- * properly.
+ * Test sending a image HTML mail based on a real world website. We would expect to see the ApacheCon logo at the bottom of the email. Please note that not
+ * all major email clients can display the email properly.
*
* @throws Exception the test failed
*/
@Test
- public void testImageHtmlEmailRemote() throws Exception
- {
- if (EmailConfiguration.MAIL_FORCE_SEND)
- {
+ public void testImageHtmlEmailRemote() throws Exception {
+ if (EmailConfiguration.MAIL_FORCE_SEND) {
final URL url = new URL("https://commons.apache.org/email/");
// URL url = new URL("http://www.dzone.com/links/index.html");
final String htmlMsg = getFromUrl(url);
@@ -313,23 +296,20 @@ public class EmailLiveTest extends AbstractEmailTest
email.setSubject("[testImageHtmlEmail] 2.Test: complex html content");
email.setHtmlMsg(htmlMsg);
- EmailUtils.writeMimeMessage( new File("./target/test-emails/testImageHtmlEmailRemote.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/testImageHtmlEmailRemote.eml"), send(email).getMimeMessage());
}
}
/**
- * Testing if we are able to send a few emails in a batch, i.e.
- * using a single authenticated {@code Transport} instance.
- * Use a single instance speeds up processing since the
- * authorization is only done once.
+ * Testing if we are able to send a few emails in a batch, i.e. using a single authenticated {@code Transport} instance. Use a single instance speeds up
+ * processing since the authorization is only done once.
*
* https://issues.apache.org/jira/browse/EMAIL-72
*
* @throws Exception the test failed.
*/
@Test
- public void testSendingEmailsInBatch() throws Exception
- {
+ public void testSendingEmailsInBatch() throws Exception {
final List<SimpleEmail> emails = new ArrayList<>();
// we need to instantiate an email to provide the mail session - a bit ugly
@@ -337,8 +317,7 @@ public class EmailLiveTest extends AbstractEmailTest
final Transport transport = session.getTransport();
// simulate creating a bunch of emails using an existing mail session
- for (int i = 0; i < 3; i++)
- {
+ for (int i = 0; i < 3; i++) {
final SimpleEmail personalizedEmail = (SimpleEmail) create(SimpleEmail.class);
personalizedEmail.setMailSession(session);
personalizedEmail.setSubject("Personalized Test Mail Nr. " + i);
@@ -348,19 +327,17 @@ public class EmailLiveTest extends AbstractEmailTest
}
// send the list of emails using a single 'Transport' instance.
- if ( EmailConfiguration.MAIL_FORCE_SEND )
- {
+ if (EmailConfiguration.MAIL_FORCE_SEND) {
transport.connect();
- for (final SimpleEmail personalizedEmail : emails)
- {
+ for (final SimpleEmail personalizedEmail : emails) {
final MimeMessage mimeMessage = personalizedEmail.getMimeMessage();
Transport.send(mimeMessage);
System.out.println("Successfully sent the following email : " + mimeMessage.getMessageID());
}
transport.close();
- }
+ }
}
/**
@@ -371,8 +348,7 @@ public class EmailLiveTest extends AbstractEmailTest
* @throws Exception the test failed.
*/
@Test
- public void testPartialSend() throws Exception
- {
+ public void testPartialSend() throws Exception {
final SimpleEmail email = (SimpleEmail) create(SimpleEmail.class);
email.addTo(EmailConfiguration.TEST_TO);
email.addTo("nobody@is.invalid");
@@ -381,7 +357,7 @@ public class EmailLiveTest extends AbstractEmailTest
email.setSendPartial(true);
- EmailUtils.writeMimeMessage( new File("./target/test-emails/partialmail.eml"), send(email).getMimeMessage());
+ EmailUtils.writeMimeMessage(new File("./target/test-emails/partialmail.eml"), send(email).getMimeMessage());
}
}
diff --git a/src/test/java/org/apache/commons/mail/EmailTest.java b/src/test/java/org/apache/commons/mail/EmailTest.java
index a96360f..5718bdc 100644
--- a/src/test/java/org/apache/commons/mail/EmailTest.java
+++ b/src/test/java/org/apache/commons/mail/EmailTest.java
@@ -49,29 +49,21 @@ import org.junit.Test;
*
* @since 1.0
*/
-public class EmailTest extends AbstractEmailTest
-{
+public class EmailTest extends AbstractEmailTest {
- private static final String[] VALID_EMAILS =
- {
- "me@home.com",
- "joe.doe@apache.org",
- "someone_here@work-address.com.au"
- };
+ private static final String[] VALID_EMAILS = { "me@home.com", "joe.doe@apache.org", "someone_here@work-address.com.au" };
/** mock for testing */
private MockEmailConcrete email;
@Before
- public void setUpEmailTest()
- {
+ public void setUpEmailTest() {
// reusable objects to be used across multiple tests
email = new MockEmailConcrete();
}
@Test
- public void testGetSetDebug()
- {
+ public void testGetSetDebug() {
email.setDebug(true);
assertTrue(email.isDebug());
email.setDebug(false);
@@ -79,15 +71,12 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetSession() throws Exception
- {
+ public void testGetSetSession() throws Exception {
final Properties properties = new Properties(System.getProperties());
properties.setProperty(EmailConstants.MAIL_TRANSPORT_PROTOCOL, EmailConstants.SMTP);
- properties.setProperty(
- EmailConstants.MAIL_PORT,
- String.valueOf(getMailServerPort()));
+ properties.setProperty(EmailConstants.MAIL_PORT, String.valueOf(getMailServerPort()));
properties.setProperty(EmailConstants.MAIL_HOST, strTestMailServer);
properties.setProperty(EmailConstants.MAIL_DEBUG, String.valueOf(false));
@@ -99,8 +88,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetAuthentication()
- {
+ public void testGetSetAuthentication() {
// setup
final String strUsername = "user.name";
final String strPassword = "user.pwd";
@@ -108,45 +96,32 @@ public class EmailTest extends AbstractEmailTest
// this is cast into DefaultAuthenticator for convenience
// and give us access to the getPasswordAuthentication fn
- final DefaultAuthenticator retrievedAuth =
- (DefaultAuthenticator) email.getAuthenticator();
+ final DefaultAuthenticator retrievedAuth = (DefaultAuthenticator) email.getAuthenticator();
// tests
- assertEquals(
- strUsername,
- retrievedAuth.getPasswordAuthentication().getUserName());
- assertEquals(
- strPassword,
- retrievedAuth.getPasswordAuthentication().getPassword());
+ assertEquals(strUsername, retrievedAuth.getPasswordAuthentication().getUserName());
+ assertEquals(strPassword, retrievedAuth.getPasswordAuthentication().getPassword());
}
@Test
- public void testGetSetAuthenticator()
- {
+ public void testGetSetAuthenticator() {
// setup
final String strUsername = "user.name";
final String strPassword = "user.pwd";
- final DefaultAuthenticator authenticator =
- new DefaultAuthenticator(strUsername, strPassword);
+ final DefaultAuthenticator authenticator = new DefaultAuthenticator(strUsername, strPassword);
email.setAuthenticator(authenticator);
// this is cast into DefaultAuthenticator for convenience
// and give us access to the getPasswordAuthentication fn
- final DefaultAuthenticator retrievedAuth =
- (DefaultAuthenticator) email.getAuthenticator();
+ final DefaultAuthenticator retrievedAuth = (DefaultAuthenticator) email.getAuthenticator();
// tests
- assertEquals(
- strUsername,
- retrievedAuth.getPasswordAuthentication().getUserName());
- assertEquals(
- strPassword,
- retrievedAuth.getPasswordAuthentication().getPassword());
+ assertEquals(strUsername, retrievedAuth.getPasswordAuthentication().getUserName());
+ assertEquals(strPassword, retrievedAuth.getPasswordAuthentication().getPassword());
}
@Test
- public void testGetSetCharset()
- {
+ public void testGetSetCharset() {
Charset set = StandardCharsets.US_ASCII;
email.setCharset(set.name());
assertEquals(set.name(), email.getCharset());
@@ -157,8 +132,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetContentEmptyMimeMultipart()
- {
+ public void testSetContentEmptyMimeMultipart() {
final MimeMultipart part = new MimeMultipart();
email.setContent(part);
@@ -166,8 +140,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetContentMimeMultipart()
- {
+ public void testSetContentMimeMultipart() {
final MimeMultipart part = new MimeMultipart("abc123");
email.setContent(part);
@@ -175,15 +148,13 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetContentNull() throws Exception
- {
+ public void testSetContentNull() throws Exception {
email.setContent(null);
assertNull(email.getContentMimeMultipart());
}
@Test
- public void testSetContentObject()
- {
+ public void testSetContentObject() {
// ====================================================================
// test (string object and valid content type)
String testObject = "test string object";
@@ -222,8 +193,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetHostName()
- {
+ public void testGetSetHostName() {
for (final String validChar : testCharsValid) {
email.setHostName(validChar);
assertEquals(validChar, email.getHostName());
@@ -231,57 +201,41 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetSmtpPort()
- {
+ public void testGetSetSmtpPort() {
email.setSmtpPort(1);
- assertEquals(
- 1,
- Integer.parseInt(email.getSmtpPort()));
+ assertEquals(1, Integer.parseInt(email.getSmtpPort()));
email.setSmtpPort(Integer.MAX_VALUE);
- assertEquals(
- Integer.MAX_VALUE,
- Integer.parseInt(email.getSmtpPort()));
+ assertEquals(Integer.MAX_VALUE, Integer.parseInt(email.getSmtpPort()));
}
@Test
- public void testSetSmtpPortZero()
- {
+ public void testSetSmtpPortZero() {
assertThrows(IllegalArgumentException.class, () -> email.setSmtpPort(0));
}
@Test
- public void testSetSmptPortNegative()
- {
+ public void testSetSmptPortNegative() {
assertThrows(IllegalArgumentException.class, () -> email.setSmtpPort(-1));
}
@Test
- public void testSetSmtpPortMinValue()
- {
+ public void testSetSmtpPortMinValue() {
assertThrows(IllegalArgumentException.class, () -> email.setSmtpPort(Integer.MIN_VALUE));
}
@Test
- public void testSetFrom() throws Exception
- {
+ public void testSetFrom() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "me@home.com"));
- arrExpected.add(
- new InternetAddress(
- "joe.doe@apache.org",
- "joe.doe@apache.org"));
- arrExpected.add(
- new InternetAddress(
- "someone_here@work-address.com.au",
- "someone_here@work-address.com.au"));
-
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ arrExpected.add(new InternetAddress("joe.doe@apache.org", "joe.doe@apache.org"));
+ arrExpected.add(new InternetAddress("someone_here@work-address.com.au", "someone_here@work-address.com.au"));
+
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set from
email.setFrom(VALID_EMAILS[i]);
@@ -292,15 +246,13 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetFromWithEncoding() throws Exception
- {
+ public void testSetFromWithEncoding() throws Exception {
// ====================================================================
// Test Success (with charset set)
// ====================================================================
final String testValidEmail = "me@home.com";
- final InternetAddress inetExpected =
- new InternetAddress("me@home.com", "me@home.com", EmailConstants.ISO_8859_1);
+ final InternetAddress inetExpected = new InternetAddress("me@home.com", "me@home.com", EmailConstants.ISO_8859_1);
// set from
email.setFrom(testValidEmail, testValidEmail, EmailConstants.ISO_8859_1);
@@ -311,25 +263,17 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetFrom2() throws Exception
- {
+ public void testSetFrom2() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1"));
- arrExpected.add(
- new InternetAddress(
- "joe.doe@apache.org",
- "joe.doe@apache.org"));
- arrExpected.add(
- new InternetAddress(
- "someone_here@work-address.com.au",
- "someone_here@work-address.com.au"));
-
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ arrExpected.add(new InternetAddress("joe.doe@apache.org", "joe.doe@apache.org"));
+ arrExpected.add(new InternetAddress("someone_here@work-address.com.au", "someone_here@work-address.com.au"));
+
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set from
email.setFrom(VALID_EMAILS[i], testEmailNames[i]);
@@ -345,8 +289,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddTo() throws Exception
- {
+ public void testAddTo() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -366,8 +309,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddToArray() throws Exception
- {
+ public void testAddToArray() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -377,7 +319,7 @@ public class EmailTest extends AbstractEmailTest
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- //set To
+ // set To
email.addTo(VALID_EMAILS);
// retrieve and verify
@@ -386,25 +328,19 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddToWithEncoding() throws Exception
- {
+ public void testAddToWithEncoding() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final String testCharset = EmailConstants.ISO_8859_1;
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
- arrExpected.add(
- new InternetAddress(
- "me@home.com",
- "Name1",
- testCharset));
+ arrExpected.add(new InternetAddress("me@home.com", "Name1", testCharset));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set from
email.addTo(VALID_EMAILS[i], testEmailNames[i], testCharset);
}
@@ -415,21 +351,19 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddTo2() throws Exception
- {
+ public void testAddTo2() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1"));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set from
email.addTo(VALID_EMAILS[i], testEmailNames[i]);
}
@@ -440,52 +374,39 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddToBadEncoding()
- {
+ public void testAddToBadEncoding() {
assertThrows(IllegalCharsetNameException.class, () -> email.addTo("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"));
}
@Test
- public void testSetTo() throws Exception
- {
+ public void testSetTo() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final List<InternetAddress> testEmailValid2 = new ArrayList<>();
testEmailValid2.add(new InternetAddress("me@home.com", "Name1"));
- testEmailValid2.add(
- new InternetAddress(
- "joe.doe@apache.org",
- "joe.doe@apache.org"));
- testEmailValid2.add(
- new InternetAddress(
- "someone_here@work-address.com.au",
- "someone_here@work-address.com.au"));
+ testEmailValid2.add(new InternetAddress("joe.doe@apache.org", "joe.doe@apache.org"));
+ testEmailValid2.add(new InternetAddress("someone_here@work-address.com.au", "someone_here@work-address.com.au"));
email.setTo(testEmailValid2);
// retrieve and verify
assertEquals(testEmailValid2.size(), email.getToAddresses().size());
- assertEquals(
- testEmailValid2.toString(),
- email.getToAddresses().toString());
+ assertEquals(testEmailValid2.toString(), email.getToAddresses().toString());
}
@Test
- public void testSetToNull()
- {
+ public void testSetToNull() {
assertThrows(EmailException.class, () -> email.setTo(null));
}
@Test
- public void testSetToEmpty()
- {
+ public void testSetToEmpty() {
assertThrows(EmailException.class, () -> email.setTo(Collections.<InternetAddress>emptyList()));
}
@Test
- public void testAddCc() throws Exception
- {
+ public void testAddCc() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -505,8 +426,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddCcArray() throws Exception
- {
+ public void testAddCcArray() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -516,7 +436,7 @@ public class EmailTest extends AbstractEmailTest
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- //set Cc array
+ // set Cc array
email.addCc(VALID_EMAILS);
// retrieve and verify
@@ -525,23 +445,20 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddCcWithEncoding() throws Exception
- {
+ public void testAddCcWithEncoding() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final String testCharset = EmailConstants.ISO_8859_1;
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
- arrExpected.add(
- new InternetAddress("me@home.com", "Name1", testCharset));
+ arrExpected.add(new InternetAddress("me@home.com", "Name1", testCharset));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
// add valid ccs
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
email.addCc(VALID_EMAILS[i], testEmailNames[i], testCharset);
}
@@ -551,21 +468,19 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddCc2() throws Exception
- {
+ public void testAddCc2() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1"));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set from
email.addCc(VALID_EMAILS[i], testEmailNames[i]);
}
@@ -576,42 +491,36 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddCcBadEncoding()
- {
+ public void testAddCcBadEncoding() {
assertThrows(IllegalCharsetNameException.class, () -> email.addCc("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"));
}
@Test
- public void testSetCc() throws Exception
- {
+ public void testSetCc() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final List<InternetAddress> testEmailValid2 = new ArrayList<>();
testEmailValid2.add(new InternetAddress("Name1 <me...@home.com>"));
testEmailValid2.add(new InternetAddress("\"joe.doe@apache.org\" <jo...@apache.org>"));
- testEmailValid2.add(
- new InternetAddress("\"someone_here@work.com.au\" <so...@work.com.au>"));
+ testEmailValid2.add(new InternetAddress("\"someone_here@work.com.au\" <so...@work.com.au>"));
email.setCc(testEmailValid2);
assertEquals(testEmailValid2, email.getCcAddresses());
}
@Test
- public void testSetCcNull()
- {
+ public void testSetCcNull() {
assertThrows(EmailException.class, () -> email.setCc(null));
}
@Test
- public void testSetCcEmpty()
- {
+ public void testSetCcEmpty() {
assertThrows(EmailException.class, () -> email.setCc(Collections.<InternetAddress>emptyList()));
}
@Test
- public void testAddBcc() throws Exception
- {
+ public void testAddBcc() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -627,14 +536,11 @@ public class EmailTest extends AbstractEmailTest
// retrieve and verify
assertEquals(arrExpected.size(), email.getBccAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getBccAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getBccAddresses().toString());
}
@Test
- public void testAddBccArray() throws Exception
- {
+ public void testAddBccArray() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -649,107 +555,86 @@ public class EmailTest extends AbstractEmailTest
// retrieve and verify
assertEquals(arrExpected.size(), email.getBccAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getBccAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getBccAddresses().toString());
}
@Test
- public void testAddBccWithEncoding() throws Exception
- {
+ public void testAddBccWithEncoding() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final String testCharset = EmailConstants.ISO_8859_1;
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1", testCharset));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set bccs
email.addBcc(VALID_EMAILS[i], testEmailNames[i], testCharset);
}
// retrieve and verify
assertEquals(arrExpected.size(), email.getBccAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getBccAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getBccAddresses().toString());
}
@Test
- public void testAddBcc2() throws Exception
- {
+ public void testAddBcc2() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1"));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set from
email.addBcc(VALID_EMAILS[i], testEmailNames[i]);
}
// retrieve and verify
assertEquals(arrExpected.size(), email.getBccAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getBccAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getBccAddresses().toString());
}
@Test
- public void testAddBccBadEncoding()
- {
+ public void testAddBccBadEncoding() {
assertThrows(IllegalCharsetNameException.class, () -> email.addBcc("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"));
}
@Test
- public void testSetBcc() throws Exception
- {
+ public void testSetBcc() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final List<InternetAddress> testInetEmailValid = new ArrayList<>();
testInetEmailValid.add(new InternetAddress("me@home.com", "Name1"));
- testInetEmailValid.add(
- new InternetAddress(
- "joe.doe@apache.org",
- "joe.doe@apache.org"));
- testInetEmailValid.add(
- new InternetAddress(
- "someone_here@work-address.com.au",
- "someone_here@work-address.com.au"));
+ testInetEmailValid.add(new InternetAddress("joe.doe@apache.org", "joe.doe@apache.org"));
+ testInetEmailValid.add(new InternetAddress("someone_here@work-address.com.au", "someone_here@work-address.com.au"));
email.setBcc(testInetEmailValid);
assertEquals(testInetEmailValid, email.getBccAddresses());
}
@Test
- public void testSetBccNull()
- {
+ public void testSetBccNull() {
assertThrows(EmailException.class, () -> email.setBcc(null));
}
@Test
- public void testSetBccEmpty()
- {
+ public void testSetBccEmpty() {
assertThrows(EmailException.class, () -> email.setBcc(Collections.<InternetAddress>emptyList()));
}
@Test
- public void testAddReplyTo() throws Exception
- {
+ public void testAddReplyTo() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -765,74 +650,62 @@ public class EmailTest extends AbstractEmailTest
// retrieve and verify
assertEquals(arrExpected.size(), email.getReplyToAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getReplyToAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getReplyToAddresses().toString());
}
@Test
- public void testAddReplyToWithEncoding() throws Exception
- {
+ public void testAddReplyToWithEncoding() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
final String testCharset = EmailConstants.ISO_8859_1;
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1", testCharset));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set replyTo
email.addReplyTo(VALID_EMAILS[i], testEmailNames[i], testCharset);
}
// retrieve and verify
assertEquals(arrExpected.size(), email.getReplyToAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getReplyToAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getReplyToAddresses().toString());
}
@Test
- public void testAddReplyTo2() throws Exception
- {
+ public void testAddReplyTo2() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
- final String[] testEmailNames = {"Name1", "", null};
+ final String[] testEmailNames = { "Name1", "", null };
final List<InternetAddress> arrExpected = new ArrayList<>();
arrExpected.add(new InternetAddress("me@home.com", "Name1"));
arrExpected.add(new InternetAddress("joe.doe@apache.org"));
arrExpected.add(new InternetAddress("someone_here@work-address.com.au"));
- for (int i = 0; i < VALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < VALID_EMAILS.length; i++) {
// set replyTo
email.addReplyTo(VALID_EMAILS[i], testEmailNames[i]);
}
// retrieve and verify
assertEquals(arrExpected.size(), email.getReplyToAddresses().size());
- assertEquals(
- arrExpected.toString(),
- email.getReplyToAddresses().toString());
+ assertEquals(arrExpected.toString(), email.getReplyToAddresses().toString());
}
@Test
- public void testAddReplyToBadEncoding()
- {
+ public void testAddReplyToBadEncoding() {
assertThrows(IllegalCharsetNameException.class, () -> email.addReplyTo("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"));
}
@Test
- public void testAddHeader()
- {
+ public void testAddHeader() {
// ====================================================================
// Test Success
// ====================================================================
@@ -852,32 +725,27 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testAddHeaderEmptyName()
- {
+ public void testAddHeaderEmptyName() {
assertThrows(IllegalArgumentException.class, () -> email.addHeader("", "me@home.com"));
}
@Test
- public void testAddHeaderNullName()
- {
+ public void testAddHeaderNullName() {
assertThrows(IllegalArgumentException.class, () -> email.addHeader(null, "me@home.com"));
}
@Test
- public void testAddHeaderEmptyValue()
- {
+ public void testAddHeaderEmptyValue() {
assertThrows(IllegalArgumentException.class, () -> email.addHeader("X-Mailer", ""));
}
@Test
- public void testAddHeaderNullValue()
- {
+ public void testAddHeaderNullValue() {
assertThrows(IllegalArgumentException.class, () -> email.addHeader("X-Mailer", null));
}
@Test
- public void testSetHeaders()
- {
+ public void testSetHeaders() {
final Map<String, String> ht = new Hashtable<>();
ht.put("X-Priority", "1");
ht.put("Disposition-Notification-To", "me@home.com");
@@ -890,8 +758,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetHeader()
- {
+ public void testGetHeader() {
final Map<String, String> ht = new Hashtable<>();
ht.put("X-Foo", "Bar");
ht.put("X-Int", "1");
@@ -903,8 +770,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetHeaders()
- {
+ public void testGetHeaders() {
final Map<String, String> ht = new Hashtable<>();
ht.put("X-Foo", "Bar");
ht.put("X-Int", "1");
@@ -915,8 +781,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testFoldingHeaders() throws Exception
- {
+ public void testFoldingHeaders() throws Exception {
email.setHostName(strTestMailServer);
email.setSmtpPort(getMailServerPort());
email.setFrom("a@b.com");
@@ -947,27 +812,23 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetHeaderEmptyValue()
- {
+ public void testSetHeaderEmptyValue() {
assertThrows(IllegalArgumentException.class, () -> email.setHeaders(Collections.singletonMap("X-Mailer", "")));
}
@Test
- public void testSetHeaderNullValue()
- {
+ public void testSetHeaderNullValue() {
assertThrows(IllegalArgumentException.class, () -> email.setHeaders(Collections.singletonMap("X-Mailer", (String) null)));
}
@Test
- public void testSetHeaderEmptyName()
- {
+ public void testSetHeaderEmptyName() {
assertThrows(IllegalArgumentException.class, () -> email.setHeaders(Collections.singletonMap("", "me@home.com")));
}
@Test
- public void testSetHeaderNullName()
- {
+ public void testSetHeaderNullName() {
assertThrows(IllegalArgumentException.class, () -> email.setHeaders(Collections.singletonMap((String) null, "me@home.com")));
}
@@ -997,8 +858,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSendNoHostName()
- {
+ public void testSendNoHostName() {
getMailServer();
email = new MockEmailConcrete();
@@ -1007,10 +867,8 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSendBadHostName()
- {
- try
- {
+ public void testSendBadHostName() {
+ try {
getMailServer();
email = new MockEmailConcrete();
@@ -1022,23 +880,18 @@ public class EmailTest extends AbstractEmailTest
email.addBcc("me@home.com");
email.addReplyTo("me@home.com");
- email.setContent(
- "test string object",
- " ; charset=" + EmailConstants.US_ASCII);
+ email.setContent("test string object", " ; charset=" + EmailConstants.US_ASCII);
email.send();
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(e.getCause() instanceof ParseException);
fakeMailServer.stop();
}
}
@Test
- public void testSendFromNotSet() throws Exception
- {
+ public void testSendFromNotSet() throws Exception {
getMailServer();
email = new MockEmailConcrete();
@@ -1050,22 +903,20 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSendFromSetInSession() throws Exception
- {
- getMailServer();
+ public void testSendFromSetInSession() throws Exception {
+ getMailServer();
- email = new MockEmailConcrete();
- email.setHostName(strTestMailServer);
- email.setSmtpPort(getMailServerPort());
- email.addTo("me@home.com");
- email.getSession().getProperties().setProperty(EmailConstants.MAIL_FROM, "me@home.com");
+ email = new MockEmailConcrete();
+ email.setHostName(strTestMailServer);
+ email.setSmtpPort(getMailServerPort());
+ email.addTo("me@home.com");
+ email.getSession().getProperties().setProperty(EmailConstants.MAIL_FROM, "me@home.com");
- email.send();
+ email.send();
}
@Test
- public void testSendDestinationNotSet() throws Exception
- {
+ public void testSendDestinationNotSet() throws Exception {
getMailServer();
email = new MockEmailConcrete();
@@ -1077,8 +928,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSendBadAuthSet() throws Exception
- {
+ public void testSendBadAuthSet() throws Exception {
getMailServer();
email = new MockEmailConcrete();
@@ -1092,10 +942,8 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSendCorrectSmtpPortContainedInException()
- {
- try
- {
+ public void testSendCorrectSmtpPortContainedInException() {
+ try {
getMailServer();
email = new MockEmailConcrete();
@@ -1106,17 +954,14 @@ public class EmailTest extends AbstractEmailTest
email.setAuthentication(null, null);
email.send();
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(e.getMessage().contains("bad.host.com:465"));
fakeMailServer.stop();
}
}
@Test
- public void testGetSetSentDate()
- {
+ public void testGetSetSentDate() {
// with input date
final Date dtTest = Calendar.getInstance().getTime();
@@ -1136,40 +981,26 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testToInternetAddressArray() throws Exception
- {
+ public void testToInternetAddressArray() throws Exception {
final List<InternetAddress> testInetEmailValid = new ArrayList<>();
testInetEmailValid.add(new InternetAddress("me@home.com", "Name1"));
- testInetEmailValid.add(
- new InternetAddress(
- "joe.doe@apache.org",
- "joe.doe@apache.org"));
- testInetEmailValid.add(
- new InternetAddress(
- "someone_here@work-address.com.au",
- "someone_here@work-address.com.au"));
+ testInetEmailValid.add(new InternetAddress("joe.doe@apache.org", "joe.doe@apache.org"));
+ testInetEmailValid.add(new InternetAddress("someone_here@work-address.com.au", "someone_here@work-address.com.au"));
email.setBcc(testInetEmailValid);
- assertEquals(
- testInetEmailValid.size(),
- email.getBccAddresses().size());
+ assertEquals(testInetEmailValid.size(), email.getBccAddresses().size());
}
@Test
- public void testSetPopBeforeSmtp()
- {
+ public void testSetPopBeforeSmtp() {
// simple test (can be improved)
final boolean boolPopBeforeSmtp = true;
final String strHost = "mail.home.com";
final String strUsername = "user.name";
final String strPassword = "user.passwd";
- email.setPopBeforeSmtp(
- boolPopBeforeSmtp,
- strHost,
- strUsername,
- strPassword);
+ email.setPopBeforeSmtp(boolPopBeforeSmtp, strHost, strUsername, strPassword);
// retrieve and verify
assertEquals(boolPopBeforeSmtp, email.isPopBeforeSmtp());
@@ -1179,20 +1010,16 @@ public class EmailTest extends AbstractEmailTest
}
/**
- * Test: When Email.setCharset() is called, a subsequent setContent()
- * should use that charset for text content types unless overridden
- * by the contentType parameter.
- * See https://issues.apache.org/jira/browse/EMAIL-1.
+ * Test: When Email.setCharset() is called, a subsequent setContent() should use that charset for text content types unless overridden by the contentType
+ * parameter. See https://issues.apache.org/jira/browse/EMAIL-1.
*
*
- * Case 1:
- * Setting a default charset results in adding that charset info to
- * to the content type of a text/based content object.
+ * Case 1: Setting a default charset results in adding that charset info to to the content type of a text/based content object.
+ *
* @throws Exception on any error
*/
@Test
- public void testDefaultCharsetAppliesToTextContent() throws Exception
- {
+ public void testDefaultCharsetAppliesToTextContent() throws Exception {
email.setHostName(strTestMailServer);
email.setSmtpPort(getMailServerPort());
email.setFrom("a@b.com");
@@ -1208,15 +1035,12 @@ public class EmailTest extends AbstractEmailTest
}
/**
- * Case 2:
- * A default charset is overridden by an explicitly specified
- * charset in setContent().
+ * Case 2: A default charset is overridden by an explicitly specified charset in setContent().
+ *
* @throws Exception on any error
*/
@Test
- public void testDefaultCharsetCanBeOverriddenByContentType()
- throws Exception
- {
+ public void testDefaultCharsetCanBeOverriddenByContentType() throws Exception {
email.setHostName(strTestMailServer);
email.setSmtpPort(getMailServerPort());
email.setFrom("a@b.com");
@@ -1232,14 +1056,12 @@ public class EmailTest extends AbstractEmailTest
}
/**
- * Case 3:
- * A non-text content object ignores a default charset entirely.
+ * Case 3: A non-text content object ignores a default charset entirely.
+ *
* @throws Exception on any error
*/
@Test
- public void testDefaultCharsetIgnoredByNonTextContent()
- throws Exception
- {
+ public void testDefaultCharsetIgnoredByNonTextContent() throws Exception {
email.setHostName(strTestMailServer);
email.setSmtpPort(getMailServerPort());
email.setFrom("a@b.com");
@@ -1255,8 +1077,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testCorrectContentTypeForPNG() throws Exception
- {
+ public void testCorrectContentTypeForPNG() throws Exception {
email.setHostName(strTestMailServer);
email.setSmtpPort(getMailServerPort());
email.setFrom("a@b.com");
@@ -1273,8 +1094,7 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetBounceAddress()
- {
+ public void testGetSetBounceAddress() {
assertNull(email.getBounceAddress());
final String bounceAddress = "test_bounce@apache.org";
@@ -1285,21 +1105,18 @@ public class EmailTest extends AbstractEmailTest
}
@Test
- public void testSetNullAndEmptyBounceAddress()
- {
+ public void testSetNullAndEmptyBounceAddress() {
assertNull(email.setBounceAddress(null).getBounceAddress());
assertEquals("", email.setBounceAddress("").getBounceAddress());
}
@Test
- public void testGetSetInvalidBounceAddress()
- {
+ public void testGetSetInvalidBounceAddress() {
assertThrows(RuntimeException.class, () -> email.setBounceAddress("invalid-bounce-address"));
}
@Test
- public void testSupportForInternationalDomainNames() throws Exception
- {
+ public void testSupportForInternationalDomainNames() throws Exception {
email.setHostName(strTestMailServer);
email.setSmtpPort(getMailServerPort());
email.setFrom("from@d\u00F6m\u00E4in.example");
diff --git a/src/test/java/org/apache/commons/mail/HtmlEmailTest.java b/src/test/java/org/apache/commons/mail/HtmlEmailTest.java
index e717e95..d583f90 100644
--- a/src/test/java/org/apache/commons/mail/HtmlEmailTest.java
+++ b/src/test/java/org/apache/commons/mail/HtmlEmailTest.java
@@ -47,26 +47,22 @@ import org.powermock.modules.junit4.PowerMockRunner;
* @since 1.0
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest( { MockHtmlEmailConcrete.class })
-public class HtmlEmailTest extends AbstractEmailTest
-{
+@PrepareForTest({ MockHtmlEmailConcrete.class })
+public class HtmlEmailTest extends AbstractEmailTest {
private MockHtmlEmailConcrete email;
@Before
- public void setUpHtmlEmailTest()
- {
+ public void setUpHtmlEmailTest() {
// reusable objects to be used across multiple tests
this.email = new MockHtmlEmailConcrete();
}
@Test
- public void testGetSetTextMsg() throws EmailException
- {
+ public void testGetSetTextMsg() throws EmailException {
// ====================================================================
// Test Success
// ====================================================================
- for (final String validChar : testCharsValid)
- {
+ for (final String validChar : testCharsValid) {
this.email.setTextMsg(validChar);
assertEquals(validChar, this.email.getTextMsg());
}
@@ -74,15 +70,11 @@ public class HtmlEmailTest extends AbstractEmailTest
// ====================================================================
// Test Exception
// ====================================================================
- for (final String invalidChar : this.testCharsNotValid)
- {
- try
- {
+ for (final String invalidChar : this.testCharsNotValid) {
+ try {
this.email.setTextMsg(invalidChar);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
@@ -90,13 +82,11 @@ public class HtmlEmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetHtmlMsg() throws EmailException
- {
+ public void testGetSetHtmlMsg() throws EmailException {
// ====================================================================
// Test Success
// ====================================================================
- for (final String validChar : testCharsValid)
- {
+ for (final String validChar : testCharsValid) {
this.email.setHtmlMsg(validChar);
assertEquals(validChar, this.email.getHtmlMsg());
}
@@ -104,15 +94,11 @@ public class HtmlEmailTest extends AbstractEmailTest
// ====================================================================
// Test Exception
// ====================================================================
- for (final String invalidChar : this.testCharsNotValid)
- {
- try
- {
+ for (final String invalidChar : this.testCharsNotValid) {
+ try {
this.email.setHtmlMsg(invalidChar);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
@@ -120,32 +106,25 @@ public class HtmlEmailTest extends AbstractEmailTest
}
@Test
- public void testGetSetMsg() throws EmailException
- {
+ public void testGetSetMsg() throws EmailException {
// ====================================================================
// Test Success
// ====================================================================
- for (final String validChar : testCharsValid)
- {
+ for (final String validChar : testCharsValid) {
this.email.setMsg(validChar);
assertEquals(validChar, this.email.getTextMsg());
- assertTrue(
- this.email.getHtmlMsg().contains(validChar));
+ assertTrue(this.email.getHtmlMsg().contains(validChar));
}
// ====================================================================
// Test Exception
// ====================================================================
- for (final String invalidChar : this.testCharsNotValid)
- {
- try
- {
+ for (final String invalidChar : this.testCharsNotValid) {
+ try {
this.email.setMsg(invalidChar);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
@@ -153,27 +132,23 @@ public class HtmlEmailTest extends AbstractEmailTest
}
@Test
- public void testEmbedUrl() throws Exception
- {
+ public void testEmbedUrl() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
- final String strEmbed =
- this.email.embed(new URL(this.strTestURL), "Test name");
+ final String strEmbed = this.email.embed(new URL(this.strTestURL), "Test name");
assertNotNull(strEmbed);
assertEquals(HtmlEmail.CID_LENGTH, strEmbed.length());
// if we embed the same name again, do we get the same content ID
// back?
- final String testCid =
- this.email.embed(new URL(this.strTestURL), "Test name");
+ final String testCid = this.email.embed(new URL(this.strTestURL), "Test name");
assertEquals(strEmbed, testCid);
// if we embed the same URL under a different name, is the content ID
// unique?
- final String newCid =
- this.email.embed(new URL(this.strTestURL), "Test name 2");
+ final String newCid = this.email.embed(new URL(this.strTestURL), "Test name 2");
assertFalse(strEmbed.equals(newCid));
// ====================================================================
@@ -181,32 +156,25 @@ public class HtmlEmailTest extends AbstractEmailTest
// ====================================================================
// Does an invalid URL throw an exception?
- try
- {
+ try {
this.email.embed(createInvalidURL(), "Bad URL");
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
// expected
}
// if we try to embed a different URL under a previously used name,
// does it complain?
- try
- {
+ try {
this.email.embed(new URL("http://www.google.com"), "Test name");
fail("shouldn't be able to use an existing name with a different URL!");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
// expected
}
}
@Test
- public void testEmbedFile() throws Exception
- {
+ public void testEmbedFile() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -215,27 +183,22 @@ public class HtmlEmailTest extends AbstractEmailTest
file.deleteOnExit();
final String strEmbed = this.email.embed(file);
assertNotNull(strEmbed);
- assertEquals("generated CID has wrong length",
- HtmlEmail.CID_LENGTH, strEmbed.length());
+ assertEquals("generated CID has wrong length", HtmlEmail.CID_LENGTH, strEmbed.length());
// if we embed the same file again, do we get the same content ID
// back?
- final String testCid =
- this.email.embed(file);
- assertEquals("didn't get same CID after embedding same file twice",
- strEmbed, testCid);
+ final String testCid = this.email.embed(file);
+ assertEquals("didn't get same CID after embedding same file twice", strEmbed, testCid);
// if we embed a new file, is the content ID unique?
final File otherFile = File.createTempFile("testEmbedFile2", "txt");
otherFile.deleteOnExit();
final String newCid = this.email.embed(otherFile);
- assertFalse("didn't get unique CID from embedding new file",
- strEmbed.equals(newCid));
+ assertFalse("didn't get unique CID from embedding new file", strEmbed.equals(newCid));
}
@Test
- public void testEmbedUrlAndFile() throws Exception
- {
+ public void testEmbedUrlAndFile() throws Exception {
final File tmpFile = File.createTempFile("testfile", "txt");
tmpFile.deleteOnExit();
final String fileCid = this.email.embed(tmpFile);
@@ -243,25 +206,20 @@ public class HtmlEmailTest extends AbstractEmailTest
final URL fileUrl = tmpFile.toURI().toURL();
final String urlCid = this.email.embed(fileUrl, "urlName");
- assertFalse("file and URL cids should be different even for same resource",
- fileCid.equals(urlCid));
+ assertFalse("file and URL cids should be different even for same resource", fileCid.equals(urlCid));
}
@Test
- public void testEmbedDataSource() throws Exception
- {
+ public void testEmbedDataSource() throws Exception {
final File tmpFile = File.createTempFile("testEmbedDataSource", "txt");
tmpFile.deleteOnExit();
final FileDataSource dataSource = new FileDataSource(tmpFile);
// does embedding a datasource without a name fail?
- try
- {
+ try {
this.email.embed(dataSource, "");
fail("embedding with an empty string for a name should fail");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
// expected
}
@@ -271,30 +229,25 @@ public class HtmlEmailTest extends AbstractEmailTest
// does embedding the same datasource under the same name return
// the original cid?
final String sameCid = this.email.embed(dataSource, "testname");
- assertEquals("didn't get same CID for embedding same datasource twice",
- cid, sameCid);
+ assertEquals("didn't get same CID for embedding same datasource twice", cid, sameCid);
// does embedding another datasource under the same name fail?
final File anotherFile = File.createTempFile("testEmbedDataSource2", "txt");
anotherFile.deleteOnExit();
final FileDataSource anotherDS = new FileDataSource(anotherFile);
- try
- {
+ try {
this.email.embed(anotherDS, "testname");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
// expected
}
}
/**
* @throws EmailException when bad addresses and attachments are used
- * @throws IOException if creating a temp file, URL or sending fails
+ * @throws IOException if creating a temp file, URL or sending fails
*/
@Test
- public void testSend() throws EmailException, IOException
- {
+ public void testSend() throws EmailException, IOException {
final EmailAttachment attachment = new EmailAttachment();
/** File to used to test file attachments (Must be valid) */
@@ -320,7 +273,7 @@ public class HtmlEmailTest extends AbstractEmailTest
attachment.setPath(testFile.getAbsolutePath());
this.email.attach(attachment);
- //this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
+ // this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
this.email.setCharset(EmailConstants.ISO_8859_1);
this.email.setSubject(strSubject);
@@ -328,47 +281,24 @@ public class HtmlEmailTest extends AbstractEmailTest
final URL url = new URL(EmailConfiguration.TEST_URL);
final String cid = this.email.embed(url, "Apache Logo");
- final String strHtmlMsg =
- "<html>The Apache logo - <img src=\"cid:" + cid + "\"><html>";
+ final String strHtmlMsg = "<html>The Apache logo - <img src=\"cid:" + cid + "\"><html>";
this.email.setHtmlMsg(strHtmlMsg);
- this.email.setTextMsg(
- "Your email client does not support HTML emails");
+ this.email.setTextMsg("Your email client does not support HTML emails");
this.email.send();
this.fakeMailServer.stop();
// validate txt message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
// validate html message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getHtmlMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
// validate attachment
- validateSend(
- this.fakeMailServer,
- strSubject,
- attachment.getName(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, attachment.getName(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
this.getMailServer();
@@ -378,11 +308,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.setFrom(this.strTestMailFrom);
this.email.addTo(this.strTestMailTo);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
strSubject = "Test HTML Send #1 Subject (wo charset)";
@@ -392,20 +319,12 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.send();
this.fakeMailServer.stop();
// validate txt message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
}
@Test
- public void testSend2() throws Exception
- {
+ public void testSend2() throws Exception {
// ====================================================================
// Test Success
// ====================================================================
@@ -418,11 +337,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.setFrom(this.strTestMailFrom);
this.email.addTo(this.strTestMailTo);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
String strSubject = "Test HTML Send #2 Subject (wo charset)";
@@ -432,26 +348,12 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.send();
this.fakeMailServer.stop();
// validate txt message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
// validate html message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getHtmlMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
this.getMailServer();
@@ -461,11 +363,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.setSmtpPort(this.getMailServerPort());
this.email.addTo(this.strTestMailTo);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
strSubject = "Test HTML Send #2 Subject (w charset)";
@@ -476,33 +375,18 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.send();
this.fakeMailServer.stop();
// validate txt message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
// validate html message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getHtmlMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
}
@Test
@Ignore
- public void testSendWithDefaultCharset() throws Exception
- {
+ public void testSendWithDefaultCharset() throws Exception {
// Test is disabled as its result is dependent on the execution order:
// the mail.mime.charset property is normally cached by the MimeUtility
// class, thus setting it to another value while running the tests
@@ -522,11 +406,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.setFrom(this.strTestMailFrom);
this.email.addTo(this.strTestMailTo);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
final String strSubject = "Test HTML Send Subject (w default charset)";
@@ -536,34 +417,22 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.send();
this.fakeMailServer.stop();
// validate charset
- validateSend(
- this.fakeMailServer,
- strSubject,
- "charset=iso-8859-15",
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, "charset=iso-8859-15", this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
System.clearProperty(EmailConstants.MAIL_MIME_CHARSET);
}
/**
- * Create a HTML email containing an URL pointing to a ZIP file
- * to be downloaded. According to EMAIL-93 the resulting URL
- * "http://paradisedelivery.homeip.net/delivery/?file=TZC268X93337..zip"
- * contains TWO dots instead of one dot which breaks the link.
+ * Create a HTML email containing an URL pointing to a ZIP file to be downloaded. According to EMAIL-93 the resulting URL
+ * "http://paradisedelivery.homeip.net/delivery/?file=TZC268X93337..zip" contains TWO dots instead of one dot which breaks the link.
*/
@Test
- public void testAddZipUrl() throws Exception
- {
- final String htmlMsg =
- "Please click on the following link: <br><br>" +
- "<a href=\"http://paradisedelivery.homeip.net/delivery/?file=3DTZC268X93337.zip\">" +
- "http://paradisedelivery.homeip.net/delivery/?file=3DTZC268X93337.zip" +
- "</a><br><br>Customer satisfaction is very important for us.";
+ public void testAddZipUrl() throws Exception {
+ final String htmlMsg = "Please click on the following link: <br><br>"
+ + "<a href=\"http://paradisedelivery.homeip.net/delivery/?file=3DTZC268X93337.zip\">"
+ + "http://paradisedelivery.homeip.net/delivery/?file=3DTZC268X93337.zip" + "</a><br><br>Customer satisfaction is very important for us.";
this.getMailServer();
@@ -574,11 +443,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.addTo(this.strTestMailTo);
this.email.setCharset(EmailConstants.ISO_8859_1);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
final String strSubject = "A dot (\".\") is appended to some ULRs of a HTML mail.";
@@ -589,15 +455,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.fakeMailServer.stop();
// validate html message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getHtmlMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
// make sure that no double dots show up
assertTrue(this.email.getHtmlMsg().contains("3DTZC268X93337.zip"));
@@ -605,9 +464,7 @@ public class HtmlEmailTest extends AbstractEmailTest
}
/**
- * According to EMAIL-95 calling buildMimeMessage() before calling send()
- * causes duplicate mime parts - now we throw an exception to catch the
- * problem
+ * According to EMAIL-95 calling buildMimeMessage() before calling send() causes duplicate mime parts - now we throw an exception to catch the problem
*/
@Test
public void testCallingBuildMimeMessageBeforeSent() throws Exception {
@@ -621,11 +478,8 @@ public class HtmlEmailTest extends AbstractEmailTest
this.email.addTo(this.strTestMailTo);
this.email.setCharset(EmailConstants.ISO_8859_1);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
final String strSubject = "testCallingBuildMimeMessageBeforeSent";
@@ -635,12 +489,9 @@ public class HtmlEmailTest extends AbstractEmailTest
// this should NOT be called when sending a message
this.email.buildMimeMessage();
- try
- {
+ try {
this.email.send();
- }
- catch (final IllegalStateException e)
- {
+ } catch (final IllegalStateException e) {
return;
}
@@ -648,12 +499,13 @@ public class HtmlEmailTest extends AbstractEmailTest
}
/**
- * EMAIL-73 - check that providing a plain text content using setMsg()
- * creates a plain content and HTML content using {@code <pre>} tags.
+ * EMAIL-73 - check that providing a plain text content using setMsg() creates a plain content and HTML content using {@code
+ *
+ * <pre>
+ * } tags.
*/
@Test
- public void testSendWithPlainTextButNoHtmlContent() throws EmailException, IOException
- {
+ public void testSendWithPlainTextButNoHtmlContent() throws EmailException, IOException {
this.getMailServer();
final String strSubject = "testSendWithPlainTextButNoHtmlContent";
@@ -673,53 +525,42 @@ public class HtmlEmailTest extends AbstractEmailTest
this.fakeMailServer.stop();
// validate text message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
}
/**
- * Test that the specified Content-ID is used when embedding a File
- * object in an HtmlEmail.
+ * Test that the specified Content-ID is used when embedding a File object in an HtmlEmail.
*
- * Rolled back the changes since they broke real emails therefore
- * the test is currently disabled.
+ * Rolled back the changes since they broke real emails therefore the test is currently disabled.
*
* see https://issues.apache.org/jira/browse/EMAIL-101
*/
@Test
- public void testEmbedFileWithCID() throws Exception
- {
- // ====================================================================
- // Test Success
- // ====================================================================
-
- final File file = File.createTempFile("testEmbedFile", "txt");
- file.deleteOnExit();
-
- final String testCid = "Test CID";
- final String encodedCid = EmailUtils.encodeUrl(testCid);
-
- // if we embed a new file, do we get the content ID we specified back?
- final String strEmbed = this.email.embed(file, testCid);
- assertNotNull(strEmbed);
- assertEquals("didn't get same CID when embedding with a specified CID", encodedCid, strEmbed);
-
- // if we embed the same file again, do we get the same content ID
- // back?
- final String returnedCid = this.email.embed(file);
- assertEquals("didn't get same CID after embedding same file twice", encodedCid, returnedCid);
+ public void testEmbedFileWithCID() throws Exception {
+ // ====================================================================
+ // Test Success
+ // ====================================================================
+
+ final File file = File.createTempFile("testEmbedFile", "txt");
+ file.deleteOnExit();
+
+ final String testCid = "Test CID";
+ final String encodedCid = EmailUtils.encodeUrl(testCid);
+
+ // if we embed a new file, do we get the content ID we specified back?
+ final String strEmbed = this.email.embed(file, testCid);
+ assertNotNull(strEmbed);
+ assertEquals("didn't get same CID when embedding with a specified CID", encodedCid, strEmbed);
+
+ // if we embed the same file again, do we get the same content ID
+ // back?
+ final String returnedCid = this.email.embed(file);
+ assertEquals("didn't get same CID after embedding same file twice", encodedCid, returnedCid);
}
@Test
- public void testHtmlMailMimeLayout() throws Exception
- {
+ public void testHtmlMailMimeLayout() throws Exception {
assertCorrectContentType("contentTypeTest.gif", "image/gif");
assertCorrectContentType("contentTypeTest.jpg", "image/jpeg");
assertCorrectContentType("contentTypeTest.png", "image/png");
diff --git a/src/test/java/org/apache/commons/mail/ImageHtmlEmailTest.java b/src/test/java/org/apache/commons/mail/ImageHtmlEmailTest.java
index 4a2e985..b24a683 100644
--- a/src/test/java/org/apache/commons/mail/ImageHtmlEmailTest.java
+++ b/src/test/java/org/apache/commons/mail/ImageHtmlEmailTest.java
@@ -152,18 +152,15 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
email.setDataSourceResolver(new DataSourceUrlResolver(TEST_IMAGE_DIR.toURI().toURL(), TEST_IS_LENIENT));
// set the html message
- email.setHtmlMsg(
- "<html><body><img src=\"http://www.apache.org/images/feather.gif\"/></body></html>"
- );
+ email.setHtmlMsg("<html><body><img src=\"http://www.apache.org/images/feather.gif\"/></body></html>");
// send the email
email.send();
fakeMailServer.stop();
// validate txt message
- validateSend(fakeMailServer, strSubject, email.getHtmlMsg(),
- email.getFromAddress(), email.getToAddresses(),
- email.getCcAddresses(), email.getBccAddresses(), true);
+ validateSend(fakeMailServer, strSubject, email.getHtmlMsg(), email.getFromAddress(), email.getToAddresses(), email.getCcAddresses(),
+ email.getBccAddresses(), true);
}
@Test
@@ -185,22 +182,18 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
email.setDataSourceResolver(new DataSourceUrlResolver(TEST_IMAGE_DIR.toURI().toURL(), TEST_IS_LENIENT));
final File file = File.createTempFile("emailtest", ".tst");
- FileUtils.writeStringToFile(file,
- "just some silly data that we won't be able to display anyway");
+ FileUtils.writeStringToFile(file, "just some silly data that we won't be able to display anyway");
// set the html message
- email.setHtmlMsg("<html><body><img src=\"" + file.getAbsolutePath()
- + "\"/></body></html>"
- );
+ email.setHtmlMsg("<html><body><img src=\"" + file.getAbsolutePath() + "\"/></body></html>");
// send the email
email.send();
fakeMailServer.stop();
// validate txt message
- validateSend(fakeMailServer, strSubject, email.getHtmlMsg(),
- email.getFromAddress(), email.getToAddresses(),
- email.getCcAddresses(), email.getBccAddresses(), true);
+ validateSend(fakeMailServer, strSubject, email.getHtmlMsg(), email.getFromAddress(), email.getToAddresses(), email.getCcAddresses(),
+ email.getBccAddresses(), true);
}
@Test
@@ -274,8 +267,7 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
assertEquals(1, fakeMailServer.getMessages().size());
final MimeMessage mimeMessage = fakeMailServer.getMessages().get(0).getMimeMessage();
- MimeMessageUtils.writeMimeMessage(mimeMessage,
- new File("./target/test-emails/testSendClassPathFileWithNullName.eml"));
+ MimeMessageUtils.writeMimeMessage(mimeMessage, new File("./target/test-emails/testSendClassPathFileWithNullName.eml"));
final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();
assertTrue(mimeMessageParser.getHtmlContent().contains("\"cid:"));
@@ -344,9 +336,8 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
email.addTo(strTestMailTo);
email.setSubject(strSubject);
- final String html = "<p>First image <img src=\"images/contentTypeTest.gif\"/></p>" +
- "<p>Second image <img src=\"images/contentTypeTest.jpg\"/></p>" +
- "<p>Third image <img src=\"images/contentTypeTest.png\"/></p>";
+ final String html = "<p>First image <img src=\"images/contentTypeTest.gif\"/></p>" + "<p>Second image <img src=\"images/contentTypeTest.jpg\"/></p>"
+ + "<p>Third image <img src=\"images/contentTypeTest.png\"/></p>";
// set the html message
email.setHtmlMsg(html);
@@ -373,61 +364,57 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
final Pattern pattern = Pattern.compile(ImageHtmlEmail.REGEX_IMG_SRC);
// ensure that the regex that we use is catching the cases correctly
- Matcher matcher = pattern
- .matcher("<html><body><img src=\"h\"/></body></html>");
+ Matcher matcher = pattern.matcher("<html><body><img src=\"h\"/></body></html>");
assertTrue(matcher.find());
assertEquals("h", matcher.group(2));
- matcher = pattern
- .matcher("<html><body><img id=\"laskdasdkj\" src=\"h\"/></body></html>");
+ matcher = pattern.matcher("<html><body><img id=\"laskdasdkj\" src=\"h\"/></body></html>");
assertTrue(matcher.find());
assertEquals("h", matcher.group(2));
// uppercase
- matcher = pattern
- .matcher("<html><body><IMG id=\"laskdasdkj\" SRC=\"h\"/></body></html>");
+ matcher = pattern.matcher("<html><body><IMG id=\"laskdasdkj\" SRC=\"h\"/></body></html>");
assertTrue(matcher.find());
assertEquals("h", matcher.group(2));
// matches twice
- matcher = pattern
- .matcher("<html><body><img id=\"laskdasdkj\" src=\"http://dstadler1.org/\"/><img id=\"laskdasdkj\" src=\"http://dstadler2.org/\"/></body></html>");
+ matcher = pattern.matcher(
+ "<html><body><img id=\"laskdasdkj\" src=\"http://dstadler1.org/\"/><img id=\"laskdasdkj\" src=\"http://dstadler2.org/\"/></body></html>");
assertTrue(matcher.find());
assertEquals("http://dstadler1.org/", matcher.group(2));
assertTrue(matcher.find());
assertEquals("http://dstadler2.org/", matcher.group(2));
// what about newlines
- matcher = pattern
- .matcher("<html><body><img\n \rid=\"laskdasdkj\"\n \rsrc=\"http://dstadler1.org/\"/><img id=\"laskdasdkj\" src=\"http://dstadler2.org/\"/></body></html>");
+ matcher = pattern.matcher(
+ "<html><body><img\n \rid=\"laskdasdkj\"\n \rsrc=\"http://dstadler1.org/\"/><img id=\"laskdasdkj\" src=\"http://dstadler2.org/\"/></body></html>");
assertTrue(matcher.find());
assertEquals("http://dstadler1.org/", matcher.group(2));
assertTrue(matcher.find());
assertEquals("http://dstadler2.org/", matcher.group(2));
// what about newlines and other whitespaces
- matcher = pattern
- .matcher("<html><body><img\n \t\rid=\"laskdasdkj\"\n \rsrc \n =\r \"http://dstadler1.org/\"/><img \r id=\" laskdasdkj\" src = \"http://dstadler2.org/\"/></body></html>");
+ matcher = pattern.matcher(
+ "<html><body><img\n \t\rid=\"laskdasdkj\"\n \rsrc \n =\r \"http://dstadler1.org/\"/><img \r id=\" laskdasdkj\" src = \"http://dstadler2.org/\"/></body></html>");
assertTrue(matcher.find());
assertEquals("http://dstadler1.org/", matcher.group(2));
assertTrue(matcher.find());
assertEquals("http://dstadler2.org/", matcher.group(2));
// what about some real markup
- matcher = pattern.matcher("<img alt=\"Chart?ck=xradar&w=120&h=120&c=7fff00|7fff00&m=4&g=0\" src=\"/chart?ck=xradar&w=120&h=120&c=7fff00|7fff00&m=4&g=0.2&l=A,C,S,T&v=3.0,3.0,2.0,2.0\"");
+ matcher = pattern.matcher(
+ "<img alt=\"Chart?ck=xradar&w=120&h=120&c=7fff00|7fff00&m=4&g=0\" src=\"/chart?ck=xradar&w=120&h=120&c=7fff00|7fff00&m=4&g=0.2&l=A,C,S,T&v=3.0,3.0,2.0,2.0\"");
assertTrue(matcher.find());
assertEquals("/chart?ck=xradar&w=120&h=120&c=7fff00|7fff00&m=4&g=0.2&l=A,C,S,T&v=3.0,3.0,2.0,2.0", matcher.group(2));
// had a problem with multiple img-source tags
- matcher = pattern
- .matcher("<img src=\"file1\"/><img src=\"file2\"/>");
+ matcher = pattern.matcher("<img src=\"file1\"/><img src=\"file2\"/>");
assertTrue(matcher.find());
assertEquals("file1", matcher.group(2));
assertTrue(matcher.find());
assertEquals("file2", matcher.group(2));
- matcher = pattern
- .matcher("<img src=\"file1\"/><img src=\"file2\"/><img src=\"file3\"/><img src=\"file4\"/><img src=\"file5\"/>");
+ matcher = pattern.matcher("<img src=\"file1\"/><img src=\"file2\"/><img src=\"file3\"/><img src=\"file4\"/><img src=\"file5\"/>");
assertTrue(matcher.find());
assertEquals("file1", matcher.group(2));
assertTrue(matcher.find());
@@ -472,9 +459,8 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
fakeMailServer.stop();
// validate txt message
- validateSend(fakeMailServer, strSubject, email.getHtmlMsg(),
- email.getFromAddress(), email.getToAddresses(),
- email.getCcAddresses(), email.getBccAddresses(), true);
+ validateSend(fakeMailServer, strSubject, email.getHtmlMsg(), email.getFromAddress(), email.getToAddresses(), email.getCcAddresses(),
+ email.getBccAddresses(), true);
}
private String loadUrlContent(final URL url) throws IOException {
@@ -500,8 +486,7 @@ public class ImageHtmlEmailTest extends HtmlEmailTest {
@Override
public DataSource resolve(final String resourceLocation, final boolean isLenient) throws IOException {
- final javax.mail.util.ByteArrayDataSource ds =
- (javax.mail.util.ByteArrayDataSource) super.resolve(resourceLocation, isLenient);
+ final javax.mail.util.ByteArrayDataSource ds = (javax.mail.util.ByteArrayDataSource) super.resolve(resourceLocation, isLenient);
ds.setName(null);
return ds;
}
diff --git a/src/test/java/org/apache/commons/mail/InvalidAddressTest.java b/src/test/java/org/apache/commons/mail/InvalidAddressTest.java
index 9162965..908fa74 100644
--- a/src/test/java/org/apache/commons/mail/InvalidAddressTest.java
+++ b/src/test/java/org/apache/commons/mail/InvalidAddressTest.java
@@ -27,144 +27,95 @@ import org.junit.Test;
*
* @since 1.0
*/
-public class InvalidAddressTest extends AbstractEmailTest
-{
+public class InvalidAddressTest extends AbstractEmailTest {
/** */
- private static final String [] ARR_INVALID_EMAILS = {
- "local name@domain.com",
- "local(name@domain.com",
- "local)name@domain.com",
- "local<name@domain.com",
- "local>name@domain.com",
- "local,name@domain.com",
- "local;name@domain.com",
- "local:name@domain.com",
- "local[name@domain.com",
- "local]name@domain.com",
- // "local\\name@domain.com", is considered valid for mail-1.4.1
- "local\"name@domain.com",
- "local\tname@domain.com",
- "local\nname@domain.com",
- "local\rname@domain.com",
- "local.name@domain com",
- "local.name@domain(com",
- "local.name@domain)com",
- "local.name@domain<com",
- "local.name@domain>com",
- "local.name@domain,com",
- "local.name@domain;com",
- "local.name@domain:com",
+ private static final String[] ARR_INVALID_EMAILS = { "local name@domain.com", "local(name@domain.com", "local)name@domain.com", "local<name@domain.com",
+ "local>name@domain.com", "local,name@domain.com", "local;name@domain.com", "local:name@domain.com", "local[name@domain.com",
+ "local]name@domain.com",
+ // "local\\name@domain.com", is considered valid for mail-1.4.1
+ "local\"name@domain.com", "local\tname@domain.com", "local\nname@domain.com", "local\rname@domain.com", "local.name@domain com",
+ "local.name@domain(com", "local.name@domain)com", "local.name@domain<com", "local.name@domain>com", "local.name@domain,com",
+ "local.name@domain;com", "local.name@domain:com",
- // "local.name@domain[com",
- "local.name@domain]com",
- "local.name@domain\\com",
- "local.name@domain\tcom",
- "local.name@domain\ncom",
- "local.name@domain\rcom",
- "local.name@",
- "@domain.com"
- };
+ // "local.name@domain[com",
+ "local.name@domain]com", "local.name@domain\\com", "local.name@domain\tcom", "local.name@domain\ncom", "local.name@domain\rcom", "local.name@",
+ "@domain.com" };
private MockEmailConcrete email;
@Before
- public void setUpInvalidAddressTest()
- {
+ public void setUpInvalidAddressTest() {
// reusable objects to be used across multiple tests
this.email = new MockEmailConcrete();
}
@Test
- public void testSetInvalidFrom()
- throws Exception
- {
+ public void testSetInvalidFrom() throws Exception {
// ====================================================================
// Test setting invalid 'from' addresses
// ====================================================================
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
- try
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
+ try {
// set from
email.setFrom(ARR_INVALID_EMAILS[i]);
// Expected an exception to be thrown
fail("setFrom " + i + " passed: " + ARR_INVALID_EMAILS[i]);
- }
- catch (final EmailException ignore)
- {
+ } catch (final EmailException ignore) {
// Expected Result
}
}
}
@Test
- public void testAddInvalidTo()
- throws Exception
- {
+ public void testAddInvalidTo() throws Exception {
// ====================================================================
// Test adding invalid 'to' addresses
// ====================================================================
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
- try
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
+ try {
// Add To
email.addTo(ARR_INVALID_EMAILS[i], "Joe");
// Expected an exception to be thrown
fail("addTo " + i + " passed: " + ARR_INVALID_EMAILS[i]);
- }
- catch (final EmailException ignore)
- {
+ } catch (final EmailException ignore) {
// Expected Result
}
}
}
@Test
- public void testAddInvalidCc()
- throws Exception
- {
+ public void testAddInvalidCc() throws Exception {
// ====================================================================
// Test adding invalid 'cc' addresses
// ====================================================================
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
- try
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
+ try {
// add cc
email.addCc(ARR_INVALID_EMAILS[i], "Joe");
// Expected an exception to be thrown
fail("addCc " + i + " passed: " + ARR_INVALID_EMAILS[i]);
- }
- catch (final EmailException ignore)
- {
+ } catch (final EmailException ignore) {
// Expected Result
}
}
}
@Test
- public void testAddInvalidBcc()
- throws Exception
- {
+ public void testAddInvalidBcc() throws Exception {
// ====================================================================
// Test adding invalid 'Bcc' addresses
// ====================================================================
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
- try
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
+ try {
// add bcc
email.addBcc(ARR_INVALID_EMAILS[i], "Joe");
// Expected an exception to be thrown
fail("addBcc " + i + " passed: " + ARR_INVALID_EMAILS[i]);
- }
- catch (final EmailException ignore)
- {
+ } catch (final EmailException ignore) {
// Expected Result
}
}
diff --git a/src/test/java/org/apache/commons/mail/InvalidInternetAddressTest.java b/src/test/java/org/apache/commons/mail/InvalidInternetAddressTest.java
index b738e7d..702e7d6 100644
--- a/src/test/java/org/apache/commons/mail/InvalidInternetAddressTest.java
+++ b/src/test/java/org/apache/commons/mail/InvalidInternetAddressTest.java
@@ -32,8 +32,7 @@ import org.junit.Test;
*
* @since 1.0
*/
-public class InvalidInternetAddressTest extends AbstractEmailTest
-{
+public class InvalidInternetAddressTest extends AbstractEmailTest {
/** */
private static final String VALID_QUOTED_EMAIL = "\"John O'Groats\"@domain.com";
@@ -41,102 +40,65 @@ public class InvalidInternetAddressTest extends AbstractEmailTest
private static Method validateMethod;
/** */
- private static final String[] ARR_INVALID_EMAILS =
- {
- "local name@domain.com",
- "local(name@domain.com",
- "local)name@domain.com",
- "local<name@domain.com",
- "local>name@domain.com",
- "local,name@domain.com",
- "local;name@domain.com",
- "local:name@domain.com",
- "local[name@domain.com",
+ private static final String[] ARR_INVALID_EMAILS = { "local name@domain.com", "local(name@domain.com", "local)name@domain.com", "local<name@domain.com",
+ "local>name@domain.com", "local,name@domain.com", "local;name@domain.com", "local:name@domain.com", "local[name@domain.com",
"local]name@domain.com",
// "local\\name@domain.com", -- works for javamail-1.4.4
// "local\"name@domain.com", -- works for javamail-1.4.4
- "local\tname@domain.com",
- "local\nname@domain.com",
- "local\rname@domain.com",
- "local.name@domain com",
- "local.name@domain(com",
- "local.name@domain)com",
- "local.name@domain<com",
- "local.name@domain>com",
- "local.name@domain,com",
- "local.name@domain;com",
+ "local\tname@domain.com", "local\nname@domain.com", "local\rname@domain.com", "local.name@domain com", "local.name@domain(com",
+ "local.name@domain)com", "local.name@domain<com", "local.name@domain>com", "local.name@domain,com", "local.name@domain;com",
"local.name@domain:com",
// "local.name@domain[com", -- works for javamail-1.5.5
- "local.name@domain]com",
- "local.name@domain\\com",
- "local.name@domain\tcom",
- "local.name@domain\ncom",
- "local.name@domain\rcom",
- "local.name@",
+ "local.name@domain]com", "local.name@domain\\com", "local.name@domain\tcom", "local.name@domain\ncom", "local.name@domain\rcom", "local.name@",
"@domain.com" };
/**
* Setup for a test
*/
@Before
- public void setUpInvalidInternetAddressTest()
- {
- try
- {
+ public void setUpInvalidInternetAddressTest() {
+ try {
validateMethod = InternetAddress.class.getMethod("validate");
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
assertEquals("Got wrong Exception when looking for validate()", NoSuchMethodException.class, e.getClass());
}
}
@Test
- public void testStrictConstructor() throws Exception
- {
+ public void testStrictConstructor() throws Exception {
// ====================================================================
// Prove InternetAddress constructor is throwing exception.
// ====================================================================
// test Invalid Email addresses
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
- try
- {
+ try {
// Create Internet Address using "strict" constructor
new InternetAddress(ARR_INVALID_EMAILS[i]);
// Expected an exception to be thrown
fail("Strict " + i + " passed: " + ARR_INVALID_EMAILS[i]);
- }
- catch (final Exception ex)
- {
+ } catch (final Exception ex) {
// Expected Result
}
}
// test valid 'quoted' Email addresses
- try
- {
+ try {
// Create Internet Address using "strict" constructor
new InternetAddress(VALID_QUOTED_EMAIL);
- }
- catch (final Exception ex)
- {
- fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL
- + " - " + ex.getMessage());
+ } catch (final Exception ex) {
+ fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL + " - " + ex.getMessage());
}
}
@Test
- public void testValidateMethod() throws Exception
- {
- if (validateMethod == null)
- {
+ public void testValidateMethod() throws Exception {
+ if (validateMethod == null) {
return;
}
@@ -145,52 +107,38 @@ public class InvalidInternetAddressTest extends AbstractEmailTest
// the validate() method is
// ====================================================================
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
final InternetAddress address = new InternetAddress(ARR_INVALID_EMAILS[i], "Joe");
// N.B. validate() doesn't check addresses containing quotes or '['
final boolean quoted = ARR_INVALID_EMAILS[i].contains("\"");
- final int atIndex = ARR_INVALID_EMAILS[i].indexOf("@");
- final boolean domainBracket = atIndex >= 0
- && ARR_INVALID_EMAILS[i].indexOf("[", atIndex) >= 0;
- try
- {
+ final int atIndex = ARR_INVALID_EMAILS[i].indexOf("@");
+ final boolean domainBracket = atIndex >= 0 && ARR_INVALID_EMAILS[i].indexOf("[", atIndex) >= 0;
+ try {
validateMethod.invoke(address, (Object[]) null);
- if (!(quoted || domainBracket))
- {
+ if (!(quoted || domainBracket)) {
fail("Validate " + i + " passed: " + ARR_INVALID_EMAILS[i]);
}
- }
- catch (final Exception ex)
- {
- if (quoted || domainBracket)
- {
- fail("Validate " + i + " failed: " + ARR_INVALID_EMAILS[i]
- + " - " + ex.getMessage());
+ } catch (final Exception ex) {
+ if (quoted || domainBracket) {
+ fail("Validate " + i + " failed: " + ARR_INVALID_EMAILS[i] + " - " + ex.getMessage());
}
}
}
// test valid 'quoted' Email addresses
- try
- {
+ try {
validateMethod.invoke(new InternetAddress(VALID_QUOTED_EMAIL, "Joe"), (Object[]) null);
- }
- catch (final Exception ex)
- {
- fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL
- + " - " + ex.getMessage());
+ } catch (final Exception ex) {
+ fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL + " - " + ex.getMessage());
}
}
@Test
- public void testValidateMethodCharset() throws Exception
- {
- if (validateMethod == null)
- {
+ public void testValidateMethodCharset() throws Exception {
+ if (validateMethod == null) {
return;
}
@@ -199,46 +147,34 @@ public class InvalidInternetAddressTest extends AbstractEmailTest
// the validate() method is
// ====================================================================
- for (int i = 0; i < ARR_INVALID_EMAILS.length; i++)
- {
+ for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) {
final InternetAddress address = new InternetAddress(ARR_INVALID_EMAILS[i], "Joe", StandardCharsets.UTF_8.name());
// N.B. validate() doesn't check addresses containing quotes or '['
final boolean quoted = ARR_INVALID_EMAILS[i].contains("\"");
- final int atIndex = ARR_INVALID_EMAILS[i].indexOf("@");
- final boolean domainBracket = atIndex >= 0
- && ARR_INVALID_EMAILS[i].indexOf("[", atIndex) >= 0;
+ final int atIndex = ARR_INVALID_EMAILS[i].indexOf("@");
+ final boolean domainBracket = atIndex >= 0 && ARR_INVALID_EMAILS[i].indexOf("[", atIndex) >= 0;
- try
- {
+ try {
validateMethod.invoke(address, (Object[]) null);
- if (!(quoted || domainBracket))
- {
+ if (!(quoted || domainBracket)) {
fail("Validate " + i + " passed: " + ARR_INVALID_EMAILS[i]);
}
- }
- catch (final Exception ex)
- {
- if (quoted || domainBracket)
- {
- fail("Validate " + i + " failed: " + ARR_INVALID_EMAILS[i]
- + " - " + ex.getMessage());
+ } catch (final Exception ex) {
+ if (quoted || domainBracket) {
+ fail("Validate " + i + " failed: " + ARR_INVALID_EMAILS[i] + " - " + ex.getMessage());
}
}
}
// test valid 'quoted' Email addresses
- try
- {
+ try {
validateMethod.invoke(new InternetAddress(VALID_QUOTED_EMAIL, "Joe", StandardCharsets.UTF_8.name()), (Object[]) null);
- }
- catch (final Exception ex)
- {
- fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL
- + " - " + ex.getMessage());
+ } catch (final Exception ex) {
+ fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL + " - " + ex.getMessage());
}
}
diff --git a/src/test/java/org/apache/commons/mail/MultiPartEmailTest.java b/src/test/java/org/apache/commons/mail/MultiPartEmailTest.java
index 612b1fb..2b630cf 100644
--- a/src/test/java/org/apache/commons/mail/MultiPartEmailTest.java
+++ b/src/test/java/org/apache/commons/mail/MultiPartEmailTest.java
@@ -42,40 +42,35 @@ import org.powermock.modules.junit4.PowerMockRunner;
* @since 1.0
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest( { MockMultiPartEmailConcrete.class, URLDataSource.class })
-public class MultiPartEmailTest extends AbstractEmailTest
-{
+@PrepareForTest({ MockMultiPartEmailConcrete.class, URLDataSource.class })
+public class MultiPartEmailTest extends AbstractEmailTest {
/** */
private MockMultiPartEmailConcrete email;
/** File to used to test file attachments (Must be valid) */
private File testFile;
@Before
- public void setUpMultiPartEmailTest() throws Exception
- {
+ public void setUpMultiPartEmailTest() throws Exception {
// reusable objects to be used across multiple tests
this.email = new MockMultiPartEmailConcrete();
testFile = File.createTempFile("testfile", ".txt");
}
@Test
- public void testSetMsg() throws EmailException
- {
+ public void testSetMsg() throws EmailException {
// ====================================================================
// Test Success
// ====================================================================
// without charset set
- for (final String validChar : testCharsValid)
- {
+ for (final String validChar : testCharsValid) {
this.email.setMsg(validChar);
assertEquals(validChar, this.email.getMsg());
}
// with charset set
this.email.setCharset(EmailConstants.US_ASCII);
- for (final String validChar : testCharsValid)
- {
+ for (final String validChar : testCharsValid) {
this.email.setMsg(validChar);
assertEquals(validChar, this.email.getMsg());
}
@@ -83,15 +78,11 @@ public class MultiPartEmailTest extends AbstractEmailTest
// ====================================================================
// Test Exceptions
// ====================================================================
- for (final String invalidChar : testCharsNotValid)
- {
- try
- {
+ for (final String invalidChar : testCharsNotValid) {
+ try {
this.email.setMsg(invalidChar);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
@@ -99,11 +90,10 @@ public class MultiPartEmailTest extends AbstractEmailTest
/**
* @throws EmailException when a bad address or attachment is used
- * @throws IOException when sending fails
+ * @throws IOException when sending fails
*/
@Test
- public void testSend() throws EmailException, IOException
- {
+ public void testSend() throws EmailException, IOException {
// ====================================================================
// Test Success
// ====================================================================
@@ -117,8 +107,7 @@ public class MultiPartEmailTest extends AbstractEmailTest
attachment.setName("Test_Attachment");
attachment.setDescription("Test Attachment Desc");
- final MockMultiPartEmailConcrete testEmail =
- new MockMultiPartEmailConcrete();
+ final MockMultiPartEmailConcrete testEmail = new MockMultiPartEmailConcrete();
testEmail.setHostName(this.strTestMailServer);
testEmail.setSmtpPort(this.getMailServerPort());
testEmail.setFrom(this.strTestMailFrom);
@@ -126,12 +115,8 @@ public class MultiPartEmailTest extends AbstractEmailTest
testEmail.attach(attachment);
testEmail.setSubType("subType");
- if (EmailUtils.isNotEmpty(this.strTestUser)
- && EmailUtils.isNotEmpty(this.strTestPasswd))
- {
- testEmail.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (EmailUtils.isNotEmpty(this.strTestUser) && EmailUtils.isNotEmpty(this.strTestPasswd)) {
+ testEmail.setAuthentication(this.strTestUser, this.strTestPasswd);
}
testEmail.setSubject(strSubject);
@@ -149,46 +134,28 @@ public class MultiPartEmailTest extends AbstractEmailTest
this.fakeMailServer.stop();
// validate message
- validateSend(
- this.fakeMailServer,
- strSubject,
- testEmail.getMsg(),
- testEmail.getFromAddress(),
- testEmail.getToAddresses(),
- testEmail.getCcAddresses(),
- testEmail.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, testEmail.getMsg(), testEmail.getFromAddress(), testEmail.getToAddresses(), testEmail.getCcAddresses(),
+ testEmail.getBccAddresses(), true);
// validate attachment
- validateSend(
- this.fakeMailServer,
- strSubject,
- attachment.getName(),
- testEmail.getFromAddress(),
- testEmail.getToAddresses(),
- testEmail.getCcAddresses(),
- testEmail.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, attachment.getName(), testEmail.getFromAddress(), testEmail.getToAddresses(), testEmail.getCcAddresses(),
+ testEmail.getBccAddresses(), false);
// ====================================================================
// Test Exceptions
// ====================================================================
- try
- {
+ try {
this.getMailServer();
this.email.send();
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
this.fakeMailServer.stop();
}
}
@Test
- public void testAttach() throws Exception
- {
+ public void testAttach() throws Exception {
EmailAttachment attachment;
// ====================================================================
@@ -220,100 +187,74 @@ public class MultiPartEmailTest extends AbstractEmailTest
// Test Exceptions
// ====================================================================
// null attachment
- try
- {
+ try {
this.email.attach((EmailAttachment) null);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
// bad url
attachment = new EmailAttachment();
- try
- {
+ try {
attachment.setURL(createInvalidURL());
this.email.attach(attachment);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
// bad file
attachment = new EmailAttachment();
- try
- {
+ try {
attachment.setPath("");
this.email.attach(attachment);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
/**
* @throws MalformedURLException when a bad attachment URL is used
- * @throws EmailException when a bad address or attachment is used
+ * @throws EmailException when a bad address or attachment is used
*/
@Test
- public void testAttach2() throws MalformedURLException, EmailException
- {
+ public void testAttach2() throws MalformedURLException, EmailException {
// ====================================================================
// Test Success - URL
// ====================================================================
- this.email.attach(
- new URL(this.strTestURL),
- "Test Attachment",
- "Test Attachment Desc");
+ this.email.attach(new URL(this.strTestURL), "Test Attachment", "Test Attachment Desc");
// bad name
- this.email.attach(
- new URL(this.strTestURL),
- null,
- "Test Attachment Desc");
+ this.email.attach(new URL(this.strTestURL), null, "Test Attachment Desc");
}
@Test
- public void testAttach3() throws Exception
- {
+ public void testAttach3() throws Exception {
// ====================================================================
// Test Success - URL
// ====================================================================
- this.email.attach(
- new URLDataSource(new URL(this.strTestURL)),
- "Test Attachment",
- "Test Attachment Desc");
+ this.email.attach(new URLDataSource(new URL(this.strTestURL)), "Test Attachment", "Test Attachment Desc");
// ====================================================================
// Test Exceptions
// ====================================================================
// null datasource
- try
- {
+ try {
final URLDataSource urlDs = null;
this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc");
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
// invalid datasource
- try
- {
+ try {
final URLDataSource urlDs = new URLDataSource(createInvalidURL());
this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc");
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
@@ -323,22 +264,18 @@ public class MultiPartEmailTest extends AbstractEmailTest
// ====================================================================
// EMAIL-120: attaching a FileDataSource may result in a locked file
- // resource on windows systems
+ // resource on windows systems
// ====================================================================
final File tmpFile = File.createTempFile("attachment", ".eml");
- this.email.attach(
- new FileDataSource(tmpFile),
- "Test Attachment",
- "Test Attachment Desc");
+ this.email.attach(new FileDataSource(tmpFile), "Test Attachment", "Test Attachment Desc");
assertTrue(tmpFile.delete());
}
@Test
- public void testAddPart() throws Exception
- {
+ public void testAddPart() throws Exception {
// setup
this.email = new MockMultiPartEmailConcrete();
@@ -349,19 +286,13 @@ public class MultiPartEmailTest extends AbstractEmailTest
this.email.addPart(strMessage, strContentType);
// validate
- assertEquals(
- strContentType,
- this.email.getContainer().getBodyPart(0).getContentType());
- assertEquals(
- strMessage,
- this.email.getContainer().getBodyPart(0).getDataHandler()
- .getContent());
+ assertEquals(strContentType, this.email.getContainer().getBodyPart(0).getContentType());
+ assertEquals(strMessage, this.email.getContainer().getBodyPart(0).getDataHandler().getContent());
}
@Test
- public void testAddPart2() throws Exception
- {
+ public void testAddPart2() throws Exception {
// setup
this.email = new MockMultiPartEmailConcrete();
@@ -371,47 +302,33 @@ public class MultiPartEmailTest extends AbstractEmailTest
this.email.addPart(new MimeMultipart(strSubtype));
// validate
- assertTrue(
- this
- .email
- .getContainer()
- .getBodyPart(0)
- .getDataHandler()
- .getContentType()
- .contains(strSubtype));
+ assertTrue(this.email.getContainer().getBodyPart(0).getDataHandler().getContentType().contains(strSubtype));
}
/** TODO implement test for GetContainer */
@Test
- public void testGetContainer()
- {
+ public void testGetContainer() {
assertTrue(true);
}
/** init called twice should fail */
@Test
- public void testInit()
- {
+ public void testInit() {
// call the init function twice to trigger the IllegalStateException
- try
- {
+ try {
this.email.init();
this.email.init();
fail("Should have thrown an exception");
- }
- catch (final IllegalStateException e)
- {
+ } catch (final IllegalStateException e) {
assertTrue(true);
}
}
/** test get/set sub type */
@Test
- public void testGetSetSubType()
- {
- for (final String validChar : testCharsValid)
- {
+ public void testGetSetSubType() {
+ for (final String validChar : testCharsValid) {
this.email.setSubType(validChar);
assertEquals(validChar, this.email.getSubType());
}
diff --git a/src/test/java/org/apache/commons/mail/SendWithAttachmentsTest.java b/src/test/java/org/apache/commons/mail/SendWithAttachmentsTest.java
index 17e9be5..814063e 100644
--- a/src/test/java/org/apache/commons/mail/SendWithAttachmentsTest.java
+++ b/src/test/java/org/apache/commons/mail/SendWithAttachmentsTest.java
@@ -32,24 +32,21 @@ import org.junit.Test;
*
* @since 1.0
*/
-public class SendWithAttachmentsTest extends AbstractEmailTest
-{
+public class SendWithAttachmentsTest extends AbstractEmailTest {
private MockHtmlEmailConcrete email;
@Before
- public void setUpSendWithAttachmentsTest()
- {
+ public void setUpSendWithAttachmentsTest() {
// reusable objects to be used across multiple tests
this.email = new MockHtmlEmailConcrete();
}
/**
* @throws EmailException on an email error
- * @throws IOException when sending fails, or a bad URL is used
+ * @throws IOException when sending fails, or a bad URL is used
*/
@Test
- public void testSendNoAttachments() throws EmailException, IOException
- {
+ public void testSendNoAttachments() throws EmailException, IOException {
this.getMailServer();
final String strSubject = "Test HTML Send #1 Subject (w charset)";
@@ -68,46 +65,29 @@ public class SendWithAttachmentsTest extends AbstractEmailTest
final URL url = new URL(EmailConfiguration.TEST_URL);
final String cid = this.email.embed(url, "Apache Logo");
- final String strHtmlMsg =
- "<html>The Apache logo - <img src=\"cid:" + cid + "\"><html>";
+ final String strHtmlMsg = "<html>The Apache logo - <img src=\"cid:" + cid + "\"><html>";
this.email.setHtmlMsg(strHtmlMsg);
- this.email.setTextMsg(
- "Your email client does not support HTML emails");
+ this.email.setTextMsg("Your email client does not support HTML emails");
this.email.send();
this.fakeMailServer.stop();
// validate txt message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
// validate html message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getHtmlMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
}
/**
* @throws EmailException on an email error
- * @throws IOException when sending fails, or a bad URL is used
+ * @throws IOException when sending fails, or a bad URL is used
*/
@Test
- public void testSendWAttachments() throws EmailException, IOException
- {
+ public void testSendWAttachments() throws EmailException, IOException {
final EmailAttachment attachment = new EmailAttachment();
/** File to used to test file attachments (Must be valid) */
@@ -142,43 +122,21 @@ public class SendWithAttachmentsTest extends AbstractEmailTest
final String strHtmlMsg = "<html>Test Message<html>";
this.email.setHtmlMsg(strHtmlMsg);
- this.email.setTextMsg(
- "Your email client does not support HTML emails");
+ this.email.setTextMsg("Your email client does not support HTML emails");
this.email.send();
this.fakeMailServer.stop();
// validate txt message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getTextMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getTextMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
// validate html message
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getHtmlMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
// validate attachment
- validateSend(
- this.fakeMailServer,
- strSubject,
- MimeUtility.encodeText(attachment.getName()),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- false);
+ validateSend(this.fakeMailServer, strSubject, MimeUtility.encodeText(attachment.getName()), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), false);
}
}
diff --git a/src/test/java/org/apache/commons/mail/SimpleEmailTest.java b/src/test/java/org/apache/commons/mail/SimpleEmailTest.java
index 5700606..074156e 100644
--- a/src/test/java/org/apache/commons/mail/SimpleEmailTest.java
+++ b/src/test/java/org/apache/commons/mail/SimpleEmailTest.java
@@ -29,27 +29,24 @@ import org.junit.Test;
/**
* JUnit test case for SimpleEmailTest
+ *
* @since 1.0
*/
-public class SimpleEmailTest extends AbstractEmailTest
-{
+public class SimpleEmailTest extends AbstractEmailTest {
private MockSimpleEmail email;
@Before
- public void setUpSimpleEmailTest()
- {
+ public void setUpSimpleEmailTest() {
// reusable objects to be used across multiple tests
this.email = new MockSimpleEmail();
}
@Test
- public void testGetSetMsg() throws EmailException
- {
+ public void testGetSetMsg() throws EmailException {
// ====================================================================
// Test Success
// ====================================================================
- for (final String validChar : testCharsValid)
- {
+ for (final String validChar : testCharsValid) {
this.email.setMsg(validChar);
assertEquals(validChar, this.email.getMsg());
}
@@ -57,15 +54,11 @@ public class SimpleEmailTest extends AbstractEmailTest
// ====================================================================
// Test Exception
// ====================================================================
- for (final String invalidChar : this.testCharsNotValid)
- {
- try
- {
+ for (final String invalidChar : this.testCharsNotValid) {
+ try {
this.email.setMsg(invalidChar);
fail("Should have thrown an exception");
- }
- catch (final EmailException e)
- {
+ } catch (final EmailException e) {
assertTrue(true);
}
}
@@ -74,12 +67,10 @@ public class SimpleEmailTest extends AbstractEmailTest
/**
* @throws EmailException when a bad address is set.
- * @throws IOException when sending fails
- * TODO Add code to test the popBeforeSmtp() settings
+ * @throws IOException when sending fails TODO Add code to test the popBeforeSmtp() settings
*/
@Test
- public void testSend() throws EmailException, IOException
- {
+ public void testSend() throws EmailException, IOException {
// ====================================================================
// Test Success
// ====================================================================
@@ -91,11 +82,8 @@ public class SimpleEmailTest extends AbstractEmailTest
this.email.setFrom(this.strTestMailFrom);
this.email.addTo(this.strTestMailTo);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
final String strSubject = "Test Msg Subject";
@@ -109,26 +97,16 @@ public class SimpleEmailTest extends AbstractEmailTest
this.email.send();
this.fakeMailServer.stop();
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getMsg(),
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getMsg(), this.email.getFromAddress(), this.email.getToAddresses(),
+ this.email.getCcAddresses(), this.email.getBccAddresses(), true);
}
@Test
@Ignore
- public void testDefaultMimeCharset() throws EmailException, IOException
- {
+ public void testDefaultMimeCharset() throws EmailException, IOException {
/*
- * disabling this test as it is dependent on execution order.
- * MimeUtility.getDefaultMIMECharset does some internal caching and if
- * mail.mime.charset is not defined, reverts to the default Java charset
- * which is basically the system default file encoding.
+ * disabling this test as it is dependent on execution order. MimeUtility.getDefaultMIMECharset does some internal caching and if mail.mime.charset is
+ * not defined, reverts to the default Java charset which is basically the system default file encoding.
*/
System.setProperty(EmailConstants.MAIL_MIME_CHARSET, "utf-8");
@@ -143,11 +121,8 @@ public class SimpleEmailTest extends AbstractEmailTest
this.email.setFrom(this.strTestMailFrom);
this.email.addTo(this.strTestMailTo);
- if (this.strTestUser != null && this.strTestPasswd != null)
- {
- this.email.setAuthentication(
- this.strTestUser,
- this.strTestPasswd);
+ if (this.strTestUser != null && this.strTestPasswd != null) {
+ this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
}
final String strSubject = "Test Msg Subject";
@@ -160,15 +135,8 @@ public class SimpleEmailTest extends AbstractEmailTest
this.fakeMailServer.stop();
- validateSend(
- this.fakeMailServer,
- strSubject,
- this.email.getMsg().substring(0, 13), // only check the start, the ä will be encoded
- this.email.getFromAddress(),
- this.email.getToAddresses(),
- this.email.getCcAddresses(),
- this.email.getBccAddresses(),
- true);
+ validateSend(this.fakeMailServer, strSubject, this.email.getMsg().substring(0, 13), // only check the start, the ä will be encoded
+ this.email.getFromAddress(), this.email.getToAddresses(), this.email.getCcAddresses(), this.email.getBccAddresses(), true);
final String message = getMessageAsString(0);
// check that the charset has been correctly set
diff --git a/src/test/java/org/apache/commons/mail/mocks/MockEmailConcrete.java b/src/test/java/org/apache/commons/mail/mocks/MockEmailConcrete.java
index 63e6fe6..6db7c9f 100644
--- a/src/test/java/org/apache/commons/mail/mocks/MockEmailConcrete.java
+++ b/src/test/java/org/apache/commons/mail/mocks/MockEmailConcrete.java
@@ -25,22 +25,20 @@ import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
/**
- * Concrete Implementation on the Abstract Email Class (used to allow testing only).
- * Supplies getters for methods that normally only have setters.
+ * Concrete Implementation on the Abstract Email Class (used to allow testing only). Supplies getters for methods that normally only have setters.
*
* @since 1.0
*/
-public class MockEmailConcrete extends Email
-{
+public class MockEmailConcrete extends Email {
/**
* Not Implemented, should be implemented in subclasses of Email
+ *
* @param msg The email message
* @return Email msg.
*/
@Override
- public Email setMsg(final String msg)
- {
+ public Email setMsg(final String msg) {
// This abstract method should be tested in the concrete
// implementation classes only.
return null;
@@ -48,51 +46,47 @@ public class MockEmailConcrete extends Email
/**
* Retrieve the current debug setting
+ *
* @return debug
*/
- public boolean isDebug()
- {
... 765 lines suppressed ...