commons-email-1.5-src/README.txt0100664 0001750 0001750 00000003170 13137110666 017574 0ustar00stefanstefan0000000 0000000 Email ----- Getting started: 1) Build the jar file If you have the source distribution you will need to build the jar file using Maven 2. For instructions on downloading and installing Maven see http://maven.apache.org/. To build execute the command 'mvn package'. The jar file will be built in the target directory. 2) Generate the documentation Run the 'mvn site' command. The documentation will be written to the target/site directory. The documentation has some examples of how to use this package as well as a FAQ. 3) Create source and binary distributions Run the 'mvn site assembly:assembly' command. The source and binary distributions are created in the 'target' directory. 4) Use Simply include the jar file built in step #1 in your classpath. Import the classes that you want to use and you are ready to go! commons-email-1.5-src/NOTICE.txt0100664 0001750 0001750 00000000256 13137110665 017621 0ustar00stefanstefan0000000 0000000 Apache Commons Email Copyright 2001-2017 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). commons-email-1.5-src/LICENSE.txt0100664 0001750 0001750 00000026136 13137110665 017727 0ustar00stefanstefan0000000 0000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. commons-email-1.5-src/RELEASE-NOTES.txt0100664 0001750 0001750 00000025330 13137110665 020606 0ustar00stefanstefan0000000 0000000 Commons Email Package Version 1.5 Release Notes INTRODUCTION: ------------- Commons Email aims to provide a API for sending email. It builds on the JavaMail API with the aim of presenting a simplified API which is easy for developers who are not mail experts to use. It is a compact component with a small number of classes. The Commons Email website is the source for the most recent information, downloads, reports, and bug status: http://commons.apache.org/email/ This is a major release which adds some new features and fixes several bugs present in the 1.4.0 release. All current users are encouraged to upgrade. CHANGES FROM 1.4: ----------------- == Compatibility == * Java 6 or later is required. * JavaMail dependency has been upgraded to version 1.5.6, as a consequence, the maven dependency has changed to: com.sun.mail javax.mail 1.5.6 == New Features == * Add Support for International Domain Names. This change requires JDK 1.6+. Issue: EMAIL-160 * Add Email#getHeader(String) and Email#getHeaders() methods. Issue: EMAIL-154. Thanks to Ken Geis, Balachandran Sivakumar == Updates == * Update Oracle JavaMail dependency from 1.5.2 to 1.5.6. Issue: EMAIL-165. * Remove "javax.activation" dependency since it is included in JDK 1.6 Issue: EMAIL-161. == Fixed Bugs == * DataSourceClassPathResolver doesn't close InputStream when resolving resources Issue: EMAIL-167. Thanks to Lucian Burja. CHANGES FROM 1.3.3: ----------------- == Compatibility == * Java 5 or later is required (unchanged since 1.3). * JavaMail dependency has been upgraded to version 1.5.2, as a consequence, the maven dependency has changed to: com.sun.mail javax.mail 1.5.2 == New Features == * Added getter for the bounce address of an email to class Email. Issue: EMAIL-146. Thanks to Alexander Lehmann. * Added support for mapping of content-ids to DataSource in "MimeMessageParser". Issue: EMAIL-141. Thanks to Stephen Kruger. == Updates == * Update Oracle JavaMail dependency from 1.4.5 to 1.5.2. Issue: EMAIL-144. == Fixed Bugs == * "Email" threw an "EmailException" when trying to send the email if neither a from nor bounce address was specified, although a "mail.from" property was set in the mail session. Issue: EMAIL-149. Thanks to Richard DiCroce. * "ImageHtmlEmail" failed to embed attachments if their data source name was null. Issue: EMAIL-151. Thanks to Andreas Kohn. * Html emails did not have the correct content-type set when using the Apache Geronimo JavaMail implementation v1.8.x. Issue: EMAIL-147. Thanks to Can Eskikaya. * An "HtmlEmail" with both, an html and plain text content but no attachments or embedded images will now be created with mimetype "multipart/alternative" instead of "multipart/mixed". Issue: EMAIL-142. Thanks to Marcin Tomiak. CHANGES FROM 1.3.2: ----------------- == Compatibility == * Java 5 or later is required (unchanged since 1.3). == Fixed Bugs == * The filename of an attachment was not properly encoded in case it contained non-ascii characters. Issue: EMAIL-138. Thanks to qed. * MimeMessageParser did not correctly parse MimeMessage objects created by calling HtmlEmail.buildMimeMessage() and HtmlEmail.getMimeMessage(). Issue: EMAIL-137. Thanks to Alex Kogan. * Fix Javadoc 1.8 errors. Issue: EMAIL-136. Thanks to Ville Skyttä. CHANGES FROM 1.3.1: ----------------- == Compatibility == * Java 5 or later is required (unchanged since 1.3). == Fixed Bugs == * Change visibility of DataSourceUrlResourceResolver.createUrl(String) to protected so that sub-classes can override it. Issue: EMAIL-135. Thanks to Andreas Kohn. * Support default mime charset property "mail.mime.charset" when adding text content to instances of either SimpleEmail or HtmlEmail. Issue: EMAIL-104. Thanks to Hiroshi Ikeda. * Added support for sending partial emails in case of invalid addresses. Issue: EMAIL-132. Thanks to Allen Xudong Cheng. * The MimeMessageParser will now correctly parse MIME multi-parts of type "text/plain" and "text/html" with a content disposition header of "attachment". The parts will be added to the list of attachments even if there is no other text or html content. Issue: EMAIL-131. Thanks to Raju Y. * Special characters in the body of an HTML email could lead to an exception when the mime message was built. Issue: EMAIL-127. Thanks to Dominik Stadler. CHANGES FROM 1.3: ----------------- == Compatibility == * Java 5 or later is required (unchanged since 1.3). == Fixed Bugs == * DataSourceClassPathResolver will now correctly set the DataSource name for resolved resources. Additionally, it is now possible to set the name for a ByteArrayDataSource. Issue: EMAIL-125. Thanks to Jean-Marc. * Header values are not folded twice anymore. The actual encoding and folding is now only performed in Email.buildMimeMessage(). Issue: EMAIL-124. Thanks to Stefan Schueffler. CHANGES FROM 1.2: ----------------- == Compatibility == * Java 5 or later is now required. == New Features == * Added new methods addTo(String[]), addCc(String[]) and addBcc(String[]) to Email. Issue: EMAIL-114. Thanks to Gokul Nanthakumar C. * HtmlmageEmail should support class path resources Issue: EMAIL-108. Thanks to Elisabeth Kasimir, Alexander Kasimir. * Added a MultiPartEmail.attach(File) method since attaching a file is a simple and common. * Added MimeMessageParser and MimeMessageUtils. == Fixed Bugs == * Use the provided Content-ID in HtmlEmail#embed(File, String) instead of creating a random one. The used and returned Content-ID will be URL encoded (see RFC 2392). Issue: EMAIL-101. Thanks to Andrew Starodub. * Upgraded source and binary compatibility to JDK 1.5. Additionally the public/protected methods and fields have been properly generified. Issue: EMAIL-122. Thanks to sebb. * Do not set the personal name of an address to the email address unless it is explicitly specified (affects TO, CC, BCC and FROM addresses). Issue: EMAIL-103. Thanks to David Rees. * Removed emulation support for nested exceptions in EmailException. Issue: EMAIL-117. Thanks to sebb. * Prevent external modification of internal array in DataSourceCompositeResolver. Issue: EMAIL-116. Thanks to sebb. * Close temporary input stream in MultiPartEmail#attach(DataSource, String, String) to prevent locking of file resources on windows systems. Issue: EMAIL-120. Thanks to Mike Bell. * The patch actually broke sending emails over a secured connection - disabled the "MAIL_SMTP_SSL_CHECKSERVERIDENTITY" and "MAIL_SMTP_SSL_ENABLE" activation. Tested the functionality using GMail, GMX and Office365 so the code is at least working for a couple of existing SMTP servers. Also added 'sslCheckServerIdentity' including setter and getter. Also added a chapter regarding "Security" to the user manual. Issue: EMAIL-105. Thanks to Siegfried Goeschl. * Maven Site fails with error in Checkstyle configuration. Issue: EMAIL-113. Thanks to Peter Kofler. * DataSourceFileResolverTest fails under IBM JDK 1.4 and 1.6 running on Windows. Issue: EMAIL-112. Thanks to Peter Kofler. * Update the current trunk to be binary compatible with the commons-email-1.2 release. Issue: EMAIL-111. Thanks to Florian Pirchner. * Added unit test to ensure that parsing the broken mime message does not cause an OutOfMemoryException. Issue: EMAIL-110. Thanks to Thomas Pummer. * Added mime.types to META-INF - the definition is actually found in activation.jar but did not work. Issue: EMAIL-107. Thanks to Claus Polanka, Michael Jakl. * STARTTLS can be used even without authenticator. Issue: EMAIL-106. Thanks to Bruno Harbulot. * Clarified the meaning of setTLS() which actually sends a "STARTTLS" command from the client to the SMTP server. Please note that some "protected" variables were renamed which could break existing code. Issue: EMAIL-105. Thanks to Bruno Harbulot. * Fixed HtmlEmail embed toLowerCase bug with Turkish locale. Issue: EMAIL-102. Thanks to Okan Özeren. * Specified Content-ID is now used when embedding a File object in an HtmlEmail. Issue: EMAIL-101. Thanks to Andrew Starodub. * Throwing an IllegalStateException when setting mail session properties for an already created mail session because the settings would be ignored. Please note that this change could potentially break existing (but invalid) code. Issue: EMAIL-96. * Encoding and folding of headers is now done by commons-email. Issue: EMAIL-98. Thanks to Mario Daepp. * The default connection timeout is set to a reasonable default value of 60 seconds. Issue: EMAIL-100. Thanks to David Parks. * Moving the various constants from 'EMail' to 'EmailConstants' * All setters are returning "this" to simplify building an email. Issue: EMAIL-76. Thanks to Yu Kobayashi. * Adding ImageHtmlEmail to create HTML emails with embedded images either downloaded from HTTP or from the local file system. Issue: EMAIL-92. Thanks to Dominik Stadler. * Calling buildMimeMessage() before invoking send() caused duplicated mime parts for HtmlEmail. The implementation now enforces that an email can be only used once and throw an exception when multiple invocations of buildMimeMessage() are detected. Issue: EMAIL-95. * Incorrect SMTP Port number shown in error message when an email fails to send due to a blocked port and SSL is used. Issue: EMAIL-91. Thanks to Kevin Lester. REQUIREMENTS: J2SE environments ----------------- Commons Email requires JavaMail 1.5.2 or later. The reference implementation is available at: https://java.net/projects/javamail/pages/Home However, the Apache Geronimo project (http://geronimo.apache.org) provides a J2EE-certified implementation of the JavaMail 1.4 specification licensed under the Apache Software License. Commons Email also requires the JavaBeans Activation Framework unless you are running on Java SE 6 or later. The Oracle implementation is available at: http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html Apache Geronimo likewise provides an implementation under the Apache Software License. Commons Email has been tested with JDK 1.6 and 1.7. J2EE environments ----------------- Commons Email is compatible with all certified Java Enterprise Edition 5 implementations; no further dependencies are required. Java 2 Enterprise Edition 1.4 users must ensure that the versions of JavaMail and JAF indicated above are available to their applications; the J2EE 1.4 specification only requires earlier versions. Earlier versions of J2EE are not supported.commons-email-1.5-src/pom.xml0100664 0001750 0001750 00000040677 13137111176 017425 0ustar00stefanstefan0000000 0000000 org.apache.commons commons-parent 40 4.0.0 org.apache.commons commons-email 1.5 Apache Commons Email 2001 Apache Commons Email aims to provide an API for sending email. It is built on top of the JavaMail API, which it aims to simplify. http://commons.apache.org/proper/commons-email/ jira http://issues.apache.org/jira/browse/EMAIL scm:svn:http://svn.apache.org/repos/asf/commons/proper/email/tags/EMAIL_1_5 scm:svn:https://svn.apache.org/repos/asf/commons/proper/email/trunk http://svn.apache.org/viewvc/commons/proper/email/tags/EMAIL_1_5 dIon Gillard dion dion@apache.org The Apache Software Foundation Java Developer John McNally jmcnally jmcnally@collab.net CollabNet, Inc. Quinton McCombs quintonm quintonm@bellsouth.net NequalsOne, LLC. Eric Pugh epugh epugh@opensourceconnections.com OpenSource Connections Daniel Rall dlr dlr@finemaltcoding.com CollabNet, Inc. Jon Scott Stevens jon jon@latchkey.com CollabNet, Inc. Jason van Zyl jvanzyl jason@zenplex.com Zenplex Joe Germuska germuska Joe@Germuska.com Robert Burrell Donkin rdonkin rdonkin@apache.org Henning P. Schmiedehausen henning hps@intermeta.de INTERMETA - Gesellschaft fuer Mehrwertdienste mbH Java Developer 2 Stephen Colebourne scolebourne 0 Ben Speakmon bspeakmon bspeakmon@apache.org The Apache Software Foundation Java Developer -8 Siegfried Goeschl sgoeschl sgoeschl@apache.org Java Developer 2 Thomas Neidhart tn tn@apache.org The Apache Software Foundation Gary Gregory ggregory ggregory@apache.org http://www.garygregory.com -5 Bindul Bhowmik Colin Chalmers colin.chalmers@maxware.nl Frank Y. Kim frank.kim@clearink.com Regis Koenig Stephen Kruger Sean Legassick sean@informage.net Andrew Liles Cedrik Lime Mark Lowe mark.lowe@boxstuff.com Brett McLaughlin bmclaugh@algx.net Piero Ottuzzi Niall Pemberton Greg Ritter greg@shwoop.com Corey Scott corey.scott@gmail.com Eric Spiegelberg eric@spiegs.com Dominik Stadler Matthias Wessendorf matthias@wessendorf.net Brandon Wolfe com.sun.mail javax.mail 1.5.6 junit junit 4.12 test org.slf4j slf4j-jdk14 1.7.7 test commons-io commons-io 2.5 test org.subethamail subethasmtp 3.1.7 test javax.mail mail org.powermock powermock-module-junit4 ${powermock.version} test org.powermock powermock-api-easymock ${powermock.version} test org.easymock easymock ${easymock.version} test UTF-8 UTF-8 1.6 1.6 email org.apache.commons.mail EMAIL 12310474 1.5 RC1 UTF-8 1.6.5 3.4 2.5.5 org.apache.maven.plugins maven-surefire-plugin org/apache/commons/mail/mocks/* org/apache/commons/mail/settings/* **/Abstract*Test.java maven-assembly-plugin src/assembly/bin.xml src/assembly/src.xml gnu org.apache.maven.plugins maven-jar-plugin true true org.apache.maven.plugins maven-release-plugin forked-path org.apache.maven.plugins maven-scm-publish-plugin javadocs apache.website Apache Website ${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/email/ org.apache.maven.plugins maven-changes-plugin %URL%/%ISSUE% changes-report org.apache.maven.plugins maven-checkstyle-plugin 2.13 ${basedir}/conf/checkstyle.xml false ${basedir}/conf/HEADER.txt org.apache.maven.plugins maven-pmd-plugin 2.7.1 ${maven.compiler.target} org.codehaus.mojo findbugs-maven-plugin ${findbugs.version} Normal Default ${basedir}/conf/findbugs-exclude-filter.xml org.codehaus.mojo clirr-maven-plugin org.apache.rat apache-rat-plugin src/test/resources/eml/*.eml rc apache.website Apache Commons Release Candidate Staging Site ${commons.deployment.protocol}://people.apache.org/www/people.apache.org/builds/commons/${commons.componentid}/${commons.release.version}/${commons.rc.version}/site test_java_8 1.8 3.0.3 commons-email-1.5-src/conf/0040775 0001750 0001750 00000000000 13137110665 017024 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/conf/findbugs-exclude-filter.xml0100664 0001750 0001750 00000003345 13137110665 024263 0ustar00stefanstefan0000000 0000000 commons-email-1.5-src/conf/checkstyle.xml0100664 0001750 0001750 00000015404 13137110665 021705 0ustar00stefanstefan0000000 0000000 commons-email-1.5-src/conf/HEADER.txt0100664 0001750 0001750 00000001442 13137110665 020513 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ commons-email-1.5-src/src/0040775 0001750 0001750 00000000000 13137110665 016666 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/changes/0040775 0001750 0001750 00000000000 13137110666 020277 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/0040775 0001750 0001750 00000000000 13137110665 017612 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/resources/0040775 0001750 0001750 00000000000 13137110665 021624 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/resources/META-INF/0040775 0001750 0001750 00000000000 13137110666 022765 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/0040775 0001750 0001750 00000000000 13137110665 020533 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/org/0040775 0001750 0001750 00000000000 13137110665 021322 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/0040775 0001750 0001750 00000000000 13137110665 022543 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/commons/0040775 0001750 0001750 00000000000 13137110665 024216 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/commons/mail/0040775 0001750 0001750 00000000000 13137110666 025141 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/0040775 0001750 0001750 00000000000 13137110666 027002 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/commons/mail/util/0040775 0001750 0001750 00000000000 13137110666 026116 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/site/0040775 0001750 0001750 00000000000 13137110666 017633 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/site/resources/0040775 0001750 0001750 00000000000 13137110666 021645 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/site/resources/images/0040775 0001750 0001750 00000000000 13137110666 023112 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/site/xdoc/0040775 0001750 0001750 00000000000 13137110666 020570 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/assembly/0040775 0001750 0001750 00000000000 13137110665 020505 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/0040775 0001750 0001750 00000000000 13137110664 017644 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/resources/0040775 0001750 0001750 00000000000 13137110664 021656 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/resources/html/0040775 0001750 0001750 00000000000 13137110665 022623 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/resources/eml/0040775 0001750 0001750 00000000000 13137110665 022434 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/resources/attachments/0040775 0001750 0001750 00000000000 13137110665 024172 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/resources/images/0040775 0001750 0001750 00000000000 13137110665 023124 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/resources/images/logos/0040775 0001750 0001750 00000000000 13137110665 024247 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/0040775 0001750 0001750 00000000000 13137110664 020565 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/0040775 0001750 0001750 00000000000 13137110664 021354 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/0040775 0001750 0001750 00000000000 13137110664 022575 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/0040775 0001750 0001750 00000000000 13137110664 024250 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/0040775 0001750 0001750 00000000000 13137110666 025174 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/settings/0040775 0001750 0001750 00000000000 13137110665 027033 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/0040775 0001750 0001750 00000000000 13137110665 027034 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/util/0040775 0001750 0001750 00000000000 13137110666 026151 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/0040775 0001750 0001750 00000000000 13137110665 026307 5ustar00stefanstefan0000000 0000000 commons-email-1.5-src/src/changes/changes.xml0100664 0001750 0001750 00000056124 13137110666 022436 0ustar00stefanstefan0000000 0000000 Changes Eric Pugh Grammar error in comment MimeMessageUtils.writeMimeMessage writes stacktrace DataSourceClassPathResolver doesn't close InputStream when resolving resources Upgrade to javax.mail-1.5.6 Remove "javax.activation" dependency since it is included in JDK 1.6 and update to javax.mail-1.5.5 Add Support for International Domain Names. This change requires JDK 1.6+. Add Email#getHeader(String) and Email#getHeaders() methods. "Email" threw an "EmailException" when trying to send the email if neither a from nor bounce address was specified, although a "mail.from" property was set in the mail session. "ImageHtmlEmail" failed to embed attachments if their data source name was null. Html emails did not have the correct content-type set when using the Apache Geronimo JavaMail implementation v1.8.x. Added getter for the bounce address of an email to class Email. Update Oracle JavaMail dependency from 1.4.5 to 1.5.2. An "HtmlEmail" with both, an html and plain text content but no attachments or embedded images will now be created with mimetype "multipart/alternative" instead of "multipart/mixed". Added support for mapping of content-ids to DataSource in "MimeMessageParser". Fix test execution errors with Java 8. The filename of an attachment was not properly encoded in case it contained non-ascii characters. MimeMessageParser did not correctly parse MimeMessage objects created by calling HtmlEmail.buildMimeMessage() and HtmlEmail.getMimeMessage(). Fix Javadoc 1.8 errors. Change visibility of DataSourceUrlResourceResolver.createUrl(String) to protected so that sub-classes can override it. Support default mime charset property "mail.mime.charset" when adding text content to instances of either SimpleEmail or HtmlEmail. Added support for sending partial emails in case of invalid addresses. The MimeMessageParser will now correctly parse MIME multi-parts of type "text/plain" and "text/html" with a content disposition header of "attachment". The parts will be added to the list of attachments even if there is no other text or html content. Special characters in the body of an HTML email could lead to an exception when the mime message was built. DataSourceClassPathResolver will now correctly set the DataSource name for resolved resources. Additionally, it is now possible to set the name for a ByteArrayDataSource. Header values are not folded twice anymore. The actual encoding and folding is now only performed in Email.buildMimeMessage(). Use the provided Content-ID in HtmlEmail#embed(File, String) instead of creating a random one. The used and returned Content-ID will be URL encoded (see RFC 2392). Upgraded source and binary compatibility to JDK 1.5. Additionally the public/protected methods and fields have been properly generified. Do not set the personal name of an address to the email address unless it is explicitly specified (affects TO, CC, BCC and FROM addresses). Added new methods addTo(String[]), addCc(String[]) and addBcc(String[]) to Email. Removed emulation support for nested exceptions in EmailException. Prevent external modification of internal array in DataSourceCompositeResolver. Close temporary input stream in MultiPartEmail#attach(DataSource, String, String) to prevent locking of file resources on windows systems. The patch actually broke sending emails over a secured connection - disabled the "MAIL_SMTP_SSL_CHECKSERVERIDENTITY" and "MAIL_SMTP_SSL_ENABLE" activation. Tested the functionality using GMail, GMX and Office365 so the code is at least working for a couple of existing SMTP servers. Also added 'sslCheckServerIdentity' including setter and getter. Also added a chapter regarding "Security" to the user manual. Maven Site fails with error in Checkstyle configuration. DataSourceFileResolverTest fails under IBM JDK 1.4 and 1.6 running on Windows. Update the current trunk to be binary compatible with the commons-email-1.2 release. Added unit test to ensure that parsing the broken mime message does not cause an OutOfMemoryException. ImageHtmlEmail should support class path resources. Added mime.types to META-INF - the definition is actually found in activation.jar but did not work. STARTTLS can be used even without authenticator. Clarified the meaning of setTLS() which actually sends a "STARTTLS" command from the client to the SMTP server. Please note that some "protected" variables were renamed which could break existing code. Fixed HtmlEmail embed toLowerCase bug with Turkish locale. Added a MultiPartEmail.attach(File) method since attaching a file is a simple and common. Specified Content-ID is now used when embedding a File object in an HtmlEmail. Restore Java 1.4 compatibility. Added MimeMessageParser and MimeMessageUtils. Throwing an IllegalStateException when setting mail session properties for an already created mail session because the settings would be ignored. Please note that this change could potentially break existing (but invalid) code. Encoding and folding of headers is now done by commons-email. The default connection timeout is set to a reasonable default value of 60 seconds. Moving the various constants from 'EMail' to 'EmailConstants' All setters are returning "this" to simplify building an email. Adding ImageHtmlEmail to create HTML emails with embedded images either downloaded from HTTP or from the local file system. Calling buildMimeMessage() before invoking send() caused duplicated mime parts for HtmlEmail. The implementation now enforces that an email can be only used once and throw an exception when multiple invocations of buildMimeMessage() are detected. Incorrect SMTP Port number shown in error message when an email fails to send due to a blocked port and SSL is used. Changing groupId from "commons-email" to "org.apache.commons" because the 1.1 release was already using "org.apache.commons" Using "http://example.invalid" for a bad url - ".invalid" is reserved and not intended to be installed as a top-level domain in the global Domain Name System (DNS) of the Internet. Made BaseEmailTestCase abstract and fixed a few coding issues. HtmlEmail invokes java.net.URL.equals(Object), which blocks to do domain name resolution. This is avoided by using "url.toExternalForm().equals()" instead of "url.equals()". Email.setFrom and Email.addTo are using Email.charset to properly encode the name. SimpleEmail#setMsg() with UTF-8 content honors correct charset in header and does encode the content correctly now. Created additional methods to support timeouts. Create an overridable method in Email.java to create the MimeMessage instance. If setHostName() has not been called, getHostName() tries to return this.session.getProperty(MAIL_HOST). If mail session has not been created yet, this will throw a NullPointerException. Now getHostName() checks that this.session is not null before trying to access it. Add getTo and getReplyTo to Email class. Provide better diagnostics when attaching documents fail. When mail authentication is required and no username/password is supplied than the provided mail session is used. If a username/password is found the implementation creates a new mail session and a DefaultAuthenticator as convinence implementation. Using Kenneth's implementation of HtmlEmail.buildMimeMessage() to fix a couple of HtmlEmail layout issues. Also thanks to Martin Lau and Morten Hattesen for providing in-depth analysis of the problem During regression tests write out the generated MimeMessage instead of WiserEmail.toString(). Support embedding of raw DataSource attachments in HtmlEmail. Use wiser instead of dumbster for test cases. Original patch supplied by Bindul Bhowmik. Build patches to enforce source 1.4 and target 1.4 when compiling. Identical Inline images should share same BodyPart. Fixed by EMAIL-50. Problems with HTML emails with attachments and embedded images. Fixed by EMAIL-50. HTML Emails with images don't display in Outlook 2000. Fix from Ben Speakmon. Use JDK1.4 and java.nio.Charset instead of keeping our own. Fix from Ben Speakmon. not support content charset gb2312. Fixed by EMAIL-54. Address char-set can not be individually set. Fixed by EMAIL-54. setCharset() in Email does not set the charset for the message content. Fix provided by Ben Speakmon. Enhance website Added Email.setReplyTo(Collection) If you provide a mailSession in tomcat you cannot send email using commons-email: the problem is mainly caused by typos or missing constant declaration. Added TLS helper methods on Email and Added setMailSessionFromJNDI(String) helper method Added HtmlEmail.embed(String,String) as a wrapper to embed(URL,String) Make sure that the unit tests don't fail under JDK 1.3.x with java.net.BindException: Address already in use Replace our usage of address.validate() with simpler code that allows commons-email to work with javamail 1.2 / J2EE 1.3 environment. Added an unit test which verifies the behaviour. Add an unit test to check for invalid addresses. Remove dependencies to commons-lang, allowing commons-email to exist without any external dependencies in an J2EE 1.4+ environment. Improve MultiPartEmail to ease extending it. Refactoring the code to seperate creation of a MimeMessage and sending it. Add serialVersionUID to EmailException Use Dumbster 1.6 compiled with jdk13 for testing Refactor Hashtable usage to Map Email throws EmailException wrapping underlying JavaMail exception Change port for dumbster from 25 to 2500 to use unreserved port. Add back in ByteArrayDataSource. Removed deprecated MailMessage and ByteArrayDataSource. Output test emails to /target/test-emails as .txt files for manual review. Inline attatchment encoding was incorrect. Integrate our own checkstyle config instead of using Turbine style only. Clone the System.getProperties() call instead of putting random properties into it. Can't supply a javax.mail.Session to Commons Email component HTML email with plain text alternative and attachments Integrate use of Dumbster to supply a fake SMTP server. Lots of new unit tests and cleanup of code. Update dependencies to latest available. Support the delivery of bounced messages to an address other than "from". commons-email-1.5-src/src/main/resources/META-INF/mime.types0100664 0001750 0001750 00000001456 13137110666 025005 0ustar00stefanstefan0000000 0000000 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. image/png png PNG commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceUrlResolver.java0100664 0001750 0001750 00000007612 13137110666 034107 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import javax.activation.DataSource; import javax.activation.URLDataSource; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; /** * Creates a DataSource based on an URL. * * @since 1.3 */ public class DataSourceUrlResolver extends DataSourceBaseResolver { /** the base url of the resource when resolving relative paths */ private final URL baseUrl; /** * Constructor. * * @param baseUrl the base URL used for resolving relative resource locations */ public DataSourceUrlResolver(final URL baseUrl) { super(); this.baseUrl = baseUrl; } /** * Constructor. * * @param baseUrl the base URL used for resolving relative resource locations * @param lenient shall we ignore resources not found or complain with an exception */ public DataSourceUrlResolver(final URL baseUrl, final boolean lenient) { super(lenient); this.baseUrl = baseUrl; } /** * Get the base URL used for resolving relative resource locations. * * @return the baseUrl */ public URL getBaseUrl() { return baseUrl; } /** {@inheritDoc} */ @Override 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 { DataSource result = null; try { if (!isCid(resourceLocation)) { final URL url = createUrl(resourceLocation); result = new URLDataSource(url); result.getInputStream(); } return result; } catch (final IOException e) { if (isLenient) { return null; } throw e; } } /** * 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 { // if we get an non-existing base url than the resource can // be directly used to create an URL if (baseUrl == null) { return new URL(resourceLocation); } // if we get an non-existing location what we shall do? if (resourceLocation == null || resourceLocation.length() == 0) { throw new IllegalArgumentException("No resource defined"); } // if we get a stand-alone resource than ignore the base url if (isFileUrl(resourceLocation) || isHttpUrl(resourceLocation)) { return new URL(resourceLocation); } return new URL(getBaseUrl(), resourceLocation.replaceAll("&", "&")); } } ././@LongLink0100644 0000000 0000000 00000000146 13137110666 011640 Lustar 0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceCompositeResolver.javacommons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceCompositeResolver.jav0100664 0001750 0001750 00000007356 13137110666 035153 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import org.apache.commons.mail.DataSourceResolver; 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. * * @since 1.3 */ public class DataSourceCompositeResolver extends DataSourceBaseResolver { /** the list of resolvers */ private final DataSourceResolver[] dataSourceResolvers; /** * Constructor. * * @param dataSourceResolvers a list of of resolvers being used */ public DataSourceCompositeResolver(final DataSourceResolver[] dataSourceResolvers) { this.dataSourceResolvers = new DataSourceResolver[dataSourceResolvers.length]; System.arraycopy(dataSourceResolvers, 0, this.dataSourceResolvers, 0, dataSourceResolvers.length); } /** * Constructor. * * @param dataSourceResolvers a list of of resolvers being used * @param isLenient shall we ignore resources not found or throw an exception? */ public DataSourceCompositeResolver(final DataSourceResolver[] dataSourceResolvers, final boolean isLenient) { super(isLenient); this.dataSourceResolvers = new DataSourceResolver[dataSourceResolvers.length]; System.arraycopy(dataSourceResolvers, 0, this.dataSourceResolvers, 0, dataSourceResolvers.length); } /** * Get the underlying data source resolvers. * * @return underlying data source resolvers */ public DataSourceResolver[] getDataSourceResolvers() { // clone the internal array to prevent external modification (see EMAIL-116) final DataSourceResolver[] resolvers = new DataSourceResolver[dataSourceResolvers.length]; System.arraycopy(dataSourceResolvers, 0, resolvers, 0, dataSourceResolvers.length); return resolvers; } /** {@inheritDoc} */ @Override public DataSource resolve(final String resourceLocation) throws IOException { final DataSource result = resolve(resourceLocation, true); if (isLenient() || result != null) { return result; } throw new IOException("The following resource was not found : " + resourceLocation); } /** {@inheritDoc} */ @Override 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) { return dataSource; } } if (isLenient) { return null; } throw new IOException("The following resource was not found : " + resourceLocation); } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceFileResolver.java0100664 0001750 0001750 00000006241 13137110666 034221 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import javax.activation.DataSource; import javax.activation.FileDataSource; import java.io.File; import java.io.IOException; /** * Creates a DataSource based on an URL. The implementation * also resolves file resources. * * @since 1.3 */ public class DataSourceFileResolver extends DataSourceBaseResolver { /** the base directory of the resource when resolving relative paths */ private final File baseDir; /** * Constructor. */ public DataSourceFileResolver() { baseDir = new File("."); } /** * Constructor. * * @param baseDir the base directory of the resource when resolving relative paths */ public DataSourceFileResolver(final File baseDir) { this.baseDir = baseDir; } /** * Constructor. * * @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) { super(lenient); this.baseDir = baseDir; } /** * Get the base directory used for resolving relative resource locations. * * @return the baseUrl */ public File getBaseDir() { return baseDir; } /** {@inheritDoc} */ @Override 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 { File file; DataSource result = null; if (!isCid(resourceLocation)) { file = new File(resourceLocation); if (!file.isAbsolute()) { file = getBaseDir() != null ? new File(getBaseDir(), resourceLocation) : new File(resourceLocation); } if (file.exists()) { result = new FileDataSource(file); } else { if (!isLenient) { throw new IOException("Cant resolve the following file resource :" + file.getAbsolutePath()); } } } return result; } } ././@LongLink0100644 0000000 0000000 00000000146 13137110666 011640 Lustar 0000000 0000000 commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceClassPathResolver.javacommons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceClassPathResolver.jav0100664 0001750 0001750 00000011002 13137110666 035052 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import javax.activation.DataSource; import javax.activation.FileTypeMap; import javax.mail.util.ByteArrayDataSource; import java.io.IOException; import java.io.InputStream; /** * Creates a DataSource based on an class path. * * @since 1.3 */ public class DataSourceClassPathResolver extends DataSourceBaseResolver { /** the base string of the resource relative to the classpath when resolving relative paths */ private final String classPathBase; /** * Constructor */ public DataSourceClassPathResolver() { this.classPathBase = "/"; } /** * Constructor. * * @param classPathBase a base class path */ public DataSourceClassPathResolver(final String classPathBase) { this.classPathBase = classPathBase.endsWith("/") ? classPathBase : classPathBase + "/"; } /** * Constructor. * * @param classPathBase a base class path * @param lenient shall we ignore resources not found or throw an exception? */ public DataSourceClassPathResolver(final String classPathBase, final boolean lenient) { super(lenient); this.classPathBase = classPathBase.endsWith("/") ? classPathBase : classPathBase + "/"; } /** * @return the classPathBase */ public String getClassPathBase() { return classPathBase; } /** {@inheritDoc} */ @Override 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 { DataSource result = null; try { if (!isCid(resourceLocation) && !isHttpUrl(resourceLocation)) { final String mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(resourceLocation); final String resourceName = getResourceName(resourceLocation); final InputStream is = DataSourceClassPathResolver.class.getResourceAsStream(resourceName); if (is != null) { try { final ByteArrayDataSource ds = new ByteArrayDataSource(is, mimeType); // EMAIL-125: set the name of the DataSource to the normalized resource URL // similar to other DataSource implementations, e.g. FileDataSource, URLDataSource ds.setName(DataSourceClassPathResolver.class.getResource(resourceName).toString()); result = ds; } finally { is.close(); } } else { if (isLenient) { return null; } throw new IOException("The following class path resource was not found : " + resourceLocation); } } return result; } catch (final IOException e) { if (isLenient) { return null; } throw e; } } /** * Returns the resource name for a given resource location. * * @param resourceLocation the resource location * @return {@link #getClassPathBase()} + {@code resourceLocation} * @see #getClassPathBase() */ private String getResourceName(final String resourceLocation) { return (getClassPathBase() + resourceLocation).replaceAll("//", "/"); } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/DataSourceBaseResolver.java0100664 0001750 0001750 00000004663 13137110666 034222 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import org.apache.commons.mail.DataSourceResolver; /** * Base class for various resolvers. * * @since 1.3 */ public abstract class DataSourceBaseResolver implements DataSourceResolver { /** shall we ignore resources not found or complain with an exception */ private final boolean lenient; /** * Constructor. */ public DataSourceBaseResolver() { this.lenient = false; } /** * Constructor. * * @param lenient shall we ignore resources not found or throw an exception? */ public DataSourceBaseResolver(final boolean lenient) { this.lenient = lenient; } /** * Shall we ignore resources not found or throw an exception? * * @return the lenient flag */ public boolean isLenient() { return lenient; } /** * Is this a content id? * * @param resourceLocation the resource location * @return true if it is a CID */ protected boolean isCid(final String resourceLocation) { return resourceLocation.startsWith("cid:"); } /** * Is this a file URL? * * @param urlString the URL string * @return true if it is a file URL */ protected boolean isFileUrl(final String urlString) { return urlString.startsWith("file:/"); } /** * Is this a HTTP/HTTPS URL? * * @param urlString the URL string * @return true if it is a HTTP/HTTPS URL */ protected boolean isHttpUrl(final String urlString) { return urlString.startsWith("http://") || urlString.startsWith("https://"); } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/resolver/package-info.java0100664 0001750 0001750 00000002003 13137110666 032161 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Contains implementation classes to resolve data sources from the following locations: *
    *
  • class path
  • *
  • file system
  • *
  • URL
  • *
*/ package org.apache.commons.mail.resolver; commons-email-1.5-src/src/main/java/org/apache/commons/mail/SimpleEmail.java0100664 0001750 0001750 00000002730 13137110666 030204 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; /** * This class is used to send simple internet email messages without * attachments. * * @since 1.0 */ public class SimpleEmail extends Email { /** * Set the content of the mail. * * @param msg A String. * @return An Email. * @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)) { throw new EmailException("Invalid message supplied"); } setContent(msg, EmailConstants.TEXT_PLAIN); return this; } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/ByteArrayDataSource.java0100664 0001750 0001750 00000014417 13137110666 031665 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.activation.DataSource; /** * This class implements a typed DataSource from:
* * - an InputStream
* - a byte array
* - a String
* *

* 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 { /** Define the buffer size. */ public static final int BUFFER_SIZE = 512; /** Stream containing the Data. */ private ByteArrayOutputStream baos; /** The Content-type. */ 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. * @since 1.3.1 */ private String name = ""; /** * Create a datasource from a byte array. * * @param data A byte[]. * @param aType A String. * @throws IOException IOException * @since 1.0 */ public ByteArrayDataSource(final byte[] data, final String aType) throws IOException { this.type = aType; ByteArrayInputStream bis = null; try { bis = new ByteArrayInputStream(data); this.byteArrayDataSource(bis); } finally { if (bis != null) { bis.close(); } } } /** * Create a datasource from an input stream. * * @param aIs An InputStream. * @param aType A String. * @throws IOException IOException * @since 1.0 */ 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. * * @param data A String. * @param aType A String. * @throws IOException IOException * @since 1.0 */ public ByteArrayDataSource(final String data, final String aType) throws IOException { this.type = aType; try { baos = new ByteArrayOutputStream(); // Assumption that the string contains only ASCII characters! // Else just pass in a charset into this constructor and use it in getBytes(). baos.write(data.getBytes("iso-8859-1")); baos.flush(); baos.close(); } catch (final UnsupportedEncodingException uex) { throw new IOException("The Character Encoding is not supported."); } 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 { BufferedInputStream bis = null; BufferedOutputStream osWriter = null; try { int length = 0; final byte[] buffer = new byte[ByteArrayDataSource.BUFFER_SIZE]; bis = new BufferedInputStream(aIs); baos = new ByteArrayOutputStream(); osWriter = new BufferedOutputStream(baos); // Write the InputData to OutputStream while ((length = bis.read(buffer)) != -1) { osWriter.write(buffer, 0, length); } osWriter.flush(); osWriter.close(); } finally { if (bis != null) { bis.close(); } if (baos != null) { baos.close(); } if (osWriter != null) { osWriter.close(); } } } /** * Get the content type. * * @return A String. * @since 1.0 */ @Override public String getContentType() { return type == null ? "application/octet-stream" : type; } /** * Get the input stream. * * @return An InputStream. * @throws IOException IOException * @since 1.0 */ @Override public InputStream getInputStream() throws IOException { if (baos == null) { throw new IOException("no data"); } return new ByteArrayInputStream(baos.toByteArray()); } /** * Sets the name for this DataSource. * * @param name The name. * @since 1.3.1 */ public void setName(final String name) { this.name = name; } /** * Get the name. * * @return A String. * @since 1.0 */ @Override public String getName() { return name; } /** * Get the OutputStream to write to. * * @return An OutputStream * @since 1.0 */ @Override public OutputStream getOutputStream() { baos = new ByteArrayOutputStream(); return baos; } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/EmailAttachment.java0100664 0001750 0001750 00000006712 13137110666 031047 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.net.URL; /** * This class models an email attachment. Used by MultiPartEmail. * * @since 1.0 */ public class EmailAttachment { /** Definition of the part being an attachment. */ public static final String ATTACHMENT = javax.mail.Part.ATTACHMENT; /** Definition of the part being inline. */ public static final String INLINE = javax.mail.Part.INLINE; /** The name of this attachment. */ private String name = ""; /** The description of this attachment. */ private String description = ""; /** The path to this attachment (ie c:/path/to/file.jpg). */ private String path = ""; /** The HttpURI where the file can be got. */ private URL url; /** The disposition. */ private String disposition = EmailAttachment.ATTACHMENT; /** * Get the description. * * @return A String. * @since 1.0 */ public String getDescription() { return description; } /** * Get the name. * * @return A String. * @since 1.0 */ public String getName() { return name; } /** * Get the path. * * @return A String. * @since 1.0 */ public String getPath() { return path; } /** * Get the URL. * * @return A URL. * @since 1.0 */ public URL getURL() { return url; } /** * Get the disposition. * * @return A String. * @since 1.0 */ public String getDisposition() { return disposition; } /** * Set the description. * * @param desc A String. * @since 1.0 */ public void setDescription(final String desc) { this.description = desc; } /** * Set the name. * * @param aName A String. * @since 1.0 */ public void setName(final String aName) { this.name = aName; } /** * Set the path to the attachment. The path can be absolute or relative * and should include the filename. *

* Example: /home/user/images/image.jpg
* Example: images/image.jpg * * @param aPath A String. * @since 1.0 */ public void setPath(final String aPath) { this.path = aPath; } /** * Set the URL. * * @param aUrl A URL. * @since 1.0 */ public void setURL(final URL aUrl) { this.url = aUrl; } /** * Set the disposition. * * @param aDisposition A String. * @since 1.0 */ public void setDisposition(final String aDisposition) { this.disposition = aDisposition; } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/EmailUtils.java0100664 0001750 0001750 00000023367 13137110666 030064 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.BitSet; import java.util.Random; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.apache.commons.mail.util.MimeMessageUtils; /** * Utility methods used by commons-email. * *

* These methods are copied from other commons components (commons-lang) to avoid creating * a dependency for such a small component. *

* *

* This is a package scoped class, and should not be used directly by users. *

* * @since 1.0 */ 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. */ private static final Random RANDOM = new Random(); /** * The default charset used for URL encoding. */ private static final String US_ASCII = "US-ASCII"; /** * Radix used in encoding. */ private static final int RADIX = 16; /** * The escape character used for the URL encoding scheme. */ private static final char ESCAPE_CHAR = '%'; /** * BitSet of RFC 2392 safe URL characters. */ private static final BitSet SAFE_URL = new BitSet(256); // Static initializer for safe_uri static { // alpha characters for (int i = 'a'; i <= 'z'; i++) { SAFE_URL.set(i); } for (int i = 'A'; i <= 'Z'; i++) { SAFE_URL.set(i); } // numeric characters for (int i = '0'; i <= '9'; i++) { SAFE_URL.set(i); } // safe chars SAFE_URL.set('-'); SAFE_URL.set('_'); SAFE_URL.set('.'); SAFE_URL.set('*'); SAFE_URL.set('+'); SAFE_URL.set('$'); SAFE_URL.set('!'); SAFE_URL.set('\''); SAFE_URL.set('('); SAFE_URL.set(')'); SAFE_URL.set(','); SAFE_URL.set('@'); } /** * Constructs a new EmailException with no detail message. */ private EmailUtils() { super(); } /** * Checks if a String is empty ("") or null. * * @param str the String to check, may be null * * @return true if the String is empty or null * * @since Commons Lang v2.1, svn 240418 */ static boolean isEmpty(final String str) { return (str == null) || (str.length() == 0); } /** * Checks if a String is not empty ("") and not null. * * @param str the String to check, may be null * * @return true if the String is not empty and not null * * @since Commons Lang v2.1, svn 240418 */ static boolean isNotEmpty(final String str) { return (str != null) && (str.length() > 0); } /** * Validate an argument, throwing IllegalArgumentException * if the argument is null. * * @param object the object to check is not null * @param message the exception message you would like to see if the object is null * * @throws IllegalArgumentException if the object is null * * @since Commons Lang v2.1, svn 201930 */ static void notNull(final Object object, final String message) { if (object == null) { throw new IllegalArgumentException(message); } } /** * Creates a random string whose length is the number of characters specified. * *

* Characters will be chosen from the set of alphabetic characters. *

* * @param count the length of random string to create * * @return the random string * * @since Commons Lang v2.1, svn 201930 */ static String randomAlphabetic(final int count) { return random(count, 0, 0, true, false, null, RANDOM); } /** * Creates a random string based on a variety of options, using supplied source of randomness. * *

* If start and end are both 0, start and end are set to ' ' and 'z', * the ASCII printable characters, will be used, unless letters and numbers are both false, * in which case, start and end are set to 0 and Integer.MAX_VALUE. *

* *

* If set is not null, characters between start and end are chosen. *

* *

* 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. *

* * @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 null, * then it will use the set of all chars. * @param random a source of randomness. * * @return the random string * * @throws IllegalArgumentException if count < 0. * * @since Commons Lang v2.1, svn 201930 */ 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 ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if ((start == 0) && (end == 0)) { end = 'z' + 1; start = ' '; if (!letters && !numbers) { start = 0; end = Integer.MAX_VALUE; } } final StringBuffer buffer = new StringBuffer(); final int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if ((letters && numbers && Character.isLetterOrDigit(ch)) || (letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) { buffer.append(ch); } else { count++; } } return buffer.toString(); } /** * Replaces end-of-line characters with spaces. * * @param input the input string to be scanned. * @return a clean string */ static String replaceEndOfLineCharactersWithSpaces(final String input) { return input == null ? null : input.replace('\n', ' ').replace('\r', ' '); } /** * Encodes an input string according to RFC 2392. Unsafe characters are escaped. * * @param input the input string to be URL encoded * @return a URL encoded string * @throws UnsupportedEncodingException if "US-ASCII" charset is not available * @see RFC 2392 */ static String encodeUrl(final String input) throws UnsupportedEncodingException { if (input == null) { return null; } final StringBuilder builder = new StringBuilder(); for (final byte c : input.getBytes(US_ASCII)) { int b = c; if (b < 0) { b = 256 + b; } if (SAFE_URL.get(b)) { builder.append((char) b); } 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)); builder.append(hex1); builder.append(hex2); } } return builder.toString(); } /** * Convenience method to write a MimeMessage into a file. * * @param resultFile the file containing the MimeMessgae * @param mimeMessage the MimeMessage to write * @throws IOException writing the MimeMessage failed * @throws MessagingException writing the MimeMessage failed */ static void writeMimeMessage(final File resultFile, final MimeMessage mimeMessage) throws IOException, MessagingException { MimeMessageUtils.writeMimeMessage(mimeMessage, resultFile); } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/util/MimeMessageParser.java0100664 0001750 0001750 00000033541 13137110666 032335 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.ContentType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimePart; import javax.mail.internet.MimeUtility; import javax.mail.internet.ParseException; import javax.mail.util.ByteArrayDataSource; /** * Parses a MimeMessage and stores the individual parts such a plain text, * HTML text and attachments. * * @since 1.3 */ public class MimeMessageParser { /** The MimeMessage to convert */ private final MimeMessage mimeMessage; /** Plain mail content from MimeMessage */ private String plainContent; /** Html mail content from MimeMessage */ private String htmlContent; /** List of attachments of MimeMessage */ private final List attachmentList; /** Attachments stored by their content-id */ private final Map cidMap; /** Is this a Multipart email */ private boolean isMultiPart; /** * Constructs an instance with the MimeMessage to be extracted. * * @param message the message to parse */ public MimeMessageParser(final MimeMessage message) { attachmentList = new ArrayList(); cidMap = new HashMap(); this.mimeMessage = message; this.isMultiPart = false; } /** * Does the actual extraction. * * @return this instance * @throws Exception parsing the mime message failed */ public MimeMessageParser parse() throws Exception { this.parse(null, mimeMessage); return this; } /** * @return the 'to' recipients of the message * @throws Exception determining the recipients failed */ public List getTo() throws Exception { final javax.mail.Address[] recipients = this.mimeMessage.getRecipients(Message.RecipientType.TO); return recipients != null ? Arrays.asList(recipients) : new ArrayList(); } /** * @return the 'cc' recipients of the message * @throws Exception determining the recipients failed */ public List getCc() throws Exception { final javax.mail.Address[] recipients = this.mimeMessage.getRecipients(Message.RecipientType.CC); return recipients != null ? Arrays.asList(recipients) : new ArrayList(); } /** * @return the 'bcc' recipients of the message * @throws Exception determining the recipients failed */ public List getBcc() throws Exception { final javax.mail.Address[] recipients = this.mimeMessage.getRecipients(Message.RecipientType.BCC); return recipients != null ? Arrays.asList(recipients) : new ArrayList(); } /** * @return the 'from' field of the message * @throws Exception parsing the mime message failed */ public String getFrom() throws Exception { final javax.mail.Address[] addresses = this.mimeMessage.getFrom(); if (addresses == null || addresses.length == 0) { return null; } return ((InternetAddress) addresses[0]).getAddress(); } /** * @return the 'replyTo' address of the email * @throws Exception parsing the mime message failed */ public String getReplyTo() throws Exception { final javax.mail.Address[] addresses = this.mimeMessage.getReplyTo(); if (addresses == null || addresses.length == 0) { return null; } return ((InternetAddress) addresses[0]).getAddress(); } /** * @return the mail subject * @throws Exception parsing the mime message failed */ public String getSubject() throws Exception { return this.mimeMessage.getSubject(); } /** * Extracts the content of a MimeMessage recursively. * * @param parent the parent multi-part * @param part the current MimePart * @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())) { plainContent = (String) part.getContent(); } else { if (isMimeType(part, "text/html") && htmlContent == null && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { htmlContent = (String) part.getContent(); } 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++) { parse(mp, (MimeBodyPart) mp.getBodyPart(i)); } } else { final String cid = stripContentId(part.getContentID()); final DataSource ds = createDataSource(parent, part); if (cid != null) { this.cidMap.put(cid, ds); } this.attachmentList.add(ds); } } } } /** * 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) { return null; } return contentId.trim().replaceAll("[\\<\\>]", ""); } /** * Checks whether the MimePart contains an object of the given mime type. * * @param part the current MimePart * @param mimeType the mime type to check * @return {@code true} if the MimePart matches the given mime type, {@code false} otherwise * @throws MessagingException parsing the MimeMessage failed * @throws IOException parsing the MimeMessage failed */ private boolean isMimeType(final MimePart part, final String mimeType) throws MessagingException, IOException { // Do not use part.isMimeType(String) as it is broken for MimeBodyPart // and does not really check the actual content type. try { final ContentType ct = new ContentType(part.getDataHandler().getContentType()); return ct.match(mimeType); } catch (final ParseException ex) { return part.getContentType().equalsIgnoreCase(mimeType); } } /** * Parses the MimePart to create a DataSource. * * @param parent the parent multi-part * @param part the current part to be processed * @return the DataSource * @throws MessagingException creating the DataSource failed * @throws IOException creating the DataSource failed */ protected DataSource createDataSource(final Multipart parent, final MimePart part) throws MessagingException, IOException { final DataHandler dataHandler = part.getDataHandler(); final DataSource dataSource = dataHandler.getDataSource(); final String contentType = getBaseMimeType(dataSource.getContentType()); final byte[] content = this.getContent(dataSource.getInputStream()); final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType); final String dataSourceName = getDataSourceName(part, dataSource); result.setName(dataSourceName); return result; } /** @return Returns the mimeMessage. */ public MimeMessage getMimeMessage() { return mimeMessage; } /** @return Returns the isMultiPart. */ public boolean isMultipart() { return isMultiPart; } /** @return Returns the plainContent if any */ public String getPlainContent() { return plainContent; } /** @return Returns the attachmentList. */ public List getAttachmentList() { return attachmentList; } /** * Returns a collection of all content-ids in the parsed message. *

* 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 getContentIds() { return Collections.unmodifiableSet(cidMap.keySet()); } /** @return Returns the htmlContent if any */ public String getHtmlContent() { return htmlContent; } /** @return true if a plain content is available */ public boolean hasPlainContent() { return this.plainContent != null; } /** @return true if HTML content is available */ public boolean hasHtmlContent() { return this.htmlContent != null; } /** @return true if attachments are available */ public boolean hasAttachments() { return this.attachmentList.size() > 0; } /** * Find an attachment using its name. * * @param name the name of the attachment * @return the corresponding datasource or null if nothing was found */ public DataSource findAttachmentByName(final String name) { DataSource dataSource; for (int i = 0; i < getAttachmentList().size(); i++) { dataSource = getAttachmentList().get(i); if (name.equalsIgnoreCase(dataSource.getName())) { return dataSource; } } return null; } /** * Find an attachment using its content-id. *

* 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) { final DataSource dataSource = cidMap.get(cid); return dataSource; } /** * Determines the name of the data source if it is not already set. * * @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 UnsupportedEncodingException decoding the text failed */ protected String getDataSourceName(final Part part, final DataSource dataSource) throws MessagingException, UnsupportedEncodingException { String result = dataSource.getName(); if (result == null || result.length() == 0) { result = part.getFileName(); } if (result != null && result.length() > 0) { result = MimeUtility.decodeText(result); } else { result = null; } return result; } /** * Read the content of the input stream. * * @param is the input stream to process * @return the content of the input stream * @throws IOException reading the input stream failed */ private byte[] getContent(final InputStream is) throws IOException { int ch; byte[] result; final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BufferedInputStream isReader = new BufferedInputStream(is); final BufferedOutputStream osWriter = new BufferedOutputStream(os); while ((ch = isReader.read()) != -1) { osWriter.write(ch); } osWriter.flush(); result = os.toByteArray(); osWriter.close(); return result; } /** * Parses the mimeType. * * @param fullMimeType the mime type from the mail api * @return the real mime type */ private String getBaseMimeType(final String fullMimeType) { final int pos = fullMimeType.indexOf(';'); if (pos >= 0) { return fullMimeType.substring(0, pos); } return fullMimeType; } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/util/MimeMessageUtils.java0100664 0001750 0001750 00000012123 13137110666 032172 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.util; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Static helper methods. * * @since 1.3 */ public final class MimeMessageUtils { /** * Instances should NOT be constructed in standard programming. */ private MimeMessageUtils() { super(); } /** * Create a MimeMessage. * * @param session the mail session * @param source the input data * @return the MimeMessage * @throws MessagingException creating the MimeMessage failed * @throws IOException creating the MimeMessage failed */ public static MimeMessage createMimeMessage(final Session session, final byte[] source) throws MessagingException, IOException { ByteArrayInputStream is = null; try { is = new ByteArrayInputStream(source); return new MimeMessage(session, is); } finally { if (is != null) { is.close(); } } } /** * Create a MimeMessage. * * @param session the mail session * @param source the input data * @return the MimeMessage * @throws MessagingException creating the MimeMessage failed * @throws IOException creating the MimeMessage failed */ public static MimeMessage createMimeMessage(final Session session, final File source) throws MessagingException, IOException { FileInputStream is = null; try { is = new FileInputStream(source); return createMimeMessage(session, is); } finally { if (is != null) { is.close(); } } } /** * Create a MimeMessage. * * @param session the mail session * @param source the input data * @return the MimeMessage * @throws MessagingException creating the MimeMessage failed */ public static MimeMessage createMimeMessage(final Session session, final InputStream source) throws MessagingException { return new MimeMessage(session, source); } /** * Create a MimeMessage using the platform's default character encoding. * * @param session the mail session * @param source the input data * @return the MimeMessage * @throws MessagingException creating the MimeMessage failed * @throws IOException creating the MimeMessage failed */ public static MimeMessage createMimeMessage(final Session session, final String source) throws MessagingException, IOException { ByteArrayInputStream is = null; try { final byte[] byteSource = source.getBytes(); is = new ByteArrayInputStream(byteSource); return createMimeMessage(session, is); } finally { if (is != null) { is.close(); } } } /** * Convenience method to write a MimeMessage into a file. * * @param mimeMessage the MimeMessage to write * @param resultFile the file containing the MimeMessgae * @throws MessagingException accessing MimeMessage failed * @throws IOException writing the MimeMessage failed */ public static void writeMimeMessage(final MimeMessage mimeMessage, final File resultFile) throws MessagingException, IOException { FileOutputStream fos = null; try { if (!resultFile.getParentFile().exists() && !resultFile.getParentFile().mkdirs()) { throw new IOException( "Failed to create the following parent directories: " + resultFile.getParentFile()); } fos = new FileOutputStream(resultFile); mimeMessage.writeTo(fos); fos.flush(); fos.close(); fos = null; } finally { if (fos != null) { fos.close(); } } } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/util/IDNEmailAddressConverter.java0100664 0001750 0001750 00000007230 13137110666 033540 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.util; import javax.mail.internet.InternetAddress; import java.net.IDN; /** * Converts email addresses containing International Domain Names into an ASCII * representation suitable for sending an email. * * @see https://docs.oracle.com/javase/tutorial/i18n/network/idn.html * @see https://en.wikipedia.org/wiki/Punycode * @see https://tools.ietf.org/html/rfc5891 * @see https://en.wikipedia.org/wiki/Punycode * * @since 1.5 */ 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) { final int idx = findAtSymbolIndex(email); if (idx < 0) { return email; } return getLocalPart(email, idx) + '@' + IDN.toASCII(getDomainPart(email, idx)); } /** * Convert the address part of an InternetAddress to its Unicode representation. * * @param address email address. * @return The Unicode representation */ String toUnicode(final InternetAddress address) { return address != null ? toUnicode(address.getAddress()) : null; } /** * Convert an "Punycode" email address to its Unicode representation. * * @param email email address. * @return The Unicode representation */ String toUnicode(final String email) { final int idx = findAtSymbolIndex(email); if (idx < 0) { return email; } return getLocalPart(email, idx) + '@' + IDN.toUnicode(getDomainPart(email, idx)); } /** * Extracts the local part of the email address. * * @param email email address. * @param idx index of '@' character. * @return local part of email */ private String getLocalPart(final String email, final int idx) { return email.substring(0, idx); } /** * Extracts the domain part of the email address. * * @param email email address. * @param idx index of '@' character. * @return domain part of email */ private String getDomainPart(final String email, final int idx) { return email.substring(idx + 1); } /** * Null-safe wrapper for {@link String#indexOf} to find the '@' character. * * @param value String value. * @return index of first '@' character or {@code -1} */ private int findAtSymbolIndex(final String value) { if (value == null) { return -1; } return value.indexOf('@'); } } commons-email-1.5-src/src/main/java/org/apache/commons/mail/util/package-info.java0100664 0001750 0001750 00000001577 13137110666 031314 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package provides some utility classes. */ package org.apache.commons.mail.util; commons-email-1.5-src/src/main/java/org/apache/commons/mail/ImageHtmlEmail.java0100664 0001750 0001750 00000015746 13137110666 030635 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import javax.activation.DataSource; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

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. *

*

* 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. *

*

* The image loading is done by an instance of DataSourceResolver * which has to be provided by the caller. *

* * @since 1.3 */ public class ImageHtmlEmail extends HtmlEmail { // Regular Expression to find all 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 } tags */ public static final String REGEX_IMG_SRC = "(<[Ii][Mm][Gg]\\s*[^>]*?\\s+[Ss][Rr][Cc]\\s*=\\s*[\"'])([^\"']+?)([\"'])"; /** regexp for extracting {@code

Email Downloads

We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours) may not yet be available from the mirrors.

You are currently using http://mirror.deri.at/apache. If you encounter a problem with this mirror, please select another mirror. If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

Other mirrors:

The KEYS link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

For more information concerning Email, see the Email site.

commons-email-1.5-src/src/test/resources/attachments/autoloadertest.html0100664 0001750 0001750 00000001537 13137110665 030122 0ustar00stefanstefan0000000 0000000

Auto Loader Test

commons-email-1.5-src/src/test/resources/attachments/logo.pdf0100664 0001750 0001750 00000075540 13137110665 025635 0ustar00stefanstefan0000000 0000000 %PDF-1.3 % 2 0 obj << /Length 4 0 R /Filter /FlateDecode >> stream xڅRn@.df01 UԈJkt8Viw@M6Yp3ss| >0Mr@7䰄 ȠB+U WƒtE UAI9?&)~wHP#,ޤFBT96K-0oruD`Ul0x4;)B(_Cxͮ\.j]<l̮W٦(!|N*Ռ 2]$BLAɺ?߸8y]koeC*n%/D!Yk;r>}O´l1trVRS6X[[Am@l,G@<^_Dj6!dQɐq0B8J endstream endobj 4 0 obj 371 endobj 1 0 obj << /Type /Page /Parent 10 0 R /Resources 3 0 R /Contents 2 0 R /MediaBox [0 0 595 842] >> endobj 3 0 obj << /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /ColorSpace << /Cs1 5 0 R >> /Font << /F1.0 6 0 R /F1.1 7 0 R >> /XObject << /Im1 8 0 R >> >> endobj 8 0 obj << /Length 9 0 R /Type /XObject /Subtype /Image /Width 537 /Height 51 /ColorSpace 5 0 R /Interpolate true /BitsPerComponent 8 /Filter /FlateDecode >> stream x]MY0V"wB %R**4Rĝ:4n:e,̐ d1HBp:ib I;K:"Ww{羞4hРA_>*aРAͦ{ʫ 4;/k1@[4hРSH|C˩`Jp7d' tW^=.^=D P\~߿fO} l/q^6/ D uFKkUtJ> =_:V7L03Fr=ߋly O~ OO=k՗# Cs ‡NӁWUcLjVA<= 峿%ֺn &P=~o04!M^6tյ WJ!|Fc @T9#BB*5HmYm;v(A7Lri^A't E{L%r0 mT}  $p޽~A H%Q}Υ߃̢rd5z`W8pJI'^f'5/`FoI\5ƀ%;% jIvda0"0srF&lz _JP|) G)@TAy򇿏d=ݸ݀Pì^9Y ;LwP/ѧK^̇i@ɀd{Ih;0Tc  %.\_3B dTNI` B=s/ДҥsP[%$J퀴H28E#q*ۣJ@kL97`u #$ +83}4+-eeCHe[]ޭhx.-\5\>4}%BI'v6~j/ٍ񁕈l8p+=nExٝ a0.aYN{OR3 O ^Bd P0B *4ˑE0-4޽%4'jhCLW9H60KV{OL;$-\Ud]l݄Qbd[I]cW4sB Gheeq[aLjڧ22CFQ%%KuSpk*JMFt7*KIjMAAPK(_/> PPPAC/ #/,S5߾cP:Ia)2Ҁ}tjLn~^Ѻ,x]mJ| U3V{/eJi\d^,( A#݄9Ewˡemƨ(_|+(A pP"XqQZ/WI2 #A zQW=o;Kz܀K?H]DFϢXsV99c; =9>\uiNGͅP|}XVtQMBk^%SQ`-(7esٌ&VP.OXq|ZLs<=y(ƹ3՗яO8裯`2J4=qP&+֍G%aq'9UG,~IwPRdķTmPBUKڛ{LE;;>$HT Z/.iI 7_Em;l_qvNq*$yI Yɵ$UT1RvE5q G]6߮7T(Y J\JV%tA+p)A*z`G$@Q(V\:{ XPdrL<=n~5U!ۯB3v!b^Rvv6JQ<[6xLjb+LyMP%3l%%Wա[9[:꒍Bɣ(|m0Rǔ`]ޕ`(.ׇI+vT va c0IO~0 B=0*2iƨ$S82KSY%C{a\.,r&%+MB҄R(?7VGS/ST(X Ӟa^)UߖÙ A 2Lc&fnyuWs"ODcD ءGlp{TJɪ@ >` ~ Ȓ5CQ0 !`dAA* m L"HRNyѺ@MJuH{fr\0vf4_' 9Nj,aϊ,0[)xRޘfZ0"~@qspNbS˒.Qej|JP9`ቔ\]ndz[Y'l)9Qsxg?P|W˨X-Xʭ*&+8Y[0@ڑ?u1S2Ƥ!>je5&oFmzAF+n:OZ4Cq3ӟzol .![:%b auSXU+AZ_3EV+ԇ_ԣD%,؃k] x$d Az,ݼ PX0t)4co4_V<,! A3& +X SBO01#ڸr,G\~ӟ (4h)^ypdiԿ2MJ(d@ɚ\Wۊ=st,pXp3 ){VZŽD1 66&Ş% y;(DZ%^B@InZURJ|x+A I>/4,'`CuL8MK(޿ʠAK\;@́еI4@P,#3`-,,dkqf_TOS5?0D U8\hUٶ 4hs.̬rwdB,'{v=TX>!OKa\.~S>_RK=ʵ/ЯeO4hP7ס).p~([E!yc: idۆ{_o-,LQԻ^TKg׼|zĞQY FٽzLKBXS(ApI \<e"Kzӄ`|LzBdڕ<ȫGVϿ)=nYI> P!!3ɠmg\h:'Wg#Sl_Ihz+z^PG77(1|1Y* q*ԧ(\ơ/Y'ȆXpRUK 4ABX9;T(9xcƛkV2`Jvsj,5 .\")ߡuv]Bqczv9 7{ b78n2S "(R+݃.<-hbЀmw1sc 49i tAU-&Ն!FR 4‘4>]>xj+e\B2u3hK"9XK)|3nYrmmo%n3qM₌LGƔ͕ CO(=@yEDr=/&`koucߙ/yNsϺZiݴW LzpT;N ;W_{tw/Sd*IK_9懲╢y J rQ\:+6 lv:k? ̄Ɣɜ6+SKoF}TBTXlҴ;WfDc0r>d]!|/:箢 ``ޗ  /ehJc+CL0CN$Ѹфt@],C \BC%:W2753TeޓY2rT|gnf<{8m:@(23JX;e7EҦHسRdP9wpDwVg o{^Xy&7BPprgR)&_J[a$,Q%Ê~9=#|ʸ"}j;%Q97n{)L4WltbJRRT1qu6]I[ y!^ |TJJK-+5|֌N9OA_9WL+ 5QT:Ǘy/5~uk*JcƵOZnsh;ҌDZJ 2[J77DTQ%=,Z̷&o% EU/trt7'PۤF]9O-Lm)Į] `<ΐMEZXR Q2"VA6q|8/3iM3uT_#urÓcG%Ϯ ]bb]-.t4'SNwsv\:'3䍾F96M(Fh|y|M\^g):K2gRlv9E*kRE0R>@ &8lCsbBvwו9.8~?D4q%[X c(;b[(n(3GO D[hMzԇ!O[k d>UN*ظ=Lm;vչ:*wfm(U%v#/wn/2I;k(C6m$)ߋ(ȒaCD%\uї>%4B+,*\,M Q^7?߸ trJb蜛֌?b_"s[ԒQ~!KnȺ4QK4\gD!#:r$B+آR rl8#B:$|1# %zFr%G]cVsyXd%PtC?X96ŠjÈG(nKg*>e~|w!}:@GWXۍe)S6a]$+LEPr!FLYj dׂ =MBD<qH tJ$dRHhA YfAZ?+ endstream endobj 9 0 obj 6800 endobj 11 0 obj << /Length 12 0 R /N 3 /Alternate /DeviceRGB /Filter /FlateDecode >> stream x}OHQǿ%Be&RNW`oʶkξn%B.A1XI:b]"(73ڃ73{@](mzy(;>7PA+Xf$vlqd}䜛] UƬxiO:bM1Wg>q[ 2M'"()Y'ld4䗉2'&Sg^}8&w֚, \V:kݤ;iR;;\u?V\\C9u(JI]BSs_ QP5Fz׋G%t{3qWD0vz \}\$um+٬C;X9:Y^gB,\ACioci]g(L;z9AnI ꭰ4Iݠx#{zwAj}΅Q=8m (o{1cd5Ugҷtlaȱi"\.5汔^8tph0k!~D Thd6챖:>f&mxA4L&%kiĔ?Cqոm&/By#Ց%i'W:XlErr'=_ܗ)i7Ҭ,F|Nٮͯ6rm^ UHW5;?Ͱh endstream endobj 12 0 obj 706 endobj 5 0 obj [ /ICCBased 11 0 R ] endobj 10 0 obj << /Type /Pages /MediaBox [0 0 595 842] /Count 1 /Kids [ 1 0 R ] >> endobj 13 0 obj << /Type /Catalog /Pages 10 0 R >> endobj 14 0 obj << /Length 15 0 R /Length1 22508 /Filter /FlateDecode >> stream xڽ| xTEp^n;Mh0!Fp(E"kDP &7!}OugFetS;!8̼U[u~4BFN8?-oko' D6eu Qw NyvOk a䉓fBʷkz|X=jϞ+f27̸v'JX7M8w9BFMzƉ'V߁3f?cy7~&6 |?|G$~d $+[6;!q'q= IM#$3+@!١9y={{9o?RXԟg@)LRμG89wse,.]I&:Q+A,C:$1c}gvI"9y%ȳd# ˭5'`!Lsc$7JHIY7;n*rI؉'=Є+\MѷYqddVFbOO/! s"e׊T{[߸6O~ޥT#WzL< 1E|[pvZOȥd(Yt 2 >>mgDwby¦2κν{KY?!'ǽRYuuFKȍFnj,/28Rvr g >uXழaYY2oXcjWbryLǥ7n8Yٴ9I frI&q+'bLKUl4b_H4&Q9f_|e+'[]en 5P6m8O| r?, !n ,cXJll,K8 WX2v^?0zŢ\n8*ٔJ> &莗e9@#QΉFp7{ʲictXGiG<xMcѴF_}i j;L(&7g}ǟGF46F44Nl騿&0B[,ƙe5S_Z*f`$2cF\^3"P;1,JCⴠ֝3x{.g6 j^ZP+Ōb.(ך TVv4aI7.:E `~KhA)o~}a|u,a WWH`&b%:}חCq{ flأS'/k vrV|puܿr!Xy/̽'|h;6*目 (\p.$e`JFҢV4y<߷o̭ (9vXbN܃cF÷2\lwvEEBz8"e.Z4b/-wxQx8\PSOxIǧ]ȓ:q[+4X@OI!=u:U 4ʹ2fS0+Nu.`btf!颱Q-IQu6G]@l>_XtĤk]uub6qyD#G #Q;`<<,@t}U{#7'D{WIe aC+;ʙc%QeHJ6P PRۋ.9pF uG 9U K$\trA3~'r?k5?Ed͙'p c@%'\B5| C Urŕx=t AFAj"%R.0 ,zNu]l26rP]玿8+Ks|HRX*W3S9vDTB*bY˺saHn([J<5O-7ZGs=:w\;ޡ{?k>W&x9 ̑ULNC>PA' NT_ZfNͳ5X8V,)ufq 9=dH]m&Xt, 2+[)%]˟t˒.&H.+Q]+Qw@߾΍FL61#ؿϬ+QuRKR!?5d&jTդ}Q̎)dMHb<> Wm#0(4! ;G_\Ǡ-+__̐_g\{60ME>]I#V8zy/I+r]2vQ(d=O33Vw1͘JFye v+6WsEh$µPsp5ZP(t0>޿FY>x5N @~Iu{hp zѣ>P&d7U$D_pnj8g:::r̢)vf۠Kd#Dr$'vn 5:N;3\|/N)P֌r_>-aD =lFio3!b2K|ϖQ.}ކ5OУ ?3ؐg"{&>/~MZ@-L$@~FTg _}\)Oi jZWa`4 zu HP.Ri5͝=-S-pAvke&p^r%*j`!c_E-Kmõ&gnTRQngF(ѷРnڑ Wh s{bj'QH?8 P19=n2K 묄0jƱ΅m5ėqMKn{Mc{c~hDseB@?3a8llɃ>m*}I4nc󽷌}tmL6m~]my4wڟ?Q5~SoZz[ơL>iD!AhƋmthн2A8Y\+zJquNv2&0[:DV<"2(a@jiT Ւbia@)ECqg䑍v3Fw UtCw%ʡ0X@ϐãF{#! ԔCSH8! Q4 az>^0u"|;Z޽oSy?| ,Liddx)3QՎ8j+mm7FԿ†LKFگnjc5UnmwnmVU'?Pzp-o4FԻ5}OADP (H LuAXSݚRQR\c$e-ˊ@53i=I+LbkQpUcv(w@(W/&Ң"rgfYxk2g?b.vw>{:z=EKBmdq"^T:hx@j#HXXs@^fj?h#VP#{LU0zݑ8߄a`Nl;ʿ#a/<+xPLS5%'M겻ݣ,s͠^vCF~0ڒLWݘD \ $J}<ğ/p=qH?́u0 nC[_?q۶:;3m<q -qy.;FUYC1rVmQwz(_1A=b*b&p'E>>͎jɻ5X(H/Ϡ>r}+ů:}c"GPy9&rAF9~&t V̽mE?zVs͜6m| j @AhPY#Fo_W!2*.ѪϤnK,4v6CPe"dCڛ+EfSUUXe#SX.~_o'@ TT>F-]4 JNT5e_zP3;+yE1ojuI5h9 4MoW`__riDC 6 0"ے:Q(7u.w+|GvkkU*RSb3?R^a 9aprkJwUAU /u %G1(q&u'Y,亰 at`] @ ^|zo?m!S63nISsy2DЮcIyQ&0v*_U aF"'Sh*Q)[Qdt]IlX$ʢb. 8G=#H s)28.0?\שCDMNxaU|W,hMoj AQ'u|ʎxq|Zfi8ݛ{xB@4PO4drL̳4Z Y΢[!:JC@Fϗʀˆ @lztjҵ 5[A[Z\qӇߑh%5=5({MC=5NaС`"Sb;lveB'(%,*c9GB:]Cp ?PsBKV&. yGfO`/ 21uO>چ)n<׾5iǿoiW=䆝Sdճ+GtI7[1yAn^/Gbv@~I U)Vz CWY =ep!y\hZ0 {#l+tFTz ]ڍy(Ȅ]hUpwJʕDSW~ߠ:.N=з*}H}%dֱX+%sf+h} ^H7KKO7C"-Xo3Ip @$FTXH"+`jl&{ccBAqǼc^X {ނZ.b:_>4h v(:=W:ljFO(+R|Xa #=,@>-GMz!'t3㪰]Jy##~Bq$4R/VET Z,,--dNm$Y%14ݲ7%LY%`Me:3 ZfLDeA@ RiXZ-:* U٢ }Z&괯^ϟ8RX Qm[B;u)B,-Lpf*DXvҌ-oa { t|{_Aup: s~]iD+BvF].x&FnO\y@~@~[>%rf+W0vE]KY bU-"*[LMȂΚSߨT1IF/"-ShZ茐RD7eB+ 4,%Hq(/t>>p5u]!!"#$F0.c}*͡@-t%p!>Gp IG?e}3@Ǡ~Q2`Jʹ]MrQq.,jw.\SM9@(;$I3\|ANc3B鉩M_YlqT=WU`gax zNc;|*FAtqҠ/}` 47G녕FQ*h T^T O;_v~,g48:<=^b/̠iev1K,UhR <׮)b~iJ7篂N&KDPը ' =7d9B>ClEs|mÊSnz d;ZK Y$~V'V탗|bX{l+cc@MetoIItDd(ʓm^pڲmfl|&Y. *z~\uO*ph*&z4^Э T \;duEĺpiXLhʜsxC: Bʾl{k/ C5W_J4~ Js χi!4>}ep+= ӛ,&5Iv%fnp;% TFYA;ȟ۪DGP4 z vp͵*&^vԩq쩵K=5M2^- G-H" L< |l~ e/NYtYb+,{-AZ'Q,*éQS&\@+,C*~@O+ ?3<,,Wo5kYZZ\Cpӌ&*eSH&zhp}I=㬥=3)!. ݄.* _Eۤ5k߄pb` R0A{qh Ҿoo0QyɆtKa@_C, ~Mߪ}sQ'9Ȫvioo7Ke_VZje@jFrz-1.41lnbK$CB_0B "^iDkPMKŠgrKPj&}a>jp>՝[/CR-֦S?ѷohPӆfsMD]ƒSңB4?  I;ī)l 7DG=Aa:OA =.JW>8F`[7uk>arC9! (jIR}pWqî-]_H*<%/S1@9:1U>('D;=利8J Fh4WY^!WYOxQpL:T=6bk4\T!n!M4t3:STJK9euY6%i$+8$|}NcA-V-C<18ʳlSu,+͠Ԧ裁(MJJ,v2C >P  J tD-MkCu_Jl?;uz2aG_,Y߯H;/[H~wxuD#܏8>E׻TBdCQicxa*?,[@Fi,G Ilv<7d!O&OX0렍K*Q`&0gؙlȞev3I(lݢ. bG]LNfiL c_sĽow/']}8Y0ReOi2qP30+mT-@t}Nox J") Uxj *\l 5@ҁCצߛ.vUlm,(߫Ë \Mmnt{?S A}\yۿn* K2!3]NhM1*Yvf- N+z}0ZΝgW~cNJpp믯;sӬ_c_{KJ)}](k:7xSӶuω^oZQ0]A4 &44pv'[&X(W&w/DΩ#t3?O?1_/SD0A֝&6/_ oZJyf]u`mZ뵠]K#X5Ooi',.IC$f461|-aXV-2ETxH<!}b1q gIE*mvD;)khgTt#9A*>uzz]}S=se:>\vY=y鲐RUT~%͍U.E3U DJK*0(z.Tt&@ yYwSp댓q;Gu'ΧP\B `X|hOl6~J8v6_Фe%ٕHK]C>"yw`D׉`.:k<'NBfqy,ihK (AS5kˉ&D~!U La0ce s+hDe E")(0DDAfEŌ՘Lcqh3vTE%eH]'3`/%υU~0\ 3s!kW|9l.#xۏs1;! 5u:0xP"?(Z`d{+| ̗Z?EE3{ogHK6C]ojfsJcir"Kr$Z2 .>iN`Z3L[0=)]M>c5$Gl qd'ڄb]Q. ';o0 " d')\B&+Vq!@:E:Q%B p0̠%B;VZiFDYby}+e7DLE,aRX;]%P^ 0E`'l1[Q:OFΖGɟ)5zY6}GK.74#x1w>[pr׻n.$ Id,fa_ I&R5tz!It=&XM(Ld,ZЉH}a&C5gfZ8p nfamh~"?9?$Ixq4e?Db{[V>4܌Rka9$\wT2y]p7nyNy=+.in`, iv#CU9 pP9;^qFMMܿ(76i{q{H58:Lh&~ ~|& +g#0ldPYܣY7M2NGa#I.&JTڇ`xy1juDB^4`rc^/:$s.\Y^5 J. ͹@ |ޜ M? ?MO$<|~+fS>cd{fq_3*rGȣab_.U W&a#B>ϸ楨&`ls=CpyRe\ڼ.jekBW^pHS=|u'==,kG'0Cw |XVa 1[1XLczmt Et1 BC(+uP'k6tx-( C8tP:u(uA~i'1bLdAi&Apa20Y1I%*;~["|½@{oE @.>La7 7k Pc֧4SH)Ř܊qY8j™8&L03bi"zCb\<z0~H'0w[\ s saG7#A@gc/X =j? <On-?+lgl=B,[ n7ÙX Z¢a,geK, ]v&A/Z=ֻӠwIܒ%%̒Yb/QKVBJ* MF_~~/;?Vcb18`k.oryLXB8]yUe |߱5 wVm,. zie, Wnp~UUUlJ~UU8#6~K}FUΨ"c/3f:uK~nYWXﲚ;&\pY,^6hhx,Yd.(kpt}Ze-BUKgςu٘uevsceJtd=cl[׬0 L cXsӗ@ ,?k `Q,N-$ pG4$X`ɝ!=$M4 04Oa 0<`D\`ނ?ksŘGǔ1*+b Ow9 endstream endobj 15 0 obj 15030 endobj 16 0 obj << /Type /FontDescriptor /Ascent 967 /CapHeight 732 /Descent -211 /Flags 32 /FontBBox [ -863 -738 1642 1203 ] /FontName /DMRUYU+LucidaGrande /ItalicAngle 0 /StemV 0 /MaxWidth 1629 /XHeight 536 /FontFile2 14 0 R >> endobj 17 0 obj [ 316 750 750 750 750 750 697 750 750 750 750 750 750 750 316 524 632 632 632 632 632 632 632 632 632 632 316 750 750 795 750 422 750 690 750 692 749 542 750 750 750 288 311 750 533 861 750 777 553 750 632 539 750 693 654 855 750 623 750 750 750 750 750 750 750 552 629 512 629 557 368 624 621 289 304 584 289 934 621 614 629 750 409 510 374 750 750 771 613 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 750 1000 ] endobj 6 0 obj << /Type /Font /Subtype /TrueType /BaseFont /DMRUYU+LucidaGrande /FontDescriptor 16 0 R /Widths 17 0 R /FirstChar 32 /LastChar 201 /Encoding /MacRomanEncoding >> endobj 18 0 obj << /Length 19 0 R /Length1 8704 /Filter /FlateDecode >> stream xڽY xTE>UyuҝG$ 6r#:$@nP  (oZ4|7:;Gĵ ':,>fuȊ:H_ބavΩ:uΩS1"Q$.[n4 ˠehOd\|*_>Dͷl\~ʥBl ȧCsn = ޸jۍ$'OeͲ0$ѷ oh6g=>l:wy"5-_ ͫy#' c$YADn!TDe  Lzmޤd%''&?njdUݑF8NzhEO{h֓CZ?P+qzB.U_uQ |*yP\ax0B[z>ǰ :o R m#,-erӆJr T@k,D%\"#OQ'T?䧰u`ާ چ봁CE@ |c7:{{5jfVko\i` hY!U;tVJd dCrc'C?7l?7\\[ɑ'ǘU:-h'oEPI?1yKiR(3m܀[q1G+.g:T#eHkJ$߭*Amho7.K%nf1GFvS ;WAyQ*q[rAcys΂/! H⋬@F# 9=gd-@D4u봗33 HP{F&$B6 nMj甖 w}4J MM"ٳ0g '4kj8!мave== -  Ф0TkB@FYlwɾF9WjĦ_$46DR]zu`ǥ}ZeaX֦]RWBXlnQp=S-)6GZtiQ{=94n3f*#&rSXkcP衡^e_S 1O1{aר.,ѐJ/vkE7\LT5oTVkPLPM06C])c9&,jKzƔ j\z\{u:bLQo6H.V\/ .Q!)<9X׬p>K)X[1L,q10v3;ᥥh9/RW*.$4=|jUaݼP9ʕz6#/+ s-D+CDܒ1"S4Tz\(qL9%Jy4V KUۥAPM}Yf3Dc tsrf^٥PƈA-[\Z:Cpꀌkvސ}ruMA_HՈ.!.57յ)8&AߤLdkjtQ:IKC]_&˾5Xev )J?o鑘,;t!,Eq$Ct5IscĂdZh-(M5eŅ!"$)pB98Ee&SP汘+8~ѥ)Hn.~]U|[`[*A7}wxXp诔dxeexe" gX##S5R /Jߝ)]6RrRzet)] W+~\|9IJXrq甂1+EMk/=5e2nL%%5՚&1F<=55-##=ӚiHqd)Rfegg[Ӳ)S*#L/eʜlY2GOq,I^u}S8!`8Gj'M~M:ϠtN3V3ELHMX=d.ȽjC=M7>wOh2ݧ}";L;9vB䝑ѭ}vBrM;V#Z8#pVD?X^_FX!18L*(<*Zr8m5TZ*=q~,k/C9@bmo(lFgwVR]&dqFea]N.4k`K6o6o)z8D5`+W޾\}m77-_Иﺯ@ñ⢖ME %͕f`e!+U3+=RE>>DNr *콸fT3b֜5coGHh~<+^G&\w {'>`>v?*Ue{B~/!ww˨<*>`{\/풊VVTwrtx'%~X\\%-3`o>~zh?W_Rg?{t4]'MrUTBu#䰄C@D\i"yA~E( ' &KYލ.)Gq~.~Ȋy7ޝ&4?ߕn Bot(ވ; ap*ȏ|ybs6~no5BkE(:PP<#So,*ï yU|>Qp;^t>@xSwEGVN%Mv^n.-Qؓq вo<͞Efn9NŇ+Lwk u:;Һe5vB.\QɎ#.qSÊP߿v@ )y<6{}&ƀ΂N\l~<*;Ss̉ ۄnvULQ V%`|[lo&𿿲_~ǛG+ӟ3Mow~ u6wF;{:u<יy0Rzw,U{@̽&T{οgRynnMSwaQꊎY:N6JG׵E(m\ݾMmM܊6X .vZ;P6F[yw+ʐI-9೥KLi%4XB6.9Mʒ#WP^^$ @vL؇d%v#ǖi$K +VH+JKJS,z[JJUZt ʵgbeўQa3z\ݓz$y[GuӴ<7M%$y6AH5ކ5K[r. $XPDZ]`;ikCnK8ٴ`0]S% C>#:$MN4Gs)KkX>jO kePMO; 'Wj۞j Ҟ.?wZ6_+輄ؔi?ٯA endstream endobj 19 0 obj 4716 endobj 20 0 obj << /Type /FontDescriptor /Ascent 967 /CapHeight 732 /Descent -211 /Flags 4 /FontBBox [ -863 -738 1642 1203 ] /FontName /ZJXWZU+LucidaGrande /ItalicAngle 0 /StemV 0 /MaxWidth 1629 /XHeight 536 /FontFile2 18 0 R >> endobj 21 0 obj [ 795 ] endobj 22 0 obj << /Length 23 0 R /Filter /FlateDecode >> stream x]Mj0 >`'nLȢ?4[ lgV)t!'%/sO>|OaaKaٓhZp.& Ya_3.=MNȏ"9pzrać:{KN_'  Jh W HFϽ+P="7?lpFc1QtJz`gh.#/#-1jOx?U R\RpK endstream endobj 23 0 obj 222 endobj 7 0 obj << /Type /Font /Subtype /TrueType /BaseFont /ZJXWZU+LucidaGrande /FontDescriptor 20 0 R /Widths 21 0 R /FirstChar 33 /LastChar 33 /ToUnicode 22 0 R >> endobj 24 0 obj << /Author (Siegfried Goeschl) /Creator (Safari) /CreationDate (D:20090110225808+01'00') /ModDate (D:20090110225808+01'00') /Producer (Mac OS X 10.4.11 Quartz PDFContext) /Title (\376\377\000A\000p\000a\000c\000h\000e\000 \000L\000o\000g\000o\000.\000g\000i\000f\000 \0005\0003\0007\000\327\0005\0001\000 \000p\000i\000x\000e\000l\000s) >> endobj xref 0 25 0000000000 00000 n 0000000486 00000 n 0000000022 00000 n 0000000591 00000 n 0000000467 00000 n 0000008583 00000 n 0000024828 00000 n 0000030403 00000 n 0000000751 00000 n 0000007734 00000 n 0000008619 00000 n 0000007754 00000 n 0000008563 00000 n 0000008703 00000 n 0000008754 00000 n 0000023875 00000 n 0000023897 00000 n 0000024127 00000 n 0000025005 00000 n 0000029811 00000 n 0000029832 00000 n 0000030061 00000 n 0000030085 00000 n 0000030383 00000 n 0000030569 00000 n trailer << /Size 25 /Root 13 0 R /Info 24 0 R /ID [ <3cc1fbadef9ed7e7064af1bbb4b9d60d> <3cc1fbadef9ed7e7064af1bbb4b9d60d> ] >> startxref 30925 %%EOF commons-email-1.5-src/src/test/resources/attachments/classpathtest.html0100664 0001750 0001750 00000001546 13137110665 027745 0ustar00stefanstefan0000000 0000000

Classpath Resolver Test

commons-email-1.5-src/src/test/resources/images/asf_logo_wide.gif0100664 0001750 0001750 00000013352 13137110665 026415 0ustar00stefanstefan0000000 0000000 GIF89a3OZ1DDDGZ }\RvwwFh78N> Q*jhxFk ? 2<{ l ^~%8kM%5A.0̤u.*y7W"+ŶѲM9&u&efgSVX˼333۽)!,3pH,Ȥrl:ШtJZجvz$.znE~R+?&$}e>>3N.-&?)$th>M&+-' 8C!;?# <Ä'QBNф^ŕb'I'48?8"# 2%;;ۍߪ\Lt8pUjPHF`F WN3NKtPo*GH#Z@#(kףx `DG$ YTNS5@ TQXDԓ}N3 ' Z$A#(F;=ƃ*^Xl/٭Bm* S>L6! Sg.,pҢ@*3r=YU` }j28w^S 4xaG>X%h*ᒘ&@2 d]: gj}M$6EgiyV PB -0dA9PA^{_P :1 GxCH$\L4؁QMA 0D@P25tS*5 A~HYH 'cI6*34DDjD 4lT&q]2&w @1DyB5eD D8&nQY.C .I% -0R%;; ``O6؁bdx"? M% R3O5:gR p# mGS-V DnmUMB>xT&u#Hg̮Wm9'2lۚ1^?bQC'l( m[F$ . pbfPVW6I`~pˮ胳>l*$ '0>lT0[+GMR\U 18R 5yg*ڷ-̵geӱ BTUDuEĪiEm@`@6c*Wο; h]cl4YXuJ@ oxv;~mc)~S  Sx9`\A9zZ'WT߈C&:M<0L4 a'&fȠЄ`G9}PatH/N׬ B2I@۔@>![>$k+1xȖipBX>"x=@󈰔U̎"]E8QQ-TהA<ԪB `OBչd*3YQQs8&dKQ uv =gІ83J KRb]+BMUJ3@`f0O^!ʘ@q(Eր8N3&)"0B-{"NDsCW8-C(8bKTX@^RAITL@fu$b]!S/0̆n;0* p.4i&1S][9mfWT+Z!pUD`J gH@1S;X8 Zt%YFrTYtV)7wDLU^`8+ e|KPn@ X =_ 9tf5*Jiq*{kYؓJ: IN?dMVw#EWN vRaOH;u[]i%Cf9K Sԇ6u0_0OTxd0k$;%HV" lȭ> 83E@v1 0$@t* .'f0JZjeť+H\bI7.EGT~dc,eⳜWH6돗+ȬVA|-Ĕŀ} !>*Q&@ Fh@P]h= .Ug4;uFDX\\$c f$uɫ }H:vQvHL.tQ W$.n D 8Hf3 Ze^U3eBAs^rK#xyg8 P 4`i%ĩ5Rj6F\ ʲG!C0a FRZD$pw{*oZ);_Պ o!({c~Ug8AUR6P ^`f A!l){_q9@e |\4`%~9TUynDK=IZ{$?YeHd'%+GwQ,2Ћ(wpYB&QZpQWЌ'p?]%&M ݰ?f- |33A8US'e)XS傦X3+!xȗ|#m `#0Thp[ q@$I$@h:` @8KdfY9Y8e_G|0Fti36;`L `P. e"yXe @8B BCULgY?4S5eŖt.ES!t+CY`!SiN|0a`ZRp@3?Pv!P1*Xl5\eXS_9E)b;q3#; |2 ^ĘIЛJJ`%}??)Wb(2T?[R/D೥$V Hǚ.LK-S.`GoU@[R , !ڥQŗ$Gaz*X$[&30p3B8PkO  j:S]0$w#dBxj5X˄>`QaZv5`O.bOVI P46 0(_OC#V&0ݣCSн+h]1B?RJ 3V.p%E,x+KSȔy:6uk iw;˯`9۫G;{wI,>P5i%{iGy;2 [-H"zVL`%uV:5& cb"9phf5xťVP Ҹy2(Z3T|z+>udYʣ+a%Pg@~Zں'| ZDtJ;gNMc P(|S.rEAc m (Ǫ}ƴm'R Zf}1 ` t|gFgftͲF2*o-h'pTz(@ MO' ZT<lGP~M%`;N`;D`r] Q4Ѹ7;2T`g81ngiwO}"Y ۍ0R.A {^y-U'nNo,Om ;I, Y>!V#[zgeT]Z47Dp|nmЄ%P#,=L5j#0 L M.RmuL%0/M:2 %IAMeN0OPrgP%_[}/oIPW`ʏX4It>QZ^Y:;commons-email-1.5-src/src/test/resources/images/contentTypeTest.jpg0100664 0001750 0001750 00000025365 13137110665 027012 0ustar00stefanstefan0000000 0000000 JFIFHHC  !"$"$C3" U !1A"2Qaq #BRu3456789Gbrst$%CWcv1!1Aq"Qa$2R ?xEw qBnjve=R }g$nz f_T2܈%)$h޶yޣ\O' C>DP†:R`ܝ?vlQTboS8WG_uc`9n!BKmhl5.G]t 90MFnKSʐ!sd<RC)C'L*Qmnͽ:SNM8ۜqx + uѢ*;u|;I4ۥ!JJ綕a*d!Vʌ>%X&I^!љ 4 [Rnq\Jz ]=wyvE bo; z ,|JӒ} V2?v+aq4(nU_OexRmCBAלTcVS }}59k٫K5 #jǔ_j6DzM֌_hiM뤈`|^Q?գnm^DTc+?DO᭐Nz3lL~^K^"_@ A=m*FB텡pKWju"=L}h* ¿wőݙUWkIQȒJ8}>P/֝ѿY%⹶ VI+l1?@U}_w5h- bzF[r^XbTL#RT˾zJ7>GwՍpY˩M9곈IO{COoā~}+s{o|6\VSv8m(RJ) vM;}7.IejUN[QK6=Tq BS0`H%E,GiN3N>ᨆȳLn"Ar2V N9scTɤ]@?60p% ĥ'FF mk]݅9aٓ,qKP Rtz4x7sXo$DCmQPPZ~R@00{tɋޝµid6տIPJgV#%A*ꠒx@64c +[gQ`&᥇Ks!ia.$JIc4R{-i]O&yܺiʈŶmAuKNN~HBJ*@M\5 'L{|U:丌HSc_^߆pmܫN1q:2$glMF~z@74ݻ߹vea#S*5|Jq~R P84:ZJ41iq A.;mX^j䬘%w!8]jY˶E"uBI,CvMI^ƄS#/qg¢M#b r#%SR4}ŢlMgQ?R*K<`' 9Ҫ**4ѧlȌ\iҤlFj F3Tĵ6D$[ҕ(d%c'J{å\-SZ((i¤' $rq\O_Mhk b]ʾ] "j-+*h.7 9 ۹u{\)Er|{=;QhvW[q]P7+'Z鷏&1OHaMBrBq%XHJOarʕክ@=2ǴGmd Rg8΀i'KkšKuVd8VJr$ulj;n4mҲ<yc4Ѩ{COi~ \x:tIĺ SN1=}Yq4ZPRv :˽yGx1NV' !Tr׉{wwjFiTjDm[EB KIRyBU$+Gq]\2OOVW=S+26AI=A#@([}Bv%Z, б% *JR"$$7 mE!LT *R%E-JVqӏO̽d@tGm=sG-F[SZ}TQ(,onaE&BKkltG|{;ʕ.ݮw[;*) 1U#̌JJ}>ì8j}Nw'VOnjrC!攅% CKJ Vk$jgcY]Nin/f(գS?>K-Q.7+넨_B,Ĥee\ul0|$qWL֧Wdǖ%6~קR 2lcsR[O.EjL ϮSQq\Pz7c=}3kqYCBXMYIVVgkr=myK;OO%v땎 Q=[k=BVzxyd+ *@zåx)0S)V2R{iNW׭4P^ߘ['_9}  B#үc7F`" VzPS%oԄ\H<}}t-Yn*ZќBT)$~kќe4(IX@<&,bRj Ry ] r; sPOî_Wb\DdmQ.~n:'Kl%bܫ'ѪtNZJS9Y6Ŧ~Ũn \v Pxlq̀@?CAj/v Ke5: BCd,7lj>:X48a? m !#ɁNv[sBq>##@"Lo=YZLE05; ldqBҢJT2 $k%X*AB#Ma\[u RA'68\miZJr=::IyX9-ZOzh V{gu?:V6aHBRiR6u=NIcUQ?(T$x-t}xt嬶PX) ui갳-n֍k إqĄ$$8)91=0ֵB!(! ){/z@"}a^Na֓!1&>mn)P sSxZvzk]R9:`۟PI:ZQkwHISiqf9?N/%gKQ T`BB<`$FPLjUl*)P2:w}tfi1ڨTO1<[(J)QѠ<ѥf=QU%21J8`dJǮwV>=+L1a8Nt7?uoUG25VE}[u ͉Y[VϼJVA$I\_4)CaHZA "D,u[.eTcS6‹J<{$㾟 iSkrK kRʇȐu?i_d6fۥ:1\|u@${gltmn2UTqn&K [@ B'q {k[yMEǖKIquf 4FPIBI9>hȡݳt՟]2:͓F!P22pR{:B϶\YծDM1R\/ W G\];4Z9}i0 \rs_ _ո_U\MɻMtڋ'k,yĶOQ JHmkZTrRH˦T)*-cLm'C%hk͢REn!I}=cm'kW^ N~]sm+?:tǏ:#ala |hp?1F?ӭF4hѠ a4Do0JV)*Ѓ6S]#B=S##_9*dΩ+f slx)O4)ֲɾ f<紶 jK@}R fzc3onOg}\ گg W|^^vZg(XYVOCӶ.m*dwPQ۸ǯk"өS*#fdU@;Íi#8 [N(6Vc;&jNѩɔwW '^vWr@/.Ho$+#=3ۮNUJ<)w>CSڍ)kz+htRn1=3@W+\aЬ8+Gl{g߷Q"{_ ڵL5a"ˋ4Z'}،wԢh}?T}EZR:R9<ӈm8*Q z~[m3/SxǘqoY\ Ok TԆ J]eya*Spuo*Jzv,ף^Wȶ;"m͸'ǓO9ʋ= T=QA%yp #!)#'UpLiݮR K@ yd SlE5HSk#[A3С\As֡Zgz|hQNY e,j.%i *SI* 8=;RՋ)P-?R Ϡ(I R@VT)$v.&pjyhM9LiE=?{]i!}EM|kg\y$8g!7Mlm9To;n#S) HBBSQ}ۑnãȩ;NIyrRk4ϧ,@C,\Te(QKSOMX6E&m3Tz4!DI}0>}΍uzKMW)o T}yu.!z w9!t^y7oJJOPg=xq&:_WBF9BU]ˆ{`]}IVUگK0aW$Tg 8\Գk&A0%G|G}Éqcdd Ш\BӨNV4cԩEhڛyJ$-* ƥuV-*2] ֡Sϴ:RA):Xֵl6.h5QHTISQ~c&VZz Zf뤸d@#(Ozw6vCܤ7(9>F.ӭ' 88ˈqJ%CA 3o.آĕjz@mOP[m%K^qӐαZVmq5 ƈ–%n8-jJ28_{f+sh4RQm.!+BcNػ]J !*ea.D&]i)-!ĸ":/*n:x;{j@S~ԝ:ێhKm Z֤{ m흗>ԗqϪWZ^&{&m)^:$kR(\J3T Rbˌ\+B+JYC:Ml1ʚrj?e%<$2qM~۹"m@yU& -rT{>-xT8f$/j(@KaJHII'\ZE}z?:a+dzyqQ.qsqﰨ7JcjfYg/,]R6b-C%bPmHRVҖR,$rwm`_mﲡ7DbOg>]ssE;}[UP\G"{!M)$0tN˸µm˷ZKf(_ rs":-2*9#+}BJNջ֥eUۂPbM2f-RYmnЄhJuY*QH :7Sm81]r-jzXOG7@`ظ2Řڪ2ܭKB&pa,4Ouzk@4h4Fhѣ@4h4FkM6BBFQc+ Q*jhxFk ? 2<{ l ^~%8kM%5A.0̤u.*y7W"+ŶѲM9&u&efgSVX˼333۽);U pHYs  tIME  (H#0=IDATx c҆;-EiDh3QVM89W_U511oN(bPVu!Knc_狌͙} ΟMFlIpwKno\6d2v(=I|Ǥ;&nNGxÉ69kzv<ٍ 5Aao{|doIOI^)Gc'dhF(CbGM6ֱ}=щrp;g~4emVax}0w;nsdMv&bMCmi!dxQ%&bdd(iJixL@ B wgtwކ~ PF:`k7 w~0pQJHB"ͪ ^Y/DH۝^岳 |Ց(;|+)Ԃl C1fTdzΡgJH@Qd@>(C#s7x9ISo/(Q^I'ȾXLn_! dh G *6 6iA`#/r#,.h`{scfDX=elĢҎ, 9gvE٤r:̞QjFbS{dT ~j⊬O0?ͲSҢ]zWTEU=Dɏ%q5to-F߿ (JÉ](X};JV+v!SX6;B=g dT ' C~d̒[?S$\HNKGgn l+ +f"AGb!pQ3hK/WS<=<7 2bc; +Gtryå)2T,HeCW/zjTM! NȮױYEz0!^̏F1(Yn Z˕}2p qU9@gFҵc*Ǵr̈W_!2L!X)؞Qj<=Lƾd!Ь&e&#.AD !dO&''@ Ɖr,X{ cu,+uQt>.\EWVdJ%tH8N6dP*?cI2V6JZ\8pl5#JU^jڡR N' .' zbzJKӸ2g\|m Nf1A×;_^DẅGY1 Nyq.R{(6e -ԧ^1|'`ǥ(=~C[ Fil#E$MENJ z/ Ig4o8Gn=Ẽk%TϋyZ׿,;q؇`Dw*Uehu ̗F}ft[[MsYzYX8F4kkps dsliA@h ݈!'AĄ9^ dn׭k#R A!>q.dO)piɥ11\>S8U2870'2e2oHO87mӎ͏ $y@$VW 4"&5U 3XK%B>Z]|FmB]rtDV K QS!{>#}3J݂ I2dT}sռa5m,۟cYoSOejHN Q==,HJ) 8.40 O!1[uOj*s7<Ncðdac9MJa!^L[AP맩N2karA f3Tt bRd$އ$m@s+p8&/? jAE1A,r<V)'1o~Ӳ56 G#&Tr~WǑA]ټ",S,/F^9+Gz-STv& 3M=7yhF& t}vhocFܴrB#tᩜ+;F#HiƲQ:czq1 a,; T_&4EMԺaӷ 3wq@?(X.a[;}zW)JSn821-)AEw؛Ͷl^خmsU~TvJO7ظa7q nX袊װ5v.5b%}2OlcLRe1Jٴ}oQSEM`ۛ9P4G7lR|k8ɇ7O;dd|E>~DhN.lVBNHDp84k|]+v~.6=tW~&0THJol{@,F#DžXF`&M+WO>MyJ׈V )d&kb>cdIENDB`commons-email-1.5-src/src/test/resources/images/logos/maven-feather.png0100664 0001750 0001750 00000006402 13137110665 027476 0ustar00stefanstefan0000000 0000000 PNG  IHDRZ#/ pHYs.#.#x?vgAMA|Q cHRMz%u0`:o_F xIDATxb`H  FFblnڳg!߿?x8ߟ? XQtƍ.[LL,##CAAM'O\WW7eooog o߾1cFuu5ABCC&=qߟ7j%7<Ճ Jϟ?yfZZZJJ ''gpp0666mmm c߾}o޼ٰaCoo/\۷oh'.33 366^zW<{sb['>>׌}'|vJzdt9&^=bpE@@*;;ɓ'@ٳg_~ȸz… 1y]>ucǎMO}}ŋդI._ sUU߿֭[@`&F˖-Ѽ}OgU:̪M͟"oo3.?Ú)Jz֝U ݽ?  XTwΝV8P^^2555sa`dxyyZtuu&>}:77䘘ٵk׳gϘ /ԁ&&& 7lxɞ[1K3+J2>eggaA3|~9gǚ37Va㖕e$)8QWW:9s$&&Q T#** 2p XX T`vww[...( ,b`\|1g]*˟ y|?';#?FAvVN=\JzK_`r|y9 y0*r Krp&@!!!'= ~a4)))`2??s;y>/~œO}]_EҜ;q֏, _~:ZGpYGLL"R&X "68~ X@=y`Vd@a?~@9w܃T_\\ ,**rttQUU&+XX@V%=ygO}{;vo/q?Blߘ$lY[{ET8u/NW*pGQ9X*))S{zzXX nnnSS &ܹRkߜ`1  SBl?~rr2<8]>5[V:rn_bz΢U1w?`M=%C.?2~3o=cS@J%+* l71~ ` L u}ߏot?#+'3'&.&L,18 .9}$,f.qfIvvF~t@ X#}݅ÃT~߽~ϯ9}9Y/A2L?M}a]X!DQp Q`'<% ?."T/|ݛ?~{˯nN%A/lls1?l\\<4t3@AM$]VM/` X.B`kXpk޼yR {:"!8Ab 6sssC+u31~QtH#0W ,Ae bh0Zʅ r6"„NSTOr?]PXm;8pKm6{0XbDغ FLKK &R`T4 XkC2`O08 t1#+}@.0^|  c",M7Bv "2<܁l`O!|`[˗/ `Kn.ЕGkY`2`ߙ1> eC`]N3,]UH:t*)$Kxǧ(@ĉᝫOB[l[80??{Ύǖ6$0Ctmذȝ9s& A Ağ AjRRDWcc#XHKx= b9`At+&&owK `3¾r ydx).`xoG€'Q @Cl?{,d0YjT i' ϹV@,D>'OB FV¿ _AVQΐ[) ~102@ԫ[&MD ةb `ρU;$tAvҒO۷oGͭϣ ""$0!xW2002x~"E^Q'+**Acٲeh-1HR0D@5L ρ5Ç ϯ_G `8FED tk.`3 #I… !UV eҥKAQXtApg!9L,l < _߃s-4!##4dD5d= oBB TWbqqq`:@dgF< J@Cх  @q 0*DF̬L> lNΧϮ3Z32rqt1;& H &-THsF0cyyypM^w" (hkkKL } 'ƒ]I@G':`={`Tpr3|~, | HKH`|\v H= ,V^V+*HA< `vY8 P@4P@Z':vrIENDB`commons-email-1.5-src/src/test/resources/images/contentTypeTest.gif0100664 0001750 0001750 00000013352 13137110665 026770 0ustar00stefanstefan0000000 0000000 GIF89a3OZ1DDDGZ }\RvwwFh78N> Q*jhxFk ? 2<{ l ^~%8kM%5A.0̤u.*y7W"+ŶѲM9&u&efgSVX˼333۽)!,3pH,Ȥrl:ШtJZجvz$.znE~R+?&$}e>>3N.-&?)$th>M&+-' 8C!;?# <Ä'QBNф^ŕb'I'48?8"# 2%;;ۍߪ\Lt8pUjPHF`F WN3NKtPo*GH#Z@#(kףx `DG$ YTNS5@ TQXDԓ}N3 ' Z$A#(F;=ƃ*^Xl/٭Bm* S>L6! Sg.,pҢ@*3r=YU` }j28w^S 4xaG>X%h*ᒘ&@2 d]: gj}M$6EgiyV PB -0dA9PA^{_P :1 GxCH$\L4؁QMA 0D@P25tS*5 A~HYH 'cI6*34DDjD 4lT&q]2&w @1DyB5eD D8&nQY.C .I% -0R%;; ``O6؁bdx"? M% R3O5:gR p# mGS-V DnmUMB>xT&u#Hg̮Wm9'2lۚ1^?bQC'l( m[F$ . pbfPVW6I`~pˮ胳>l*$ '0>lT0[+GMR\U 18R 5yg*ڷ-̵geӱ BTUDuEĪiEm@`@6c*Wο; h]cl4YXuJ@ oxv;~mc)~S  Sx9`\A9zZ'WT߈C&:M<0L4 a'&fȠЄ`G9}PatH/N׬ B2I@۔@>![>$k+1xȖipBX>"x=@󈰔U̎"]E8QQ-TהA<ԪB `OBչd*3YQQs8&dKQ uv =gІ83J KRb]+BMUJ3@`f0O^!ʘ@q(Eր8N3&)"0B-{"NDsCW8-C(8bKTX@^RAITL@fu$b]!S/0̆n;0* p.4i&1S][9mfWT+Z!pUD`J gH@1S;X8 Zt%YFrTYtV)7wDLU^`8+ e|KPn@ X =_ 9tf5*Jiq*{kYؓJ: IN?dMVw#EWN vRaOH;u[]i%Cf9K Sԇ6u0_0OTxd0k$;%HV" lȭ> 83E@v1 0$@t* .'f0JZjeť+H\bI7.EGT~dc,eⳜWH6돗+ȬVA|-Ĕŀ} !>*Q&@ Fh@P]h= .Ug4;uFDX\\$c f$uɫ }H:vQvHL.tQ W$.n D 8Hf3 Ze^U3eBAs^rK#xyg8 P 4`i%ĩ5Rj6F\ ʲG!C0a FRZD$pw{*oZ);_Պ o!({c~Ug8AUR6P ^`f A!l){_q9@e |\4`%~9TUynDK=IZ{$?YeHd'%+GwQ,2Ћ(wpYB&QZpQWЌ'p?]%&M ݰ?f- |33A8US'e)XS傦X3+!xȗ|#m `#0Thp[ q@$I$@h:` @8KdfY9Y8e_G|0Fti36;`L `P. e"yXe @8B BCULgY?4S5eŖt.ES!t+CY`!SiN|0a`ZRp@3?Pv!P1*Xl5\eXS_9E)b;q3#; |2 ^ĘIЛJJ`%}??)Wb(2T?[R/D೥$V Hǚ.LK-S.`GoU@[R , !ڥQŗ$Gaz*X$[&30p3B8PkO  j:S]0$w#dBxj5X˄>`QaZv5`O.bOVI P46 0(_OC#V&0ݣCSн+h]1B?RJ 3V.p%E,x+KSȔy:6uk iw;˯`9۫G;{wI,>P5i%{iGy;2 [-H"zVL`%uV:5& cb"9phf5xťVP Ҹy2(Z3T|z+>udYʣ+a%Pg@~Zں'| ZDtJ;gNMc P(|S.rEAc m (Ǫ}ƴm'R Zf}1 ` t|gFgftͲF2*o-h'pTz(@ MO' ZT<lGP~M%`;N`;D`r] Q4Ѹ7;2T`g81ngiwO}"Y ۍ0R.A {^y-U'nNo,Om ;I, Y>!V#[zgeT]Z47Dp|nmЄ%P#,=L5j#0 L M.RmuL%0/M:2 %IAMeN0OPrgP%_[}/oIPW`ʏX4It>QZ^Y:;commons-email-1.5-src/src/test/java/org/apache/commons/mail/settings/package.html0100664 0001750 0001750 00000001551 13137110665 031313 0ustar00stefanstefan0000000 0000000

This package provides the test mail server configuration.

commons-email-1.5-src/src/test/java/org/apache/commons/mail/settings/EmailConfiguration.java0100664 0001750 0001750 00000005456 13137110665 033464 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.settings; import org.apache.commons.mail.EmailConstants; /** * This class contains hard-coded configuration settings * for the JUnit tests. * * @since 1.0 */ public final class EmailConfiguration { // when using GMail for testing the following combination work // // port 587 - MAIL_USE_STARTTLS, MAIL_STARTTLS_REQUIRED, MAIL_SERVER=smtp.gmail.com // port 465 - MAIL_USE_SSL // when using GMX for testing the following combination work // // port 465 - MAIL_USE_SSL, -Dsun.security.ssl.allowUnsafeRenegotiation=true // when using Office 365 for testing the following combination work // // port 25 - MAIL_USE_STARTTLS, MAIL_STARTTLS_REQUIRED // port 587 - MAIL_USE_STARTTLS, MAIL_STARTTLS_REQUIRED public static final boolean MAIL_FORCE_SEND = false; public static final boolean MAIL_DEBUG = false; public static final String MAIL_CHARSET = EmailConstants.UTF_8; public static final String MAIL_SERVER = "localhost"; public static final int MAIL_SERVER_PORT = 25; public static final String TEST_FROM = "test_from@apache.org"; public static final String TEST_TO = "test_to@apache.org"; public static final String TEST_USER = "user"; public static final String TEST_PASSWD = "password"; public static final boolean MAIL_USE_SSL = false; public static final boolean MAIL_SSL_CHECKSERVERIDENTITY = false; public static final boolean MAIL_USE_STARTTLS = true; public static final boolean MAIL_STARTTLS_REQUIRED = true; public static final String TEST_URL = EmailConfiguration.class .getResource("/images/asf_logo_wide.gif") .toExternalForm(); /** Amount of time to wait for Dumbster to start up */ public static final int TIME_OUT = 500; } commons-email-1.5-src/src/test/java/org/apache/commons/mail/EmailUtilsTest.java0100664 0001750 0001750 00000004577 13137110666 030761 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.assertEquals; import java.io.UnsupportedEncodingException; import org.junit.Test; /** * JUnit test case for EmailUtils Class * * @since 1.3 */ public class EmailUtilsTest { @Test public void testClearEndOfLineCharacters() { assertEquals(null, EmailUtils.replaceEndOfLineCharactersWithSpaces(null)); assertEquals("", EmailUtils.replaceEndOfLineCharactersWithSpaces("")); assertEquals(" ", EmailUtils.replaceEndOfLineCharactersWithSpaces(" ")); assertEquals("abcdefg", EmailUtils.replaceEndOfLineCharactersWithSpaces("abcdefg")); assertEquals("abc defg", EmailUtils.replaceEndOfLineCharactersWithSpaces("abc\rdefg")); assertEquals("abc defg", EmailUtils.replaceEndOfLineCharactersWithSpaces("abc\ndefg")); assertEquals("abc defg", EmailUtils.replaceEndOfLineCharactersWithSpaces("abc\r\ndefg")); assertEquals("abc defg", EmailUtils.replaceEndOfLineCharactersWithSpaces("abc\n\rdefg")); } @Test public void testUrlEncoding() throws UnsupportedEncodingException { assertEquals("abcdefg", EmailUtils.encodeUrl("abcdefg")); assertEquals("0123456789", EmailUtils.encodeUrl("0123456789")); assertEquals("Test%20CID", EmailUtils.encodeUrl("Test CID")); assertEquals("joe.doe@apache.org", EmailUtils.encodeUrl("joe.doe@apache.org")); assertEquals("joe+doe@apache.org", EmailUtils.encodeUrl("joe+doe@apache.org")); assertEquals("peter%26paul%26mary@oldmusic.org", EmailUtils.encodeUrl("peter&paul&mary@oldmusic.org")); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/InvalidAddressTest.java0100664 0001750 0001750 00000012505 13137110665 031572 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.fail; import org.apache.commons.mail.mocks.MockEmailConcrete; import org.junit.Before; import org.junit.Test; /** * JUnit test case for invalid Addresses in Email Class * * @since 1.0 */ public class InvalidAddressTest extends AbstractEmailTest { /** */ private static final String [] ARR_INVALID_EMAILS = { "local name@domain.com", "local(name@domain.com", "local)name@domain.com", "localname@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@domaincom", "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" }; private MockEmailConcrete email; @Before public void setUpInvalidAddressTest() { // reusable objects to be used across multiple tests this.email = new MockEmailConcrete(); } @Test public void testSetInvalidFrom() throws Exception { // ==================================================================== // Test setting invalid 'from' addresses // ==================================================================== 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) { // Expected Result } } } @Test public void testAddInvalidTo() throws Exception { // ==================================================================== // Test adding invalid 'to' addresses // ==================================================================== 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) { // Expected Result } } } @Test public void testAddInvalidCc() throws Exception { // ==================================================================== // Test adding invalid 'cc' addresses // ==================================================================== 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) { // Expected Result } } } @Test public void testAddInvalidBcc() throws Exception { // ==================================================================== // Test adding invalid 'Bcc' addresses // ==================================================================== 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) { // Expected Result } } } } ././@LongLink0100644 0000000 0000000 00000000152 13137110665 011634 Lustar 0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceClassPathResolverTest.javacommons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceClassPathResolverTest0100664 0001750 0001750 00000005021 13137110665 035171 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import static org.junit.Assert.*; import org.apache.commons.mail.DataSourceResolver; import org.junit.Test; import java.io.IOException; /** * JUnit test case for DataSourceClassPathResolver. * * @since 1.3 */ public class DataSourceClassPathResolverTest extends AbstractDataSourceResolverTest { @Test public void testResolvingClassPathLenient() throws Exception { DataSourceResolver dataSourceResolver; dataSourceResolver = new DataSourceClassPathResolver("/", true); assertTrue(toByteArray(dataSourceResolver.resolve("images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("./images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("/images/asf_logo_wide.gif")).length == IMG_SIZE); assertNull(dataSourceResolver.resolve("/asf_logo_wide.gif")); dataSourceResolver = new DataSourceClassPathResolver("/images", true); assertTrue(toByteArray(dataSourceResolver.resolve("asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("./asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("/asf_logo_wide.gif")).length == IMG_SIZE); assertNull(dataSourceResolver.resolve("./images/asf_logo_wide.gif")); } @Test(expected = IOException.class) public void testResolvingClassPathNonLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceClassPathResolver("/", false); assertNotNull(dataSourceResolver.resolve("images/asf_logo_wide.gif")); dataSourceResolver.resolve("asf_logo_wide.gif"); } } ././@LongLink0100644 0000000 0000000 00000000152 13137110665 011634 Lustar 0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceCompositeResolverTest.javacommons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceCompositeResolverTest0100664 0001750 0001750 00000005672 13137110665 035265 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import static org.junit.Assert.*; import org.apache.commons.mail.DataSourceResolver; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.net.URL; /** * JUnit test case for DateSourceResolver. * * @since 1.3 */ public class DataSourceCompositeResolverTest extends AbstractDataSourceResolverTest { private DataSourceResolver[] dataSourceResolvers; @Before public void setUp() throws Exception { final DataSourceUrlResolver urlResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), false); final DataSourceClassPathResolver classPathResolver = new DataSourceClassPathResolver("/images", false); dataSourceResolvers = new DataSourceResolver[] { urlResolver, classPathResolver }; } @Test public void testResolvingFilesLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceCompositeResolver(dataSourceResolvers, true); // resolve using HTTP assertTrue(toByteArray(dataSourceResolver.resolve("/images/feather-small.gif")).length > 0); // resolve using class path assertTrue(toByteArray(dataSourceResolver.resolve("/contentTypeTest.gif")).length > 0); } @Test(expected = IOException.class) public void testResolvingFilesNonLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceCompositeResolver(dataSourceResolvers, false); dataSourceResolver.resolve("./image/does-not-exist.gif"); } @Test public void testExternalModification() throws Exception { final DataSourceCompositeResolver dataSourceResolver = new DataSourceCompositeResolver(dataSourceResolvers, true); final DataSourceResolver[] arr = dataSourceResolver.getDataSourceResolvers(); // modify an element in the returned array arr[0] = null; final DataSourceResolver[] arr2 = dataSourceResolver.getDataSourceResolvers(); // assert that the external modification is not propagated to the internal array assertNotNull(arr2[0]); } } ././@LongLink0100644 0000000 0000000 00000000145 13137110665 011636 Lustar 0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceFileResolverTest.javacommons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceFileResolverTest.java0100664 0001750 0001750 00000004311 13137110665 035107 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import org.apache.commons.mail.DataSourceResolver; import org.junit.Test; /** * JUnit test case for DateSourceResolver. * * @since 1.3 */ public class DataSourceFileResolverTest extends AbstractDataSourceResolverTest { @Test public void testResolvingFileLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceFileResolver(new File("./src/test/resources"), true); assertTrue(toByteArray(dataSourceResolver.resolve("images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("./images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("../resources/images/asf_logo_wide.gif")).length == IMG_SIZE); assertNull(toByteArray(dataSourceResolver.resolve("/images/does-not-exist.gif"))); assertNull(dataSourceResolver.resolve("./images/does-not-exist.gif")); } @Test(expected = IOException.class) public void testResolvingFileNonLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceFileResolver(new File("."), false); assertNotNull(dataSourceResolver.resolve("./src/test/resources/images/asf_logo_wide.gif")); dataSourceResolver.resolve("asf_logo_wide.gif"); } } ././@LongLink0100644 0000000 0000000 00000000151 13137110665 011633 Lustar 0000000 0000000 commons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/AbstractDataSourceResolverTest.javacommons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/AbstractDataSourceResolverTest.0100664 0001750 0001750 00000002640 13137110665 035134 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import java.io.IOException; import java.io.InputStream; import javax.activation.DataSource; import org.apache.commons.io.IOUtils; public abstract class AbstractDataSourceResolverTest { protected final int IMG_SIZE = 5866; protected byte[] toByteArray(final DataSource dataSource) throws IOException { if(dataSource != null) { final InputStream is = dataSource.getInputStream(); try { return IOUtils.toByteArray(is); } finally { is.close(); } } return null; } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/resolver/DataSourceUrlResolverTest.java0100664 0001750 0001750 00000006332 13137110665 034777 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import static org.junit.Assert.*; import org.apache.commons.mail.DataSourceResolver; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.URL; /** * JUnit test case for DataSourceUrlResolver. * * @since 1.3 */ public class DataSourceUrlResolverTest extends AbstractDataSourceResolverTest { /** * Shows how the DataSourceUrlResolver can resolve files as well but this should * be done using a DataSourceFileResolver. * * @throws Exception the test failed */ @Test public void testResolvingFilesLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new File("./src/test/resources").toURI().toURL(), true); assertTrue(toByteArray(dataSourceResolver.resolve("images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("./images/asf_logo_wide.gif")).length == IMG_SIZE); assertNull(dataSourceResolver.resolve("./images/does-not-exist.gif")); assertNull(dataSourceResolver.resolve("/images/asf_logo_wide.gif")); } /** * Tests resolving resources over HTTP. * * @throws Exception the test failed */ @Test public void testResolvingHttpLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), true); assertTrue(toByteArray(dataSourceResolver.resolve("http://www.apache.org/images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("./images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("/images/feather-small.gif")).length > 1); assertNull(toByteArray(dataSourceResolver.resolve("/images/does-not-exist.gif"))); } /** * Tests resolving resources over HTTP. * * @throws Exception the test failed */ @Test(expected = IOException.class) public void testResolvingHttpNonLenient() throws Exception { final DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), false); assertNotNull(dataSourceResolver.resolve("images/asf_logo_wide.gif")); dataSourceResolver.resolve("images/does-not-exist.gif"); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/EmailLiveTest.java0100664 0001750 0001750 00000035764 13137110666 030562 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.activation.DataSource; import javax.activation.URLDataSource; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.mail.resolver.DataSourceUrlResolver; import org.apache.commons.mail.settings.EmailConfiguration; import org.junit.Before; import org.junit.Test; /** * 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). */ public class EmailLiveTest extends AbstractEmailTest { @Before public void setUpLiveTest() { // enforce a default charset UTF-8 otherwise non-ASCII attachment names will not work System.setProperty("mail.mime.charset", "utf-8"); // enforce encoding of non-ASCII characters (violating the MIME specification - see // http://java.sun.com/products/javamail/javadocs/javax/mail/internet/package-summary.html System.setProperty("mail.mime.encodefilename", "true"); } protected Email send(final Email email) throws EmailException { if( EmailConfiguration.MAIL_FORCE_SEND ) { email.send(); } else { email.buildMimeMessage(); } return email; } protected String getFromUrl(final URL url) throws Exception { final URLDataSource dataSource = new URLDataSource(url); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), baos); return new String(baos.toByteArray(), "UTF-8"); } /** * Factory method to create a pre-configured email instance. * * @param clazz the requested implementation class * @return the new instance * @throws Exception creating the Email instance failed */ private Email create(final Class clazz) throws Exception { final Email email = clazz.newInstance(); email.setStartTLSEnabled(EmailConfiguration.MAIL_USE_STARTTLS); email.setStartTLSRequired(EmailConfiguration.MAIL_STARTTLS_REQUIRED); email.setSSLOnConnect(EmailConfiguration.MAIL_USE_SSL); email.setSSLCheckServerIdentity(EmailConfiguration.MAIL_SSL_CHECKSERVERIDENTITY); email.setHostName(EmailConfiguration.MAIL_SERVER); email.setSmtpPort(EmailConfiguration.MAIL_SERVER_PORT); email.setBounceAddress(EmailConfiguration.TEST_FROM); email.setDebug(EmailConfiguration.MAIL_DEBUG); email.setCharset(EmailConfiguration.MAIL_CHARSET); email.setFrom(EmailConfiguration.TEST_FROM); email.addTo(EmailConfiguration.TEST_TO); if(EmailConfiguration.TEST_USER != null) { email.setAuthenticator(new DefaultAuthenticator(EmailConfiguration.TEST_USER, EmailConfiguration.TEST_PASSWD)); } return email; } // ====================================================================== // Start of Tests // ====================================================================== /** * A sanity check that a simple email also works in reality. * * @throws Exception the test failed */ @Test 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()); } /** * A sanity check that a header folding works correctly. * * @throws Exception the test failed */ @Test 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()); } /** * A sanity check that a simple email also works in reality. * * @throws Exception the test failed */ @Test 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()); } /** * This test checks the various options of building a HTML email. * * https://issues.apache.org/jira/browse/EMAIL-65 * * @throws Exception the test failed */ @Test public void testHtmlMailMimeLayout() throws Exception { String textMsg; String htmlMsg; // prepare attachments String cid; final URL url = new URL(EmailConfiguration.TEST_URL); final File imageFile = new File("./src/test/resources/images/asf_logo_wide.gif"); final EmailAttachment attachment = new EmailAttachment(); final File attachmentFile = new File("./src/test/resources/attachments/logo.pdf"); attachment.setName("logo.pdf"); attachment.setDescription("The official Apache logo"); attachment.setPath(attachmentFile.getAbsolutePath()); // 1) text + html content final HtmlEmail htmlEmail1 = (HtmlEmail) create(HtmlEmail.class); textMsg = "Your email client does not support HTML messages"; htmlMsg = "This is a HTML message without any image"; 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()); // 2) text + html content + image as attachment final HtmlEmail htmlEmail2 = (HtmlEmail) create(HtmlEmail.class); textMsg = "Your email client does not support HTML messages"; htmlMsg = "This is a HTML message with an image 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" ); EmailUtils.writeMimeMessage( new File("./target/test-emails/htmlemail2.eml"), send(htmlEmail2).getMimeMessage()); // 3) text + html content + inline image final HtmlEmail htmlEmail3 = (HtmlEmail) create(HtmlEmail.class); textMsg = "Your email client does not support HTML messages"; cid = htmlEmail3.embed(imageFile, "Apache Logo"); htmlMsg = "This is a HTML message with an inline image - and NO attachment"; 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()); // 4) text + html content + inline image + attachment final HtmlEmail htmlEmail4 = (HtmlEmail) create(HtmlEmail.class); textMsg = "Your email client does not support HTML messages"; cid = htmlEmail4.embed(imageFile, "Apache Logo"); htmlMsg = "This is a HTML message with an inline image - and 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()); } /** * 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 { // U+03B1 : GREEK SMALL LETTER ALPHA // U+03B2 : GREEK SMALL LETTER BETA // U+03B3 : GREEK SMALL LETTER GAMMA final String subject = "[email] 5.Test: Subject with three greek UTF-8 characters : \u03B1\u03B2\u03B3"; final String textMsg = "My test body with with three greek UTF-8 characters : \u03B1\u03B2\u03B3\n"; final String attachmentName = "\u03B1\u03B2\u03B3.txt"; // make sure to set the charset before adding the message content final MultiPartEmail email = (MultiPartEmail) create(MultiPartEmail.class); email.setSubject(subject); email.setMsg(textMsg); // create a proper UTF-8 sequence for the text attachment (matching our default charset) final DataSource attachment = new javax.mail.util.ByteArrayDataSource(textMsg.getBytes("utf-8"), "text/plain"); email.attach(attachment, attachmentName, "Attachment in Greek"); EmailUtils.writeMimeMessage( new File("./target/test-emails/correct-encoding.eml"), send(email).getMimeMessage()); } /** * Test sending a image HTML mail bases on a local HTML page and local image. * * @throws Exception the test failed */ @Test 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"); final String htmlMsg1 = FileUtils.readFileToString(htmlFile, "ISO-8859-1"); final ImageHtmlEmail email = (ImageHtmlEmail) create(ImageHtmlEmail.class); email.setDataSourceResolver(new DataSourceUrlResolver(htmlFile.getParentFile().toURI().toURL(), false)); email.setSubject("[testImageHtmlEmail] 1.Test: simple html content"); email.setHtmlMsg(htmlMsg1); 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. * * @throws Exception the test failed */ @Test public void testImageHtmlEmailRemote() throws Exception { if(EmailConfiguration.MAIL_FORCE_SEND) { final URL url = new URL("http://commons.apache.org/email/"); // URL url = new URL("http://www.dzone.com/links/index.html"); final String htmlMsg = getFromUrl(url); final ImageHtmlEmail email = (ImageHtmlEmail) create(ImageHtmlEmail.class); email.setDataSourceResolver(new DataSourceUrlResolver(url, true)); email.setSubject("[testImageHtmlEmail] 2.Test: complex html content"); email.setHtmlMsg(htmlMsg); 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 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 { final List emails = new ArrayList(); // we need to instantiate an email to provide the mail session - a bit ugly final Session session = create(SimpleEmail.class).getMailSession(); final Transport transport = session.getTransport(); // simulate creating a bunch of emails using an existing mail session for(int i = 0; i<3; i++) { final SimpleEmail personalizedEmail = (SimpleEmail) create(SimpleEmail.class); personalizedEmail.setMailSession(session); personalizedEmail.setSubject("Personalized Test Mail Nr. " + i); personalizedEmail.setMsg("This is a personalized test mail ... :-)"); personalizedEmail.buildMimeMessage(); emails.add(personalizedEmail); } // send the list of emails using a single 'Transport' instance. if( EmailConfiguration.MAIL_FORCE_SEND ) { transport.connect(); 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(); } } /** * Testing if we are able to send a partial email with an invalid address. * * https://issues.apache.org/jira/browse/EMAIL-132 * * @throws Exception the test failed. */ @Test public void testPartialSend() throws Exception { final SimpleEmail email = (SimpleEmail) create(SimpleEmail.class); email.addTo(EmailConfiguration.TEST_TO); email.addTo("nobody@is.invalid"); email.setSubject("TestPartialMail"); email.setMsg("This is a test mail ... :-)"); email.setSendPartial(true); EmailUtils.writeMimeMessage( new File("./target/test-emails/partialmail.eml"), send(email).getMimeMessage()); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/util/MimeMessageParserTest.java0100664 0001750 0001750 00000055463 13137110666 033237 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.List; import java.util.Properties; import javax.activation.DataSource; import javax.mail.Session; import javax.mail.internet.MimeMessage; import org.apache.commons.mail.HtmlEmail; import org.junit.Test; /** * Testing the MimeMessageParser. */ public class MimeMessageParserTest { @Test public void testParseSimpleEmail() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/simple.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Test HTML Send #1 Subject (wo charset)", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertFalse(mimeMessageParser.hasAttachments()); } @Test public void testParseSimpleReplyEmail() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/simple-reply.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Re: java.lang.NoClassDefFoundError: org/bouncycastle/asn1/pkcs/PrivateKeyInfo", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertFalse(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("coheigea@apache.org", mimeMessageParser.getFrom()); assertEquals("dev@ws.apache.org", mimeMessageParser.getReplyTo()); assertFalse(mimeMessageParser.hasAttachments()); } @Test public void testParseHtmlEmailWithAttachments() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/html-attachment.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Test", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertTrue(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNotNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getFrom()); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 2); dataSource = mimeMessageParser.findAttachmentByName("Wasserlilien.jpg"); assertNotNull(dataSource); assertEquals("image/jpeg", dataSource.getContentType()); dataSource = mimeMessageParser.findAttachmentByName("it20one.pdf"); assertNotNull(dataSource); assertEquals("application/pdf", dataSource.getContentType()); } @Test public void testParseHtmlEmailWithAttachmentAndEncodedFilename() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/html-attachment-encoded-filename.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Test HTML Send #1 Subject (w charset)", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertTrue(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNotNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 1); dataSource = mimeMessageParser.getAttachmentList().get(0); assertNotNull(dataSource); assertEquals("text/plain", dataSource.getContentType()); assertEquals("Test Attachment - a>ä, o>ö, u>ü, au>äu", dataSource.getName()); } /** * This test parses an "email read notification" where the resulting data source has no name. Originally * the missing name caused a NPE in MimeUtility.decodeText(). * * @throws Exception the test failed */ @Test public void testParseMultipartReport() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/multipart-report.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Gelesen: ", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertTrue(mimeMessageParser.hasHtmlContent()); assertFalse(mimeMessageParser.hasPlainContent()); assertNull(mimeMessageParser.getPlainContent()); assertNotNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getFrom()); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 1); dataSource = (DataSource) attachmentList.get(0); assertNotNull(dataSource); assertNull(dataSource.getName()); assertEquals("message/disposition-notification", dataSource.getContentType()); } /** * This test parses a SAP generated email which only contains a PDF but no email * text. * * @throws Exception the test failed */ @Test public void testAttachmentOnly() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/attachment-only.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Kunde 100029 Auftrag 3600", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertFalse(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertFalse(mimeMessageParser.hasPlainContent()); assertNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getFrom()); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 1); dataSource = mimeMessageParser.findAttachmentByName("Kunde 100029 Auftrag 3600.pdf"); assertNotNull(dataSource); assertEquals("application/pdf", dataSource.getContentType()); } /** * This test parses an eml file published with issue EMAIL-110. * This eml file has a corrupted attachment but should not create * an OutOfMemoryException. * * @throws Exception the test failed */ @Test public void testParseNoHeaderSeperatorWithOutOfMemory() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/outofmemory-no-header-seperation.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("A corrupt Attachment", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertFalse(mimeMessageParser.hasPlainContent()); assertNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertEquals(mimeMessageParser.getTo().size(), 1); assertEquals(mimeMessageParser.getCc().size(), 0); assertEquals(mimeMessageParser.getBcc().size(), 0); } /** * This test parses an email which contains a text attachment together with email text. * * @throws Exception the test failed */ @Test public void testMultipartTextAttachment() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/multipart-text-attachment.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("test", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 1); dataSource = mimeMessageParser.findAttachmentByName("test.txt"); assertNotNull(dataSource); assertEquals("text/plain", dataSource.getContentType()); } /** * This test parses an email which only contains a text attachment with content-disposition: attachment. * * @throws Exception the test failed */ @Test public void testMultipartTextAttachmentOnly() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/multipart-text-attachment-only.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("test", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertFalse(mimeMessageParser.hasPlainContent()); assertNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 1); dataSource = mimeMessageParser.findAttachmentByName("test.txt"); assertNotNull(dataSource); assertEquals("text/plain", dataSource.getContentType()); } /** * This test parses an email which contains an html attachment with content-disposition: attachment. * * @throws Exception the test failed */ @Test public void testParseHtmlEmailWithHtmlAttachment() throws Exception { DataSource dataSource; final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/html-attachment-content-disposition.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("test", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); final List attachmentList = mimeMessageParser.getAttachmentList(); assertTrue(attachmentList.size() == 1); dataSource = mimeMessageParser.findAttachmentByName("test.html"); assertNotNull(dataSource); assertEquals("text/html", dataSource.getContentType()); } @Test public void testParseCreatedHtmlEmailWithNoContent() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final HtmlEmail email = new HtmlEmail(); email.setMailSession(session); email.setFrom("test_from@apache.org"); email.setSubject("Test Subject"); email.addTo("test_to@apache.org"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg); mimeMessageParser.parse(); assertEquals("Test Subject", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertFalse(mimeMessageParser.hasPlainContent()); assertNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertFalse(mimeMessageParser.hasAttachments()); } @Test public void testParseCreatedHtmlEmailWithTextContent() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final HtmlEmail email = new HtmlEmail(); email.setMailSession(session); email.setFrom("test_from@apache.org"); email.setSubject("Test Subject"); email.addTo("test_to@apache.org"); email.setTextMsg("My test message"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg); mimeMessageParser.parse(); assertEquals("Test Subject", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertFalse(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertFalse(mimeMessageParser.hasAttachments()); } @Test public void testParseCreatedHtmlEmailWithMixedContent() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final HtmlEmail email = new HtmlEmail(); email.setMailSession(session); email.setFrom("test_from@apache.org"); email.setSubject("Test Subject"); email.addTo("test_to@apache.org"); email.setTextMsg("My test message"); email.setHtmlMsg("

My HTML message

"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg); mimeMessageParser.parse(); assertEquals("Test Subject", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertTrue(mimeMessageParser.hasHtmlContent()); assertTrue(mimeMessageParser.hasPlainContent()); assertNotNull(mimeMessageParser.getPlainContent()); assertNotNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("test_from@apache.org", mimeMessageParser.getFrom()); assertEquals("test_from@apache.org", mimeMessageParser.getReplyTo()); assertFalse(mimeMessageParser.hasAttachments()); } @Test public void testParseInlineCID() throws Exception { final Session session = Session.getDefaultInstance(new Properties()); final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/html-attachment.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(message); mimeMessageParser.parse(); assertEquals("Test", mimeMessageParser.getSubject()); assertNotNull(mimeMessageParser.getMimeMessage()); assertTrue(mimeMessageParser.isMultipart()); assertTrue(mimeMessageParser.hasHtmlContent()); assertNotNull(mimeMessageParser.getHtmlContent()); assertTrue(mimeMessageParser.getTo().size() == 1); assertTrue(mimeMessageParser.getCc().size() == 0); assertTrue(mimeMessageParser.getBcc().size() == 0); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getFrom()); assertEquals("siegfried.goeschl@it20one.at", mimeMessageParser.getReplyTo()); assertTrue(mimeMessageParser.hasAttachments()); assertTrue(mimeMessageParser.getContentIds().contains("part1.01080006.06060206@it20one.at")); assertFalse(mimeMessageParser.getContentIds().contains("part2")); final DataSource ds = mimeMessageParser.findAttachmentByCid("part1.01080006.06060206@it20one.at"); assertNotNull(ds); assertEquals(ds, mimeMessageParser.getAttachmentList().get(0)); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/util/IDNEmailAddressConverterTest.java0100664 0001750 0001750 00000007173 13137110666 034441 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.util; import static org.junit.Assert.assertEquals; import javax.mail.internet.InternetAddress; import org.junit.Test; public class IDNEmailAddressConverterTest { private static final String AUSTRIAN_IDN_EMAIL_ADDRESS = "noreply@d\u00F6m\u00E4in.example"; private static final String CZECH_IDN_EMAIL_ADDRESS = "noreply@\u010Desk\u00E1republika.icom.museum"; private static final String RUSSIAN_IDN_EMAIL_ADDRESS = "noreply@\u0440\u043E\u0441\u0441\u0438\u044F.\u0438\u043A\u043E\u043C.museum"; private static final String GERMAN_IDN_EMAIL_NAME = "noreply@d\u00F6m\u00E4in.example"; private static final String[] IDN_EMAIL_ADDRESSES = { AUSTRIAN_IDN_EMAIL_ADDRESS, CZECH_IDN_EMAIL_ADDRESS, RUSSIAN_IDN_EMAIL_ADDRESS }; private final IDNEmailAddressConverter idnEmailConverter = new IDNEmailAddressConverter(); @Test public void testConvertInvalidEmailAddressToAscii() { assertEquals(null, idnEmailConverter.toASCII(null)); assertEquals("", idnEmailConverter.toASCII("")); assertEquals("@", idnEmailConverter.toASCII("@")); assertEquals("@@", idnEmailConverter.toASCII("@@")); assertEquals("foo", idnEmailConverter.toASCII("foo")); assertEquals("foo@", idnEmailConverter.toASCII("foo@")); assertEquals("@badhost.com", idnEmailConverter.toASCII("@badhost.com")); } @Test public void testIDNEmailAddressToAsciiConversion() { assertEquals("noreply@xn--dmin-moa0i.example", idnEmailConverter.toASCII(AUSTRIAN_IDN_EMAIL_ADDRESS)); assertEquals("noreply@xn--h1alffa9f.xn--h1aegh.museum", idnEmailConverter.toASCII(RUSSIAN_IDN_EMAIL_ADDRESS)); } @Test public void testMultipleIDNEmailAddressToAsciiConversion() { assertEquals("noreply@xn--dmin-moa0i.example", idnEmailConverter.toASCII(idnEmailConverter.toASCII(AUSTRIAN_IDN_EMAIL_ADDRESS))); } @Test public void testNonIDNEmailAddressToAsciiConversion() { assertEquals("me@home.com", idnEmailConverter.toASCII("me@home.com")); } @Test public void testInternetAddressToAsciiConversion() throws Exception { final InternetAddress address = new InternetAddress(idnEmailConverter.toASCII(AUSTRIAN_IDN_EMAIL_ADDRESS)); assertEquals(AUSTRIAN_IDN_EMAIL_ADDRESS, idnEmailConverter.toUnicode(address)); final InternetAddress addressWithPersonalName = new InternetAddress(idnEmailConverter.toASCII(AUSTRIAN_IDN_EMAIL_ADDRESS), GERMAN_IDN_EMAIL_NAME); assertEquals(AUSTRIAN_IDN_EMAIL_ADDRESS, idnEmailConverter.toUnicode(addressWithPersonalName)); } @Test public void testRoundTripConversionOfIDNEmailAddress() { for(final String email : IDN_EMAIL_ADDRESSES) { assertEquals(email, idnEmailConverter.toUnicode(idnEmailConverter.toASCII(email))); } } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/InvalidInternetAddressTest.java0100664 0001750 0001750 00000017562 13137110666 033314 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.lang.reflect.Method; import javax.mail.internet.InternetAddress; import org.junit.Before; import org.junit.Test; /** * JUnit test case demonstrating InternetAddress validation. * * @since 1.0 */ public class InvalidInternetAddressTest extends AbstractEmailTest { /** */ private static final String VALID_QUOTED_EMAIL = "\"John O'Groats\"@domain.com"; /** JavaMail 1.2. does not know about this */ private static Method validateMethod; /** */ private static final String[] ARR_INVALID_EMAILS = { "local name@domain.com", "local(name@domain.com", "local)name@domain.com", "localname@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@domaincom", "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@", "@domain.com" }; /** * Setup for a test */ @Before public void setUpInvalidInternetAddressTest() { try { validateMethod = InternetAddress.class.getMethod("validate", new Class [0]); } catch (final Exception e) { assertEquals("Got wrong Exception when looking for validate()", NoSuchMethodException.class, e.getClass()); } } @Test 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++) { 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) { // Expected Result } } // test valid 'quoted' Email addresses 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()); } } @Test public void testValidateMethod() throws Exception { if (validateMethod == null) { return; } // ==================================================================== // Prove InternetAddress constructor isn't throwing exception and // the validate() method is // ==================================================================== 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 { validateMethod.invoke(address, (Object[]) null); 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()); } } } // test valid 'quoted' Email addresses 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()); } } @Test public void testValidateMethodCharset() throws Exception { if (validateMethod == null) { return; } // ==================================================================== // Prove InternetAddress constructor isn't throwing exception and // the validate() method is // ==================================================================== for (int i = 0; i < ARR_INVALID_EMAILS.length; i++) { final InternetAddress address = new InternetAddress(ARR_INVALID_EMAILS[i], "Joe", "UTF-8"); // 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 { validateMethod.invoke(address, (Object[]) null); 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()); } } } // test valid 'quoted' Email addresses try { validateMethod.invoke(new InternetAddress(VALID_QUOTED_EMAIL, "Joe", "UTF-8"), (Object[]) null); } catch (final Exception ex) { fail("Valid Quoted Email failed: " + VALID_QUOTED_EMAIL + " - " + ex.getMessage()); } } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/MockImageHtmlEmailConcrete.java0100664 0001750 0001750 00000003161 13137110665 034264 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.mocks; import org.apache.commons.mail.ImageHtmlEmail; import java.io.IOException; import javax.mail.MessagingException; /** * Extension of the ImageHtmlEmail Class * (used to allow testing only) */ public class MockImageHtmlEmailConcrete extends ImageHtmlEmail { /** * Retrieve the message content * @return Message Content */ public String getMsg() { try { return this.getPrimaryBodyPart().getContent().toString(); } catch (final IOException ioE) { return null; } catch (final MessagingException msgE) { return null; } } /** * Retrieve the html msg * @return Message Content */ public String getHtmlMsg() { return this.html; } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/MockSimpleEmail.java0100664 0001750 0001750 00000002550 13137110665 032164 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.mocks; import javax.mail.internet.InternetAddress; import org.apache.commons.mail.SimpleEmail; /** * Extension of SimpleEmail Class * (used to allow testing only) * * @since 1.0 */ public class MockSimpleEmail extends SimpleEmail { /** * Retrieve the message content * @return Message Content */ public String getMsg() { return (String) this.content; } /** * @return fromAddress */ @Override public InternetAddress getFromAddress() { return this.fromAddress; } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/MockEmailConcrete.java0100664 0001750 0001750 00000006704 13137110665 032502 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.mocks; import javax.mail.Authenticator; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; 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. * * @since 1.0 */ 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) { // This abstract method should be tested in the concrete // implementation classes only. return null; } /** * Retrieve the current debug setting * @return debug */ public boolean isDebug() { return this.debug; } /** * Retrieve the current authentication setting * @return Authenticator Authenticator */ public Authenticator getAuthenticator() { return this.authenticator; } /** * @return charset */ public String getCharset() { return this.charset; } /** * @return content */ public Object getContentObject() { return this.content; } /** * @return content */ public MimeMultipart getContentMimeMultipart() { return this.emailBody; } /** * @return emailBody */ public MimeMultipart getEmailBody() { return this.emailBody; } /** * @return hostName */ @Override public String getHostName() { return this.hostName; } /** * @return message */ public MimeMessage getMessage() { return this.message; } /** * @return popHost */ public String getPopHost() { return this.popHost; } /** * @return popPassword */ public String getPopPassword() { return this.popPassword; } /** * @return popUsername */ public String getPopUsername() { return this.popUsername; } /** * @return contentType */ public String getContentType() { return contentType; } /** * @return popBeforeSmtp */ public boolean isPopBeforeSmtp() { return popBeforeSmtp; } /** * @return Session * @throws EmailException EmailException */ public Session getSession() throws EmailException { return this.getMailSession(); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/MockHtmlEmailConcrete.java0100664 0001750 0001750 00000003700 13137110665 033320 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.mocks; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import org.apache.commons.mail.HtmlEmail; /** * Extension of the HtmlEmail Class * (used to allow testing only) * * @since 1.0 */ public class MockHtmlEmailConcrete extends HtmlEmail { /** * Retrieve the message content * @return Message Content */ public String getMsg() { try { return this.getPrimaryBodyPart().getContent().toString(); } catch (final IOException ioE) { return null; } catch (final MessagingException msgE) { return null; } } /** * Retrieve the text msg * @return Message Content */ public String getTextMsg() { return this.text; } /** * Retrieve the html msg * @return Message Content */ public String getHtmlMsg() { return this.html; } /** * @return fromAddress */ @Override public InternetAddress getFromAddress() { return this.fromAddress; } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/package.html0100664 0001750 0001750 00000001555 13137110665 030573 0ustar00stefanstefan0000000 0000000

This package provides mock email implementations for testing.

commons-email-1.5-src/src/test/java/org/apache/commons/mail/mocks/MockMultiPartEmailConcrete.java0100664 0001750 0001750 00000003373 13137110665 034343 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.mocks; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import org.apache.commons.mail.MultiPartEmail; /** * Extension of MultiPartEmail Class * (used to allow testing only) * * @since 1.0 */ public class MockMultiPartEmailConcrete extends MultiPartEmail { /** * Retrieve the message content * @return Message Content */ public String getMsg() { try { return this.getPrimaryBodyPart().getContent().toString(); } catch (final IOException ioE) { return null; } catch (final MessagingException msgE) { return null; } } /** */ public void initTest() { this.init(); } /** * @return fromAddress */ @Override public InternetAddress getFromAddress() { return this.fromAddress; } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/HtmlEmailTest.java0100664 0001750 0001750 00000063405 13137110665 030557 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.internet.MimeMessage; import org.apache.commons.mail.mocks.MockHtmlEmailConcrete; import org.apache.commons.mail.settings.EmailConfiguration; import org.apache.commons.mail.util.MimeMessageParser; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * JUnit test case for HtmlEmail Class. * * @since 1.0 */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MockHtmlEmailConcrete.class }) public class HtmlEmailTest extends AbstractEmailTest { private MockHtmlEmailConcrete email; @Before public void setUpHtmlEmailTest() { // reusable objects to be used across multiple tests this.email = new MockHtmlEmailConcrete(); } @Test public void testGetSetTextMsg() throws EmailException { // ==================================================================== // Test Success // ==================================================================== for (final String validChar : testCharsValid) { this.email.setTextMsg(validChar); assertEquals(validChar, this.email.getTextMsg()); } // ==================================================================== // Test Exception // ==================================================================== for (final String invalidChar : this.testCharsNotValid) { try { this.email.setTextMsg(invalidChar); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } } } @Test public void testGetSetHtmlMsg() throws EmailException { // ==================================================================== // Test Success // ==================================================================== for (final String validChar : testCharsValid) { this.email.setHtmlMsg(validChar); assertEquals(validChar, this.email.getHtmlMsg()); } // ==================================================================== // Test Exception // ==================================================================== for (final String invalidChar : this.testCharsNotValid) { try { this.email.setHtmlMsg(invalidChar); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } } } @Test public void testGetSetMsg() throws EmailException { // ==================================================================== // Test Success // ==================================================================== for (final String validChar : testCharsValid) { this.email.setMsg(validChar); assertEquals(validChar, this.email.getTextMsg()); assertTrue( this.email.getHtmlMsg().contains(validChar)); } // ==================================================================== // Test Exception // ==================================================================== for (final String invalidChar : this.testCharsNotValid) { try { this.email.setMsg(invalidChar); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } } } @Test public void testEmbedUrl() throws Exception { // ==================================================================== // Test Success // ==================================================================== 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"); 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"); assertFalse(strEmbed.equals(newCid)); // ==================================================================== // Test Exceptions // ==================================================================== // Does an invalid URL throw an exception? try { this.email.embed(createInvalidURL(), "Bad URL"); fail("Should have thrown an exception"); } catch (final EmailException e) { // expected } // if we try to embed a different URL under a previously used name, // does it complain? 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) { // expected } } @Test public void testEmbedFile() throws Exception { // ==================================================================== // Test Success // ==================================================================== final File file = File.createTempFile("testEmbedFile", "txt"); file.deleteOnExit(); final String strEmbed = this.email.embed(file); assertNotNull(strEmbed); 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); // 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)); } @Test public void testEmbedUrlAndFile() throws Exception { final File tmpFile = File.createTempFile("testfile", "txt"); tmpFile.deleteOnExit(); final String fileCid = this.email.embed(tmpFile); 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)); } @Test 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 { this.email.embed(dataSource, ""); fail("embedding with an empty string for a name should fail"); } catch (final EmailException e) { // expected } // properly embed the datasource final String cid = this.email.embed(dataSource, "testname"); // 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); // 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 { this.email.embed(anotherDS, "testname"); } 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 */ @Test public void testSend() throws EmailException, IOException { final EmailAttachment attachment = new EmailAttachment(); File testFile = null; /** File to used to test file attachments (Must be valid) */ testFile = File.createTempFile("commons-email-testfile", ".txt"); testFile.deleteOnExit(); // ==================================================================== // Test Success // ==================================================================== this.getMailServer(); String strSubject = "Test HTML Send #1 Subject (w charset)"; this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); this.email.addTo(this.strTestMailTo); /** File to used to test file attachmetns (Must be valid) */ attachment.setName("Test Attachment"); attachment.setDescription("Test Attachment Desc"); attachment.setPath(testFile.getAbsolutePath()); this.email.attach(attachment); //this.email.setAuthentication(this.strTestUser, this.strTestPasswd); this.email.setCharset(EmailConstants.ISO_8859_1); this.email.setSubject(strSubject); final URL url = new URL(EmailConfiguration.TEST_URL); final String cid = this.email.embed(url, "Apache Logo"); final String strHtmlMsg = "The Apache logo - "; this.email.setHtmlMsg(strHtmlMsg); 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); // validate html message 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); this.getMailServer(); this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); this.email.addTo(this.strTestMailTo); if (this.strTestUser != null && this.strTestPasswd != null) { this.email.setAuthentication( this.strTestUser, this.strTestPasswd); } strSubject = "Test HTML Send #1 Subject (wo charset)"; this.email.setSubject(strSubject); this.email.setTextMsg("Test message"); 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); } @Test public void testSend2() throws Exception { // ==================================================================== // Test Success // ==================================================================== this.getMailServer(); this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); this.email.addTo(this.strTestMailTo); if (this.strTestUser != null && this.strTestPasswd != null) { this.email.setAuthentication( this.strTestUser, this.strTestPasswd); } String strSubject = "Test HTML Send #2 Subject (wo charset)"; this.email.setSubject(strSubject); this.email.setMsg("Test txt msg"); 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); // validate html message validateSend( this.fakeMailServer, strSubject, this.email.getHtmlMsg(), this.email.getFromAddress(), this.email.getToAddresses(), this.email.getCcAddresses(), this.email.getBccAddresses(), false); this.getMailServer(); this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setFrom(this.strTestMailFrom); this.email.setSmtpPort(this.getMailServerPort()); this.email.addTo(this.strTestMailTo); if (this.strTestUser != null && this.strTestPasswd != null) { this.email.setAuthentication( this.strTestUser, this.strTestPasswd); } strSubject = "Test HTML Send #2 Subject (w charset)"; this.email.setCharset(EmailConstants.ISO_8859_1); this.email.setSubject(strSubject); this.email.setMsg("Test txt msg"); 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); // validate html message 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 { // 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 // might not have the expected result. // ==================================================================== // Test Success // ==================================================================== System.setProperty(EmailConstants.MAIL_MIME_CHARSET, "iso-8859-15"); this.getMailServer(); this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); this.email.addTo(this.strTestMailTo); if (this.strTestUser != null && this.strTestPasswd != null) { this.email.setAuthentication( this.strTestUser, this.strTestPasswd); } final String strSubject = "Test HTML Send Subject (w default charset)"; this.email.setSubject(strSubject); this.email.setMsg("Test txt msg ä"); // add non-ascii character, otherwise us-ascii will be used 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); 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. */ @Test public void testAddZipUrl() throws Exception { final String htmlMsg = "Please click on the following link:

" + "
" + "http://paradisedelivery.homeip.net/delivery/?file=3DTZC268X93337.zip" + "

Customer satisfaction is very important for us."; this.getMailServer(); this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); 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); } final String strSubject = "A dot (\".\") is appended to some ULRs of a HTML mail."; this.email.setSubject(strSubject); this.email.setHtmlMsg(htmlMsg); this.email.send(); 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); // make sure that no double dots show up assertTrue(this.email.getHtmlMsg().contains("3DTZC268X93337.zip")); assertFalse(this.email.getHtmlMsg().contains("3DTZC268X93337..zip")); } /** * 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 { final String htmlMsg = "Hello World"; this.email = new MockHtmlEmailConcrete(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); 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); } final String strSubject = "testCallingBuildMimeMessageBeforeSent"; this.email.setSubject(strSubject); this.email.setHtmlMsg(htmlMsg); // this should NOT be called when sending a message this.email.buildMimeMessage(); try { this.email.send(); } catch(final IllegalStateException e) { return; } fail("Expecting an exception when calling buildMimeMessage() before send() ..."); } /** * EMAIL-73 - check that providing a plain text content using setMsg() * creates a plain content and HTML content using {@code
} tags.
     */
    @Test
    public void testSendWithPlainTextButNoHtmlContent() throws EmailException, IOException
    {
        this.getMailServer();

        final String strSubject = "testSendWithPlainTextButNoHtmlContent";

        this.email = new MockHtmlEmailConcrete();
        this.email.setHostName(this.strTestMailServer);
        this.email.setSmtpPort(this.getMailServerPort());
        this.email.setFrom(this.strTestMailFrom);
        this.email.addTo(this.strTestMailTo);
        this.email.setAuthentication(this.strTestUser, this.strTestPasswd);
        this.email.setCharset(EmailConstants.ISO_8859_1);
        this.email.setSubject(strSubject);
        this.email.setMsg("This is a plain text content : <&npsb;>");

        this.email.send();

        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);
    }

    /**
     * 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.
     *
     * 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);
    }

    @Test
    public void testHtmlMailMimeLayout() throws Exception
    {
        assertCorrectContentType("contentTypeTest.gif", "image/gif");
        assertCorrectContentType("contentTypeTest.jpg", "image/jpeg");
        assertCorrectContentType("contentTypeTest.png", "image/png");
    }

    private void assertCorrectContentType(final String picture, final String contentType) throws Exception {
        final HtmlEmail htmlEmail = createDefaultHtmlEmail();
        final String cid = htmlEmail.embed(new File("./src/test/resources/images/" + picture), "Apache Logo");
        final String htmlMsg = "";
        htmlEmail.setHtmlMsg(htmlMsg);
        htmlEmail.buildMimeMessage();

        final MimeMessage mm = htmlEmail.getMimeMessage();
        mm.saveChanges();
        final MimeMessageParser mmp = new MimeMessageParser(mm);
        mmp.parse();

        final List attachments = mmp.getAttachmentList();
        assertEquals("Attachment size", 1, attachments.size());

        final DataSource ds = (DataSource) attachments.get(0);
        assertEquals("Content type", contentType, ds.getContentType());
    }

    private HtmlEmail createDefaultHtmlEmail() throws EmailException {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setHostName(this.strTestMailServer);
        htmlEmail.setSmtpPort(this.getMailServerPort());
        htmlEmail.setFrom("a@b.com");
        htmlEmail.addTo("c@d.com");
        return htmlEmail;
    }
}
commons-email-1.5-src/src/test/java/org/apache/commons/mail/DefaultAuthenticatorTest.java0100664 0001750 0001750 00000003342 13137110665 033014 0ustar00stefanstefan0000000 0000000 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.mail;

import static org.junit.Assert.*;

import javax.mail.PasswordAuthentication;

import org.junit.Test;

/**
 * JUnit test case for DefaultAuthenticator Class.
 *
 * @since 1.0
 */
public class DefaultAuthenticatorTest
{
    @Test
    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());
    }

}
commons-email-1.5-src/src/test/java/org/apache/commons/mail/SendWithAttachmentsTest.java0100664 0001750 0001750 00000014257 13137110665 032625 0ustar00stefanstefan0000000 0000000 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.mail;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.mail.internet.MimeUtility;

import org.apache.commons.mail.mocks.MockHtmlEmailConcrete;
import org.apache.commons.mail.settings.EmailConfiguration;
import org.junit.Before;
import org.junit.Test;

/**
 * JUnit test case verifying bugzilla issue 30973 is fixed.
 *
 * @since 1.0
 */
public class SendWithAttachmentsTest extends AbstractEmailTest
{
    private MockHtmlEmailConcrete email;

    @Before
    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
     */
    @Test
    public void testSendNoAttachments() throws EmailException, IOException
    {
        this.getMailServer();

        final String strSubject = "Test HTML Send #1 Subject (w charset)";

        this.email = new MockHtmlEmailConcrete();
        this.email.setHostName(this.strTestMailServer);
        this.email.setSmtpPort(this.getMailServerPort());
        this.email.setFrom(this.strTestMailFrom);
        this.email.addTo(this.strTestMailTo);

        this.email.setAuthentication(this.strTestUser, this.strTestPasswd);

        this.email.setCharset(EmailConstants.ISO_8859_1);
        this.email.setSubject(strSubject);

        final URL url = new URL(EmailConfiguration.TEST_URL);
        final String cid = this.email.embed(url, "Apache Logo");

        final String strHtmlMsg =
            "The Apache logo - ";

        this.email.setHtmlMsg(strHtmlMsg);
        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);

        // validate html message
        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
     */
    @Test
    public void testSendWAttachments() throws EmailException, IOException
    {
        final EmailAttachment attachment = new EmailAttachment();
        File testFile = null;

        /** File to used to test file attachments (Must be valid) */
        testFile = File.createTempFile("commons-email-testfile", ".txt");

        // ====================================================================
        // Test Success
        // ====================================================================
        this.getMailServer();

        final String strSubject = "Test HTML Send #1 Subject (w charset)";

        this.email = new MockHtmlEmailConcrete();
        this.email.setHostName(this.strTestMailServer);
        this.email.setSmtpPort(this.getMailServerPort());
        this.email.setFrom(this.strTestMailFrom);
        this.email.addTo(this.strTestMailTo);

        /** File to be used to test file attachments (Must be valid) */
        /** Use umlaut characters to test if the filename is properly encoded */
        // use short name to avoid folding. Otherwise need to unfold when checking result.
        attachment.setName("a>ä, o>ö, u>ü, au>äu");
        attachment.setDescription("Test Attachment Desc");
        attachment.setPath(testFile.getAbsolutePath());
        this.email.attach(attachment);

        this.email.setAuthentication(this.strTestUser, this.strTestPasswd);

        this.email.setCharset(EmailConstants.ISO_8859_1);
        this.email.setSubject(strSubject);

        final String strHtmlMsg = "Test Message";

        this.email.setHtmlMsg(strHtmlMsg);
        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);

        // validate html message
        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);
    }

}
commons-email-1.5-src/src/test/java/org/apache/commons/mail/AbstractEmailTest.java0100664 0001750 0001750 00000043417 13137110665 031417 0ustar00stefanstefan0000000 0000000 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.mail;

import static org.easymock.EasyMock.expect;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.replay;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.activation.DataHandler;
import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.mail.settings.EmailConfiguration;
import org.junit.After;
import org.junit.Before;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;

/**
 * Base test case for Email test classes.
 *
 * @since 1.0
 */
public abstract class AbstractEmailTest
{
    /** Padding at end of body added by wiser/send */
    public static final int BODY_END_PAD = 3;

    /** Padding at start of body added by wiser/send */
    public static final int BODY_START_PAD = 2;

    /** Line separator in email messages */
    private static final String LINE_SEPARATOR = "\r\n";

    /** default port */
    private static int mailServerPort = 2500;

    /** The fake Wiser email server */
    protected Wiser fakeMailServer;

    /** Mail server used for testing */
    protected String strTestMailServer = "localhost";

    /** From address for the test email */
    protected String strTestMailFrom = "test_from@apache.org";

    /** Destination address for the test email */
    protected String strTestMailTo = "test_to@apache.org";

    /** Mailserver username (set if needed) */
    protected String strTestUser = "user";

    /** Mailserver strTestPasswd (set if needed) */
    protected String strTestPasswd = "password";

    /** URL to used to test URL attachments (Must be valid) */
    protected String strTestURL = EmailConfiguration.TEST_URL;

    /** Test characters acceptable to email */
    protected String[] testCharsValid =
    {
            " ",
            "a",
            "A",
            "\uc5ec",
            "0123456789",
            "012345678901234567890"
    };

    /** Test characters not acceptable to email */
    protected String[] endOfLineCombinations =
    {
            "\n",
            "\r",
            "\r\n",
            "\n\r",
    };

    /** Array of test strings */
    protected String[] testCharsNotValid = {"", null};

    /** Where to save email output **/
    private File emailOutputDir;

    /** counter for creating a file name */
    private static int fileNameCounter;

    @Before
    public void setUpAbstractEmailTest()
    {
        emailOutputDir = new File("target/test-emails");
        if (!emailOutputDir.exists())
        {
            emailOutputDir.mkdirs();
        }
    }

    @After
    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));
        }

        this.fakeMailServer = null;
    }

    /**
     * Gets the mail server port.
     * @return the port the server is running on.
     */
    protected int getMailServerPort()
    {
        return mailServerPort;
    }

    /**
     * Safe a mail to a file using a more or less unique file name.
     *
     * @param email email
     * @throws IOException writing the email failed
     * @throws MessagingException writing the email failed
     */
    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() );
    }

    /**
     * @param intMsgNo the message to retrieve
     * @return message as string
     */
    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
            {
                return serializeEmailMessage(emailMessage);
            }
            catch (final Exception e)
            {
                // ignore, since the test will fail on an empty string return
            }
        }
        fail("Message not found");
        return "";
    }

    /**
     * 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))
        {
            mailServerPort++;

            this.fakeMailServer = new Wiser();
            this.fakeMailServer.setPort(getMailServerPort());
            this.fakeMailServer.start();

            assertFalse("fake mail server didn't start", isMailServerStopped(fakeMailServer));

            final Date dtStartWait = new Date();
            while (isMailServerStopped(fakeMailServer))
            {
                // test for connected
                if (this.fakeMailServer != null
                    && !isMailServerStopped(fakeMailServer))
                {
                    break;
                }

                // test for timeout
                if (dtStartWait.getTime() + EmailConfiguration.TIME_OUT
                    <= new Date().getTime())
                {
                    fail("Mail server failed to start");
                }
            }
        }
    }

    /**
     * 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 boolSaveToFile true will output to file, false doesnt
     * @return WiserMessage email to check
     * @throws IOException Exception
     */
    protected WiserMessage validateSend(
        final Wiser mailServer,
        final String strSubject,
        final InternetAddress fromAdd,
        final List toAdd,
        final List ccAdd,
        final List 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
            {
                this.saveEmailToFile(emailMessage);
            }
            catch(final MessagingException me)
            {
                final IllegalStateException ise =
                    new IllegalStateException("caught MessagingException during saving the email");
                ise.initCause(me);
                throw ise;
            }
        }

        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.size() > 0)
            {
                assertTrue("got wrong Cc: address from mail",
                    ccAdd.toString().contains(mimeMessage.getHeader("Cc", null)));
            }

            //test bcc address
            if (bccAdd.size() > 0)
            {
                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()");
            ise.initCause(me);
            throw ise;
        }

        return emailMessage;
    }

    /**
     * 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 boolSaveToFile true will output to file, false doesnt
     * @throws IOException Exception
     */
    protected void validateSend(
        final Wiser mailServer,
        final String strSubject,
        final Multipart content,
        final InternetAddress fromAdd,
        final List toAdd,
        final List ccAdd,
        final List bccAdd,
        final boolean boolSaveToFile)
        throws IOException
    {
        // test other properties
        final WiserMessage emailMessage = this.validateSend(
            mailServer,
            strSubject,
            fromAdd,
            toAdd,
            ccAdd,
            bccAdd,
            boolSaveToFile);

        // test message content

        // get sent email content
        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));
    }

    /**
     * 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 boolSaveToFile true will output to file, false doesnt
     * @throws IOException Exception
     */
    protected void validateSend(
        final Wiser mailServer,
        final String strSubject,
        final String strMessage,
        final InternetAddress fromAdd,
        final List toAdd,
        final List ccAdd,
        final List bccAdd,
        final boolean boolSaveToFile)
        throws IOException
    {
        // test other properties
        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));
    }

    /**
     * Serializes the {@link MimeMessage} from the WiserMessage
     * passed in. The headers are serialized first followed by the message
     * body.
     *
     * @param wiserMessage The 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()}
     * @since 1.1
     */
    private String serializeEmailMessage(final WiserMessage wiserMessage)
            throws MessagingException, IOException
    {
        if (wiserMessage == null)
        {
            return "";
        }

        final StringBuffer serializedEmail = new StringBuffer();
        final MimeMessage message = wiserMessage.getMimeMessage();

        // Serialize the headers
        for (final Enumeration headers = message.getAllHeaders(); headers
                .hasMoreElements();)
        {
            final Header header = (Header) headers.nextElement();
            serializedEmail.append(header.getName());
            serializedEmail.append(": ");
            serializedEmail.append(header.getValue());
            serializedEmail.append(LINE_SEPARATOR);
        }

        // Serialize the body
        final byte[] messageBody = getMessageBodyBytes(message);

        serializedEmail.append(LINE_SEPARATOR);
        serializedEmail.append(messageBody);
        serializedEmail.append(LINE_SEPARATOR);

        return serializedEmail.toString();
    }

    /**
     * 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)}.
     * @since 1.1
     */
    private String getMessageBody(final WiserMessage wiserMessage)
            throws IOException
    {
        if (wiserMessage == null)
        {
            return "";
        }

        byte[] messageBody = null;

        try
        {
            final MimeMessage message = wiserMessage.getMimeMessage();
            messageBody = getMessageBodyBytes(message);
        }
        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()");
            ise.initCause(me);
            throw ise;
        }

        return messageBody != null ? new String(messageBody).intern() : "";
    }

    /**
     * Gets the byte making up the body of the message.
     *
     * @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()}
     * @since 1.1
     */
    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);
        dataHandler.writeTo(buffOs);
        buffOs.flush();

        return byteArrayOutStream.toByteArray();
    }

    /**
     * Checks if an email server is running at the address stored in the
     * fakeMailServer.
     *
     * @param fakeMailServer
     *            The server from which the address is picked up.
     * @return true if the server claims to be running
     * @since 1.1
     */
    protected boolean isMailServerStopped(final Wiser fakeMailServer) {
        return !fakeMailServer.getServer().isRunning();
    }
    
    /**
     * Create a mocked URL object which always throws an IOException
     * when the openStream() method is called.
     * 

* Several ISPs do resolve invalid URLs like {@code http://example.invalid} * to some error page causing tests to fail otherwise. * * @return an invalid URL */ protected URL createInvalidURL() throws Exception { final URL url = createMock(URL.class); expect(url.openStream()).andThrow(new IOException()); replay(url); return url; } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/SimpleEmailTest.java0100664 0001750 0001750 00000013724 13137110666 031104 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import org.apache.commons.mail.mocks.MockSimpleEmail; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * JUnit test case for SimpleEmailTest * @since 1.0 */ public class SimpleEmailTest extends AbstractEmailTest { private MockSimpleEmail email; @Before public void setUpSimpleEmailTest() { // reusable objects to be used across multiple tests this.email = new MockSimpleEmail(); } @Test public void testGetSetMsg() throws EmailException { // ==================================================================== // Test Success // ==================================================================== for (final String validChar : testCharsValid) { this.email.setMsg(validChar); assertEquals(validChar, this.email.getMsg()); } // ==================================================================== // Test Exception // ==================================================================== for (final String invalidChar : this.testCharsNotValid) { try { this.email.setMsg(invalidChar); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } } } /** * @throws EmailException when a bad address is set. * @throws IOException when sending fails * TODO Add code to test the popBeforeSmtp() settings */ @Test public void testSend() throws EmailException, IOException { // ==================================================================== // Test Success // ==================================================================== this.getMailServer(); this.email = new MockSimpleEmail(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); this.email.addTo(this.strTestMailTo); if (this.strTestUser != null && this.strTestPasswd != null) { this.email.setAuthentication( this.strTestUser, this.strTestPasswd); } final String strSubject = "Test Msg Subject"; final String strMessage = "Test Msg Body"; this.email.setCharset(EmailConstants.ISO_8859_1); this.email.setSubject(strSubject); this.email.setMsg(strMessage); 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); } @Test @Ignore 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. */ System.setProperty(EmailConstants.MAIL_MIME_CHARSET, "utf-8"); // ==================================================================== // Test Success // ==================================================================== this.getMailServer(); this.email = new MockSimpleEmail(); this.email.setHostName(this.strTestMailServer); this.email.setSmtpPort(this.getMailServerPort()); this.email.setFrom(this.strTestMailFrom); this.email.addTo(this.strTestMailTo); if (this.strTestUser != null && this.strTestPasswd != null) { this.email.setAuthentication( this.strTestUser, this.strTestPasswd); } final String strSubject = "Test Msg Subject"; final String strMessage = "Test Msg Body ä"; // add non-ascii character, otherwise us-ascii will be used this.email.setSubject(strSubject); this.email.setMsg(strMessage); this.email.send(); 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); final String message = getMessageAsString(0); // check that the charset has been correctly set assertTrue(message.toLowerCase().contains("content-type: text/plain; charset=utf-8")); System.clearProperty(EmailConstants.MAIL_MIME_CHARSET); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/package.html0100664 0001750 0001750 00000001526 13137110665 027455 0ustar00stefanstefan0000000 0000000

This package provides the JUnit tests.

commons-email-1.5-src/src/test/java/org/apache/commons/mail/MultiPartEmailTest.java0100664 0001750 0001750 00000031662 13137110665 031574 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.activation.FileDataSource; import javax.activation.URLDataSource; import javax.mail.internet.MimeMultipart; import org.apache.commons.mail.mocks.MockMultiPartEmailConcrete; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * JUnit test case for MultiPartEmail Class. * * @since 1.0 */ @RunWith(PowerMockRunner.class) @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 { // reusable objects to be used across multiple tests this.email = new MockMultiPartEmailConcrete(); testFile = File.createTempFile("testfile", ".txt"); } @Test public void testSetMsg() throws EmailException { // ==================================================================== // Test Success // ==================================================================== // without charset set 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) { this.email.setMsg(validChar); assertEquals(validChar, this.email.getMsg()); } // ==================================================================== // Test Exceptions // ==================================================================== for (final String invalidChar : testCharsNotValid) { try { this.email.setMsg(invalidChar); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } } } /** * @throws EmailException when a bad address or attachment is used * @throws IOException when sending fails */ @Test public void testSend() throws EmailException, IOException { // ==================================================================== // Test Success // ==================================================================== this.getMailServer(); final String strSubject = "Test Multipart Send Subject"; final EmailAttachment attachment = new EmailAttachment(); attachment.setPath(testFile.getAbsolutePath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setName("Test_Attachment"); attachment.setDescription("Test Attachment Desc"); final MockMultiPartEmailConcrete testEmail = new MockMultiPartEmailConcrete(); testEmail.setHostName(this.strTestMailServer); testEmail.setSmtpPort(this.getMailServerPort()); testEmail.setFrom(this.strTestMailFrom); testEmail.addTo(this.strTestMailTo); testEmail.attach(attachment); testEmail.setSubType("subType"); if (EmailUtils.isNotEmpty(this.strTestUser) && EmailUtils.isNotEmpty(this.strTestPasswd)) { testEmail.setAuthentication( this.strTestUser, this.strTestPasswd); } testEmail.setSubject(strSubject); testEmail.setMsg("Test Message"); final Map ht = new HashMap(); ht.put("X-Priority", "2"); ht.put("Disposition-Notification-To", this.strTestMailFrom); ht.put("X-Mailer", "Sendmail"); testEmail.setHeaders(ht); testEmail.send(); this.fakeMailServer.stop(); // validate message 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); // ==================================================================== // Test Exceptions // ==================================================================== try { this.getMailServer(); this.email.send(); fail("Should have thrown an exception"); } catch (final EmailException e) { this.fakeMailServer.stop(); } } @Test public void testAttach() throws Exception { EmailAttachment attachment; // ==================================================================== // Test Success - EmailAttachment // ==================================================================== attachment = new EmailAttachment(); attachment.setName("Test Attachment"); attachment.setDescription("Test Attachment Desc"); attachment.setPath(testFile.getAbsolutePath()); this.email.attach(attachment); assertTrue(this.email.isBoolHasAttachments()); // ==================================================================== // Test Success - URL // ==================================================================== attachment = new EmailAttachment(); attachment.setName("Test Attachment"); attachment.setDescription("Test Attachment Desc"); attachment.setURL(new URL(this.strTestURL)); this.email.attach(attachment); // ==================================================================== // Test Success - File // ==================================================================== this.email.attach(testFile); assertTrue(this.email.isBoolHasAttachments()); // ==================================================================== // Test Exceptions // ==================================================================== // null attachment try { this.email.attach((EmailAttachment) null); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } // bad url attachment = new EmailAttachment(); try { attachment.setURL(createInvalidURL()); this.email.attach(attachment); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } // bad file attachment = new EmailAttachment(); try { attachment.setPath(""); this.email.attach(attachment); fail("Should have thrown an exception"); } 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 */ @Test public void testAttach2() throws MalformedURLException, EmailException { // ==================================================================== // Test Success - URL // ==================================================================== 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"); } @Test public void testAttach3() throws Exception { // ==================================================================== // Test Success - URL // ==================================================================== this.email.attach( new URLDataSource(new URL(this.strTestURL)), "Test Attachment", "Test Attachment Desc"); // ==================================================================== // Test Exceptions // ==================================================================== // null datasource try { final URLDataSource urlDs = null; this.email.attach(urlDs, "Test Attachment", "Test Attachment Desc"); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(true); } // invalid datasource 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) { assertTrue(true); } } @Test public void testAttachFileLocking() throws Exception { // ==================================================================== // EMAIL-120: attaching a FileDataSource may result in a locked file // resource on windows systems // ==================================================================== final File tmpFile = File.createTempFile("attachment", ".eml"); this.email.attach( new FileDataSource(tmpFile), "Test Attachment", "Test Attachment Desc"); assertTrue(tmpFile.delete()); } @Test public void testAddPart() throws Exception { // setup this.email = new MockMultiPartEmailConcrete(); final String strMessage = "hello"; final String strContentType = "text/plain"; // add part this.email.addPart(strMessage, strContentType); // validate assertEquals( strContentType, this.email.getContainer().getBodyPart(0).getContentType()); assertEquals( strMessage, this.email.getContainer().getBodyPart(0).getDataHandler() .getContent()); } @Test public void testAddPart2() throws Exception { // setup this.email = new MockMultiPartEmailConcrete(); final String strSubtype = "subtype/abc123"; // add part this.email.addPart(new MimeMultipart(strSubtype)); // validate assertTrue( this .email .getContainer() .getBodyPart(0) .getDataHandler() .getContentType() .contains(strSubtype)); } /** TODO implement test for GetContainer */ @Test public void testGetContainer() { assertTrue(true); } /** init called twice should fail */ @Test public void testInit() { // call the init function twice to trigger the IllegalStateException try { this.email.init(); this.email.init(); fail("Should have thrown an exception"); } catch (final IllegalStateException e) { assertTrue(true); } } /** test get/set sub type */ @Test public void testGetSetSubType() { for (final String validChar : testCharsValid) { this.email.setSubType(validChar); assertEquals(validChar, this.email.getSubType()); } } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/EmailTest.java0100664 0001750 0001750 00000131255 13137110665 027731 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.*; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.ParseException; import org.apache.commons.mail.mocks.MockEmailConcrete; import org.junit.Before; import org.junit.Test; /** * JUnit test case for Email Class * * @since 1.0 */ public class EmailTest extends AbstractEmailTest { 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() { // reusable objects to be used across multiple tests email = new MockEmailConcrete(); } @Test public void testGetSetDebug() { email.setDebug(true); assertTrue(email.isDebug()); email.setDebug(false); assertFalse(email.isDebug()); } @Test 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_HOST, strTestMailServer); properties.setProperty(EmailConstants.MAIL_DEBUG, String.valueOf(false)); final Session mySession = Session.getInstance(properties, null); email.setMailSession(mySession); assertEquals(mySession, email.getMailSession()); } @Test public void testGetSetAuthentication() { // setup final String strUsername = "user.name"; final String strPassword = "user.pwd"; email.setAuthentication(strUsername, strPassword); // this is cast into DefaultAuthenticator for convenience // and give us access to the getPasswordAuthentication fn final DefaultAuthenticator retrievedAuth = (DefaultAuthenticator) email.getAuthenticator(); // tests assertEquals( strUsername, retrievedAuth.getPasswordAuthentication().getUserName()); assertEquals( strPassword, retrievedAuth.getPasswordAuthentication().getPassword()); } @Test public void testGetSetAuthenticator() { // setup final String strUsername = "user.name"; final String strPassword = "user.pwd"; 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(); // tests assertEquals( strUsername, retrievedAuth.getPasswordAuthentication().getUserName()); assertEquals( strPassword, retrievedAuth.getPasswordAuthentication().getPassword()); } @Test public void testGetSetCharset() { // test ASCII and UTF-8 charsets; since every JVM is required // to support these, testing them should always succeed. Charset set = Charset.forName("US-ASCII"); email.setCharset(set.name()); assertEquals(set.name(), email.getCharset()); set = Charset.forName("UTF-8"); email.setCharset(set.name()); assertEquals(set.name(), email.getCharset()); } @Test public void testSetContentEmptyMimeMultipart() { final MimeMultipart part = new MimeMultipart(); email.setContent(part); assertEquals(part, email.getContentMimeMultipart()); } @Test public void testSetContentMimeMultipart() { final MimeMultipart part = new MimeMultipart("abc123"); email.setContent(part); assertEquals(part, email.getContentMimeMultipart()); } @Test public void testSetContentNull() throws Exception { email.setContent(null); assertNull(email.getContentMimeMultipart()); } @Test public void testSetContentObject() { // ==================================================================== // test (string object and valid content type) String testObject = "test string object"; String testContentType = " ; charset=" + EmailConstants.US_ASCII; email.setContent(testObject, testContentType); assertEquals(testObject, email.getContentObject()); assertEquals(testContentType, email.getContentType()); // ==================================================================== // test (null string object and valid content type) testObject = null; testContentType = " ; charset=" + EmailConstants.US_ASCII + " some more here"; email.setContent(testObject, testContentType); assertEquals(testObject, email.getContentObject()); assertEquals(testContentType, email.getContentType()); // ==================================================================== // test (string object and null content type) testObject = "test string object"; testContentType = null; email.setContent(testObject, testContentType); assertEquals(testObject, email.getContentObject()); assertEquals(testContentType, email.getContentType()); // ==================================================================== // test (string object and invalid content type) testObject = "test string object"; testContentType = " something incorrect "; email.setContent(testObject, testContentType); assertEquals(testObject, email.getContentObject()); assertEquals(testContentType, email.getContentType()); } @Test public void testGetSetHostName() { for (final String validChar : testCharsValid) { email.setHostName(validChar); assertEquals(validChar, email.getHostName()); } } @Test public void testGetSetSmtpPort() { email.setSmtpPort(1); assertEquals( 1, Integer.valueOf(email.getSmtpPort()).intValue()); email.setSmtpPort(Integer.MAX_VALUE); assertEquals( Integer.MAX_VALUE, Integer.valueOf(email.getSmtpPort()).intValue()); } @Test(expected = IllegalArgumentException.class) public void testSetSmtpPortZero() { email.setSmtpPort(0); } @Test(expected = IllegalArgumentException.class) public void testSetSmptPortNegative() { email.setSmtpPort(-1); } @Test(expected = IllegalArgumentException.class) public void testSetSmtpPortMinValue() { email.setSmtpPort(Integer.MIN_VALUE); } @Test public void testSetFrom() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List 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++) { // set from email.setFrom(VALID_EMAILS[i]); // retrieve and verify assertEquals(arrExpected.get(i), email.getFromAddress()); } } @Test 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); // set from email.setFrom(testValidEmail, testValidEmail, EmailConstants.ISO_8859_1); // retrieve and verify assertEquals(inetExpected, email.getFromAddress()); } @Test public void testSetFrom2() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // set from email.setFrom(VALID_EMAILS[i], testEmailNames[i]); // retrieve and verify assertEquals(arrExpected.get(i), email.getFromAddress()); } } @Test(expected = IllegalCharsetNameException.class) public void testSetFromBadEncoding() throws Exception { email.setFrom("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"); } @Test public void testAddTo() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); for (final String address : VALID_EMAILS) { email.addTo(address); } // retrieve and verify assertEquals(arrExpected.size(), email.getToAddresses().size()); assertEquals(arrExpected.toString(), email.getToAddresses().toString()); } @Test public void testAddToArray() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); //set To email.addTo(VALID_EMAILS); // retrieve and verify assertEquals(arrExpected.size(), email.getToAddresses().size()); assertEquals(arrExpected.toString(), email.getToAddresses().toString()); } @Test public void testAddToWithEncoding() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String testCharset = EmailConstants.ISO_8859_1; final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // set from email.addTo(VALID_EMAILS[i], testEmailNames[i], testCharset); } // retrieve and verify assertEquals(arrExpected.size(), email.getToAddresses().size()); assertEquals(arrExpected.toString(), email.getToAddresses().toString()); } @Test public void testAddTo2() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // set from email.addTo(VALID_EMAILS[i], testEmailNames[i]); } // retrieve and verify assertEquals(arrExpected.size(), email.getToAddresses().size()); assertEquals(arrExpected.toString(), email.getToAddresses().toString()); } @Test(expected = IllegalCharsetNameException.class) public void testAddToBadEncoding() throws Exception { email.addTo("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"); } @Test public void testSetTo() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List 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")); email.setTo(testEmailValid2); // retrieve and verify assertEquals(testEmailValid2.size(), email.getToAddresses().size()); assertEquals( testEmailValid2.toString(), email.getToAddresses().toString()); } @Test(expected = EmailException.class) public void testSetToNull() throws Exception { email.setTo(null); } @Test(expected = EmailException.class) public void testSetToEmpty() throws Exception { email.setTo(Collections.emptyList()); } @Test public void testAddCc() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); for (final String address : VALID_EMAILS) { email.addCc(address); } // retrieve and verify assertEquals(arrExpected.size(), email.getCcAddresses().size()); assertEquals(arrExpected.toString(), email.getCcAddresses().toString()); } @Test public void testAddCcArray() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); //set Cc array email.addCc(VALID_EMAILS); // retrieve and verify assertEquals(arrExpected.size(), email.getCcAddresses().size()); assertEquals(arrExpected.toString(), email.getCcAddresses().toString()); } @Test public void testAddCcWithEncoding() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String testCharset = EmailConstants.ISO_8859_1; final String[] testEmailNames = {"Name1", "", null}; final List 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")); // add valid ccs for (int i = 0; i < VALID_EMAILS.length; i++) { email.addCc(VALID_EMAILS[i], testEmailNames[i], testCharset); } // retrieve and verify assertEquals(arrExpected.size(), email.getCcAddresses().size()); assertEquals(arrExpected.toString(), email.getCcAddresses().toString()); } @Test public void testAddCc2() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // set from email.addCc(VALID_EMAILS[i], testEmailNames[i]); } // retrieve and verify assertEquals(arrExpected.size(), email.getCcAddresses().size()); assertEquals(arrExpected.toString(), email.getCcAddresses().toString()); } @Test(expected = IllegalCharsetNameException.class) public void testAddCcBadEncoding() throws Exception { email.addCc("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"); } @Test public void testSetCc() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List testEmailValid2 = new ArrayList(); testEmailValid2.add(new InternetAddress("Name1 ")); testEmailValid2.add(new InternetAddress("\"joe.doe@apache.org\" ")); testEmailValid2.add( new InternetAddress("\"someone_here@work.com.au\" ")); email.setCc(testEmailValid2); assertEquals(testEmailValid2, email.getCcAddresses()); } @Test(expected = EmailException.class) public void testSetCcNull() throws Exception { email.setCc(null); } @Test(expected = EmailException.class) public void testSetCcEmpty() throws Exception { email.setCc(Collections.emptyList()); } @Test public void testAddBcc() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); for (final String address : VALID_EMAILS) { email.addBcc(address); } // retrieve and verify assertEquals(arrExpected.size(), email.getBccAddresses().size()); assertEquals( arrExpected.toString(), email.getBccAddresses().toString()); } @Test public void testAddBccArray() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); // add a valid bcc email.addBcc(VALID_EMAILS); // retrieve and verify assertEquals(arrExpected.size(), email.getBccAddresses().size()); assertEquals( arrExpected.toString(), email.getBccAddresses().toString()); } @Test public void testAddBccWithEncoding() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String testCharset = EmailConstants.ISO_8859_1; final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // 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()); } @Test public void testAddBcc2() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // set from email.addBcc(VALID_EMAILS[i], testEmailNames[i]); } // retrieve and verify assertEquals(arrExpected.size(), email.getBccAddresses().size()); assertEquals( arrExpected.toString(), email.getBccAddresses().toString()); } @Test(expected = IllegalCharsetNameException.class) public void testAddBccBadEncoding() throws Exception { email.addBcc("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"); } @Test public void testSetBcc() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List 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")); email.setBcc(testInetEmailValid); assertEquals(testInetEmailValid, email.getBccAddresses()); } @Test(expected = EmailException.class) public void testSetBccNull() throws Exception { email.setBcc(null); } @Test(expected = EmailException.class) public void testSetBccEmpty() throws Exception { email.setBcc(Collections.emptyList()); } @Test public void testAddReplyTo() throws Exception { // ==================================================================== // Test Success // ==================================================================== final List arrExpected = new ArrayList(); arrExpected.add(new InternetAddress("me@home.com")); arrExpected.add(new InternetAddress("joe.doe@apache.org")); arrExpected.add(new InternetAddress("someone_here@work-address.com.au")); for (final String address : VALID_EMAILS) { email.addReplyTo(address); } // retrieve and verify assertEquals(arrExpected.size(), email.getReplyToAddresses().size()); assertEquals( arrExpected.toString(), email.getReplyToAddresses().toString()); } @Test public void testAddReplyToWithEncoding() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String testCharset = EmailConstants.ISO_8859_1; final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // 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()); } @Test public void testAddReplyTo2() throws Exception { // ==================================================================== // Test Success // ==================================================================== final String[] testEmailNames = {"Name1", "", null}; final List 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++) { // set replyTo email.addReplyTo(VALID_EMAILS[i], testEmailNames[i]); } // retrieve and verify assertEquals(arrExpected.size(), email.getReplyToAddresses().size()); assertEquals( arrExpected.toString(), email.getReplyToAddresses().toString()); } @Test(expected = IllegalCharsetNameException.class) public void testAddReplyToBadEncoding() throws Exception { email.addReplyTo("me@home.com", "me@home.com", "bad.encoding\uc5ec\n"); } @Test public void testAddHeader() { // ==================================================================== // Test Success // ==================================================================== final Map headers = new HashMap(); headers.put("X-Priority", "1"); headers.put("Disposition-Notification-To", "me@home.com"); headers.put("X-Mailer", "Sendmail"); for (final Map.Entry header : headers.entrySet()) { final String name = header.getKey(); final String value = header.getValue(); email.addHeader(name, value); } assertEquals(headers.size(), email.getHeaders().size()); assertEquals(headers, email.getHeaders()); } @Test(expected = IllegalArgumentException.class) public void testAddHeaderEmptyName() throws Exception { email.addHeader("", "me@home.com"); } @Test(expected = IllegalArgumentException.class) public void testAddHeaderNullName() throws Exception { email.addHeader(null, "me@home.com"); } @Test(expected = IllegalArgumentException.class) public void testAddHeaderEmptyValue() throws Exception { email.addHeader("X-Mailer", ""); } @Test(expected = IllegalArgumentException.class) public void testAddHeaderNullValue() throws Exception { email.addHeader("X-Mailer", null); } @Test public void testSetHeaders() { final Map ht = new Hashtable(); ht.put("X-Priority", "1"); ht.put("Disposition-Notification-To", "me@home.com"); ht.put("X-Mailer", "Sendmail"); email.setHeaders(ht); assertEquals(ht.size(), email.getHeaders().size()); assertEquals(ht, email.getHeaders()); } @Test public void testGetHeader() { final Map ht = new Hashtable(); ht.put("X-Foo", "Bar"); ht.put("X-Int", "1"); email.setHeaders(ht); assertEquals("Bar", email.getHeader("X-Foo")); assertEquals("1", email.getHeader("X-Int")); } @Test public void testGetHeaders() { final Map ht = new Hashtable(); ht.put("X-Foo", "Bar"); ht.put("X-Int", "1"); email.setHeaders(ht); assertEquals(ht.size(), email.getHeaders().size()); } @Test public void testFoldingHeaders() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("a@b.com"); email.addTo("c@d.com"); email.setSubject("test mail"); final String headerValue = "1234567890 1234567890 123456789 01234567890 123456789 0123456789 01234567890 01234567890"; email.addHeader("X-LongHeader", headerValue); assertTrue(email.getHeaders().size() == 1); // the header should not yet be folded -> will be done by buildMimeMessage() assertFalse(email.getHeaders().get("X-LongHeader").contains("\r\n")); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); final String[] values = msg.getHeader("X-LongHeader"); assertEquals(1, values.length); // the header should be split in two lines final String[] lines = values[0].split("\\r\\n"); assertEquals(2, lines.length); // there should only be one line-break assertTrue(values[0].indexOf("\n") == values[0].lastIndexOf("\n")); } @Test(expected = IllegalArgumentException.class) public void testSetHeaderEmptyValue() throws Exception { email.setHeaders(Collections.singletonMap("X-Mailer", "")); } @Test(expected = IllegalArgumentException.class) public void testSetHeaderNullValue() throws Exception { email.setHeaders(Collections.singletonMap("X-Mailer", (String) null)); } @Test(expected = IllegalArgumentException.class) public void testSetHeaderEmptyName() throws Exception { email.setHeaders(Collections.singletonMap("", "me@home.com")); } @Test(expected = IllegalArgumentException.class) public void testSetHeaderNullName() throws Exception { email.setHeaders(Collections.singletonMap((String) null, "me@home.com")); } @Test public void testSetSubjectValid() { for (final String validChar : testCharsValid) { email.setSubject(validChar); assertEquals(validChar, email.getSubject()); } assertEquals(null, email.setSubject(null).getSubject()); assertEquals("", email.setSubject("").getSubject()); assertEquals(" ", email.setSubject(" ").getSubject()); assertEquals("\t", email.setSubject("\t").getSubject()); } @Test public void testEndOflineCharactersInSubjectAreReplacedWithSpaces() { for (final String invalidChar : endOfLineCombinations) { email.setSubject(invalidChar); assertNotEquals(invalidChar, email.getSubject()); } assertEquals("abcdefg", email.setSubject("abcdefg").getSubject()); assertEquals("abc defg", email.setSubject("abc\rdefg").getSubject()); assertEquals("abc defg", email.setSubject("abc\ndefg").getSubject()); assertEquals("abc defg", email.setSubject("abc\r\ndefg").getSubject()); assertEquals("abc defg", email.setSubject("abc\n\rdefg").getSubject()); } @Test(expected = EmailException.class) public void testSendNoHostName() throws Exception { getMailServer(); email = new MockEmailConcrete(); email.send(); } @Test public void testSendBadHostName() { try { getMailServer(); email = new MockEmailConcrete(); email.setSubject("Test Email #1 Subject"); email.setHostName("bad.host.com"); email.setFrom("me@home.com"); email.addTo("me@home.com"); email.addCc("me@home.com"); email.addBcc("me@home.com"); email.addReplyTo("me@home.com"); email.setContent( "test string object", " ; charset=" + EmailConstants.US_ASCII); email.send(); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(e.getCause() instanceof ParseException); fakeMailServer.stop(); } } @Test(expected = EmailException.class) public void testSendFromNotSet() throws Exception { getMailServer(); email = new MockEmailConcrete(); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.addTo("me@home.com"); email.send(); } @Test 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.send(); } @Test(expected = EmailException.class) public void testSendDestinationNotSet() throws Exception { getMailServer(); email = new MockEmailConcrete(); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("me@home.com"); email.send(); } @Test(expected = EmailException.class) public void testSendBadAuthSet() throws Exception { getMailServer(); email = new MockEmailConcrete(); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setAuthentication(null, null); email.send(); } @Test public void testSendCorrectSmtpPortContainedInException() { try { getMailServer(); email = new MockEmailConcrete(); email.setHostName("bad.host.com"); email.setSSLOnConnect(true); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setAuthentication(null, null); email.send(); fail("Should have thrown an exception"); } catch (final EmailException e) { assertTrue(e.getMessage().contains("bad.host.com:465")); fakeMailServer.stop(); } } @Test public void testGetSetSentDate() { // with input date final Date dtTest = Calendar.getInstance().getTime(); email.setSentDate(dtTest); assertEquals(dtTest, email.getSentDate()); // with null input (this is a fudge :D) email.setSentDate(null); final Date sentDate = email.getSentDate(); // Date objects are millisecond specific. If you have a slow processor, // time passes between the generation of dtTest and the new Date() in // getSentDate() and this test fails. Make sure that the difference // is less than a second... assertTrue(Math.abs(sentDate.getTime() - dtTest.getTime()) < 1000); } @Test public void testToInternetAddressArray() throws Exception { final List 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")); email.setBcc(testInetEmailValid); assertEquals( testInetEmailValid.size(), email.getBccAddresses().size()); } @Test 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); // retrieve and verify assertEquals(boolPopBeforeSmtp, email.isPopBeforeSmtp()); assertEquals(strHost, email.getPopHost()); assertEquals(strUsername, email.getPopUsername()); assertEquals(strPassword, email.getPopPassword()); } /** * 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. * @throws Exception on any error */ @Test public void testDefaultCharsetAppliesToTextContent() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("a@b.com"); email.addTo("c@d.com"); email.setSubject("test mail"); email.setCharset("ISO-8859-1"); email.setContent("test content", "text/plain"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); assertEquals("text/plain; charset=ISO-8859-1", msg.getContentType()); } /** * 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 { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("a@b.com"); email.addTo("c@d.com"); email.setSubject("test mail"); email.setCharset("ISO-8859-1"); email.setContent("test content", "text/plain; charset=US-ASCII"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); assertEquals("text/plain; charset=US-ASCII", msg.getContentType()); } /** * Case 3: * A non-text content object ignores a default charset entirely. * @throws Exception on any error */ @Test public void testDefaultCharsetIgnoredByNonTextContent() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("a@b.com"); email.addTo("c@d.com"); email.setSubject("test mail"); email.setCharset("ISO-8859-1"); email.setContent("test content", "application/octet-stream"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); assertEquals("application/octet-stream", msg.getContentType()); } @Test public void testCorrectContentTypeForPNG() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("a@b.com"); email.addTo("c@d.com"); email.setSubject("test mail"); email.setCharset("ISO-8859-1"); final File png = new File("./target/test-classes/images/logos/maven-feather.png"); email.setContent(png, "image/png"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); msg.saveChanges(); assertEquals("image/png", msg.getContentType()); } @Test public void testGetSetBounceAddress() { assertNull(email.getBounceAddress()); final String bounceAddress = "test_bounce@apache.org"; email.setBounceAddress(bounceAddress); // tests assertEquals(bounceAddress, email.getBounceAddress()); } @Test public void testSetNullAndEmptyBounceAddress() { assertNull(email.setBounceAddress(null).getBounceAddress()); assertEquals("", email.setBounceAddress("").getBounceAddress()); } @Test(expected = RuntimeException.class) public void testGetSetInvalidBounceAddress() { email.setBounceAddress("invalid-bounce-address"); } @Test public void testSupportForInternationalDomainNames() throws Exception { email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom("from@d\u00F6m\u00E4in.example"); email.addTo("to@d\u00F6m\u00E4in.example"); email.addCc("cc@d\u00F6m\u00E4in.example"); email.addBcc("bcc@d\u00F6m\u00E4in.example"); email.setSubject("test mail"); email.setSubject("testSupportForInternationalDomainNames"); email.setMsg("This is a test mail ... :-)"); email.buildMimeMessage(); final MimeMessage msg = email.getMimeMessage(); assertEquals("from@xn--dmin-moa0i.example", msg.getFrom()[0].toString()); assertEquals("to@xn--dmin-moa0i.example", msg.getRecipients(Message.RecipientType.TO)[0].toString()); assertEquals("cc@xn--dmin-moa0i.example", msg.getRecipients(Message.RecipientType.CC)[0].toString()); assertEquals("bcc@xn--dmin-moa0i.example", msg.getRecipients(Message.RecipientType.BCC)[0].toString()); } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/EmailAttachmentTest.java0100664 0001750 0001750 00000005134 13137110665 031736 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.*; import java.net.URL; import org.junit.Before; import org.junit.Test; /** * JUnit test case for EmailAttachment Class. * * @since 1.0 */ public class EmailAttachmentTest extends AbstractEmailTest { private EmailAttachment attachment; @Before public void setUpAttachmentTest() { attachment = new EmailAttachment(); } @Test public void testGetSetDescription() { for (final String validChar : testCharsValid) { attachment.setDescription(validChar); assertEquals(validChar, attachment.getDescription()); } } @Test public void testGetSetName() { for (final String validChar : testCharsValid) { attachment.setName(validChar); assertEquals(validChar, attachment.getName()); } } @Test 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" }; for (final String urlString : tests) { final URL testURL = new URL(urlString); attachment.setURL(testURL); assertEquals(testURL, attachment.getURL()); } } @Test public void testGetSetDisposition() { for (final String validChar : testCharsValid) { attachment.setDisposition(validChar); assertEquals(validChar, attachment.getDisposition()); } } } commons-email-1.5-src/src/test/java/org/apache/commons/mail/ImageHtmlEmailTest.java0100664 0001750 0001750 00000047333 13137110665 031524 0ustar00stefanstefan0000000 0000000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail; import static org.junit.Assert.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.mail.resolver.DataSourceClassPathResolver; import org.apache.commons.mail.resolver.DataSourceCompositeResolver; import org.apache.commons.mail.resolver.DataSourceUrlResolver; import org.apache.commons.mail.mocks.MockImageHtmlEmailConcrete; import org.apache.commons.mail.util.MimeMessageParser; import org.apache.commons.mail.util.MimeMessageUtils; import org.junit.Before; import org.junit.Test; import javax.activation.DataSource; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ImageHtmlEmailTest extends HtmlEmailTest { private static final boolean TEST_IS_LENIENT = true; private static final URL TEST_IMAGE_URL = ImageHtmlEmailTest.class.getResource("/images/asf_logo_wide.gif"); private static final File TEST_IMAGE_DIR = new File(TEST_IMAGE_URL.getPath()).getParentFile(); private static final URL TEST_HTML_URL = ImageHtmlEmailTest.class.getResource("/attachments/download_email.cgi.html"); private static final URL TEST2_HTML_URL = ImageHtmlEmailTest.class.getResource("/attachments/classpathtest.html"); private MockImageHtmlEmailConcrete email; @Before public void setupImageHtmlEmailTest() { // reusable objects to be used across multiple tests email = new MockImageHtmlEmailConcrete(); } // ====================================================================== // Start of Tests // ====================================================================== @Test public void testSendHtml() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message getMailServer(); final String strSubject = "Test HTML Send default"; email = new MockImageHtmlEmailConcrete(); email.setDataSourceResolver(new DataSourceUrlResolver(TEST_IMAGE_DIR.toURI().toURL(), TEST_IS_LENIENT)); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); final String html = loadUrlContent(TEST_HTML_URL); // set the html message email.setHtmlMsg(html); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); fakeMailServer.stop(); assertEquals(1, fakeMailServer.getMessages().size()); final MimeMessage mimeMessage = fakeMailServer.getMessages().get(0).getMimeMessage(); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); assertTrue(mimeMessageParser.getHtmlContent().contains("\"cid:")); assertTrue(mimeMessageParser.getAttachmentList().size() == 3); } @Test public void testSendEmptyHTML() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message final ImageHtmlEmail email = new ImageHtmlEmail(); // set the html message try { email.setHtmlMsg(null); fail("Should fail here!"); } catch (final EmailException e) { assertTrue(e.getMessage(), e.getMessage().contains("Invalid message supplied")); } } @Test public void testSendEmptyHTML2() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message final ImageHtmlEmail email = new ImageHtmlEmail(); // set the html message try { email.setHtmlMsg(""); fail("Should fail here!"); } catch (final EmailException e) { assertTrue(e.getMessage(), e.getMessage().contains("Invalid message supplied")); } } @Test public void testSendHtmlUrl() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); getMailServer(); final String strSubject = "Test HTML Send default with URL"; // Create the email message email = new MockImageHtmlEmailConcrete(); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); email.setDataSourceResolver(new DataSourceUrlResolver(TEST_IMAGE_DIR.toURI().toURL(), TEST_IS_LENIENT)); // set the html message email.setHtmlMsg( "" ); // send the email email.send(); fakeMailServer.stop(); // validate txt message validateSend(fakeMailServer, strSubject, email.getHtmlMsg(), email.getFromAddress(), email.getToAddresses(), email.getCcAddresses(), email.getBccAddresses(), true); } @Test public void testSendHTMLAbsoluteLocalFile() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message getMailServer(); final String strSubject = "Test HTML Send default with absolute local path"; // Create the email message email = new MockImageHtmlEmailConcrete(); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); 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"); // set the html message email.setHtmlMsg("" ); // send the email email.send(); fakeMailServer.stop(); // validate txt message validateSend(fakeMailServer, strSubject, email.getHtmlMsg(), email.getFromAddress(), email.getToAddresses(), email.getCcAddresses(), email.getBccAddresses(), true); } @Test public void testSendHTMLClassPathFile() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message getMailServer(); final String strSubject = "Test HTML Send default"; email = new MockImageHtmlEmailConcrete(); email.setDataSourceResolver(new DataSourceClassPathResolver("/", TEST_IS_LENIENT)); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); final String html = loadUrlContent(TEST2_HTML_URL); // set the html message email.setHtmlMsg(html); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); fakeMailServer.stop(); assertEquals(1, fakeMailServer.getMessages().size()); final MimeMessage mimeMessage = fakeMailServer.getMessages().get(0).getMimeMessage(); MimeMessageUtils.writeMimeMessage(mimeMessage, new File("./target/test-emails/testSendHTMLClassPathFile.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); assertTrue(mimeMessageParser.getHtmlContent().contains("\"cid:")); assertTrue(mimeMessageParser.getAttachmentList().size() == 1); } @Test public void testSendClassPathFileWithNullName() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message getMailServer(); final String strSubject = "Test HTML Send default"; email = new MockImageHtmlEmailConcrete(); email.setDataSourceResolver(new MockDataSourceClassPathResolver("/", TEST_IS_LENIENT)); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); final String html = loadUrlContent(TEST2_HTML_URL); // set the html message email.setHtmlMsg(html); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); fakeMailServer.stop(); assertEquals(1, fakeMailServer.getMessages().size()); final MimeMessage mimeMessage = fakeMailServer.getMessages().get(0).getMimeMessage(); MimeMessageUtils.writeMimeMessage(mimeMessage, new File("./target/test-emails/testSendClassPathFileWithNullName.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); assertTrue(mimeMessageParser.getHtmlContent().contains("\"cid:")); assertTrue(mimeMessageParser.getAttachmentList().size() == 1); } @Test public void testSendHTMLAutoResolveFile() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message getMailServer(); final String strSubject = "Test HTML Send default"; email = new MockImageHtmlEmailConcrete(); final DataSourceResolver dataSourceResolvers[] = new DataSourceResolver[2]; dataSourceResolvers[0] = new DataSourceUrlResolver(new URL("http://foo"), true); dataSourceResolvers[1] = new DataSourceClassPathResolver("/", true); email.setDataSourceResolver(new DataSourceCompositeResolver(dataSourceResolvers)); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); final String html = loadUrlContent(TEST2_HTML_URL); // set the html message email.setHtmlMsg(html); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); fakeMailServer.stop(); assertEquals(1, fakeMailServer.getMessages().size()); final MimeMessage mimeMessage = fakeMailServer.getMessages().get(0).getMimeMessage(); MimeMessageUtils.writeMimeMessage(mimeMessage, new File("./target/test-emails/testSendHTMLAutoFile.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); assertTrue(mimeMessageParser.getHtmlContent().contains("\"cid:")); assertTrue(mimeMessageParser.getAttachmentList().size() == 1); } @Test public void testSendHTMLAutoResolveMultipleFiles() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); // Create the email message getMailServer(); final String strSubject = "Test HTML Send default"; email = new MockImageHtmlEmailConcrete(); final DataSourceResolver dataSourceResolver = new DataSourceClassPathResolver("/", true); email.setDataSourceResolver(dataSourceResolver); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); final String html = "

First image

" + "

Second image

" + "

Third image

"; // set the html message email.setHtmlMsg(html); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); fakeMailServer.stop(); assertEquals(1, fakeMailServer.getMessages().size()); final MimeMessage mimeMessage = fakeMailServer.getMessages().get(0).getMimeMessage(); MimeMessageUtils.writeMimeMessage(mimeMessage, new File("./target/test-emails/testSendHTMLAutoMultipleFiles.eml")); final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse(); assertTrue(mimeMessageParser.getHtmlContent().contains("\"cid:")); assertTrue(mimeMessageParser.getAttachmentList().size() == 3); } @Test public void testRegex() { 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(""); assertTrue(matcher.find()); assertEquals("h", matcher.group(2)); matcher = pattern .matcher(""); assertTrue(matcher.find()); assertEquals("h", matcher.group(2)); // uppercase matcher = pattern .matcher(""); assertTrue(matcher.find()); assertEquals("h", matcher.group(2)); // matches twice matcher = pattern .matcher(""); 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(""); 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(""); 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("\"Chart?ck=xradar&w=120&h=120&c=7fff00|7fff00&m=4&g=0\""); assertTrue(matcher.find()); assertEquals("file1", matcher.group(2)); assertTrue(matcher.find()); assertEquals("file2", matcher.group(2)); matcher = pattern .matcher(""); assertTrue(matcher.find()); assertEquals("file1", matcher.group(2)); assertTrue(matcher.find()); assertEquals("file2", matcher.group(2)); assertTrue(matcher.find()); assertEquals("file3", matcher.group(2)); assertTrue(matcher.find()); assertEquals("file4", matcher.group(2)); assertTrue(matcher.find()); assertEquals("file5", matcher.group(2)); // try with invalid HTML that is seems sometimes, i.e. without closing "/" or "" matcher = pattern.matcher(""); assertTrue(matcher.find()); assertEquals("file1", matcher.group(2)); assertTrue(matcher.find()); assertEquals("file2", matcher.group(2)); } @Test public void testEmail127() throws Exception { Logger.getLogger(ImageHtmlEmail.class.getName()).setLevel(Level.FINEST); getMailServer(); final String strSubject = "Test HTML Send default with URL"; // Create the email message email = new MockImageHtmlEmailConcrete(); email.setHostName(strTestMailServer); email.setSmtpPort(getMailServerPort()); email.setFrom(strTestMailFrom); email.addTo(strTestMailTo); email.setSubject(strSubject); email.setDataSourceResolver(new DataSourceUrlResolver(TEST_IMAGE_DIR.toURI().toURL(), TEST_IS_LENIENT)); // set the html message email.setHtmlMsg(""); // send the email email.send(); fakeMailServer.stop(); // validate txt message validateSend(fakeMailServer, strSubject, email.getHtmlMsg(), email.getFromAddress(), email.getToAddresses(), email.getCcAddresses(), email.getBccAddresses(), true); } private String loadUrlContent(final URL url) throws IOException { final InputStream stream = url.openStream(); final StringBuilder html = new StringBuilder(); try { final List lines = IOUtils.readLines(stream); for (final String line : lines) { html.append(line).append("\n"); } } finally { stream.close(); } return html.toString(); } private static final class MockDataSourceClassPathResolver extends DataSourceClassPathResolver { public MockDataSourceClassPathResolver(final String classPathBase, final boolean lenient) { super(classPathBase, lenient); } @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); ds.setName(null); return ds; } } }