├── .classpath
├── .gitignore
├── .project
├── LICENSE.txt
├── NOTICE.txt
├── README.textile
├── build.properties
├── build.xml
├── builds
├── fluent-mail-api-0.1.32.jar
└── fluent-mail-api-1.0.1.jar
├── lib-test
├── cglib-2.1_3-src.jar
├── cglib-nodep-2.1_3.jar
├── hamcrest-core-1.1.jar
├── hamcrest-library-1.1.jar
├── jmock-2.4.0.jar
├── jmock-junit3-2.4.0.jar
├── jmock-junit4-2.4.0.jar
├── jmock-legacy-2.4.0.jar
├── junit-4.4.jar
└── objenesis-1.0.jar
├── lib
└── mail.jar
├── src-examples
└── examples
│ └── SendEmailExample.java
├── src-test
└── com
│ └── guilhermechapiewski
│ └── fluentmail
│ ├── email
│ └── EmailMessageTest.java
│ ├── transport
│ ├── EmailTransportConfigurationTest.java
│ └── PostalServiceTest.java
│ └── validation
│ └── EmailAddressValidatorTest.java
└── src
└── com
└── guilhermechapiewski
└── fluentmail
├── email
├── Email.java
├── EmailBuilder.java
└── EmailMessage.java
├── transport
├── EmailTransportConfiguration.java
├── EmailTransportException.java
└── PostalService.java
└── validation
├── EmailAddressValidator.java
├── IncompleteEmailException.java
└── InvalidEmailAddressException.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/*
2 | temp/*
3 | *.javac
4 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | FluentMailAPI
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | The Fluent Mail API is developed by:
2 |
3 | Guilherme Chapiewski (http://guilhermechapiewski.com)
4 | Contact: guilherme.chapiewski at gmail.com
5 | Project Website: http://github.com/guilhermechapiewski/fluent-mail-api
6 |
7 | This software is distributed for free, under Apache License version 2.0.
8 | See LICENSE.txt for more details.
9 |
--------------------------------------------------------------------------------
/README.textile:
--------------------------------------------------------------------------------
1 | h1. About
2 |
3 | *Fluent Mail API* is a simple Java API that uses Sun's "JavaMail API":http://java.sun.com/products/javamail/ to send e-mail messages.
4 |
5 | This is a project to demonstrate "Fluent Interfaces":http://martinfowler.com/bliki/FluentInterface.html usage, although it's fully functional and production-ready. The API consists in an internal DSL to send e-mail messages that was designed to be dead-simple to use.
6 |
7 | h1. Usage example
8 |
9 |
new EmailMessage()
10 | .from("demo@guilhermechapiewski.com")
11 | .to("destination@address.com")
12 | .withSubject("Fluent Mail API")
13 | .withBody("Demo message")
14 | .send();
15 |
16 | h2. Comparison with JavaMail API
17 |
18 | If you use pure "JavaMail API":http://java.sun.com/products/javamail/, it will be something like this (from "Java World tutorial":http://www.javaworld.com/javaworld/jw-06-1999/jw-06-javamail.html?page=4):
19 |
20 | // create some properties and get the default Session
21 | Properties props = new Properties();
22 | props.put("mail.smtp.host", _smtpHost);
23 | Session session = Session.getDefaultInstance(props, null);
24 | // create a message
25 | Address replyToList[] = { new InternetAddress(replyTo) };
26 | Message newMessage = new MimeMessage(session);
27 | if (_fromName != null)
28 | newMessage.setFrom(new InternetAddress(from,
29 | _fromName + " on behalf of " + replyTo));
30 | else
31 | newMessage.setFrom(new InternetAddress(from));
32 | newMessage.setReplyTo(replyToList);
33 | newMessage.setRecipients(Message.RecipientType.BCC, _toList);
34 | newMessage.setSubject(subject);
35 | newMessage.setSentDate(sentDate);
36 | // send newMessage
37 | Transport transport = session.getTransport(SMTP_MAIL);
38 | transport.connect(_smtpHost, _user, _password);
39 | transport.sendMessage(newMessage, _toList);
40 |
41 | h1. 20 second tutorial
42 |
43 | h2. 1) Get the JARs
44 |
45 | Download the latest "fluent-mail-api.jar":https://github.com/guilhermechapiewski/fluent-mail-api/raw/master/builds/fluent-mail-api-1.0.1.jar (check all the releases available at the "builds":https://github.com/guilhermechapiewski/fluent-mail-api/tree/master/builds/ directory) and "mail.jar":https://github.com/guilhermechapiewski/fluent-mail-api/raw/master/lib/mail.jar. You can also download mail.jar from "JavaMail API":http://java.sun.com/products/javamail/ website.
46 |
47 | h2. 2) Configuration
48 |
49 | You can configure Fluent Mail API in two ways:
50 |
51 | Create a simple *fluent-mail-api.properties* file and make it available in the classpath. Example:
52 |
53 | smtp.server=my.smtp.server.com
54 | auth.required=true
55 | use.secure.smtp=false
56 | smtp.username=gc
57 | smtp.password=mypasswd
58 |
59 | OR
60 |
61 | Configure it programatically in your application startup:
62 |
63 | EmailTransportConfiguration.configure("my.smtp.server.com", true, false, "gc", "mypasswd");
64 |
65 | h2. 3) That's it!
66 |
67 | You are ready to start using the API!
68 |
69 | h1. Features
70 |
71 | * Really simple to use API.
72 | * Send email to, cc or bcc multiple addresses.
73 | * SMTP authentication support.
74 | * Secure SMTP support.
75 | * Send e-mail with attachments. (contribution by "danielbussade":https://github.com/danielbussade)
76 |
77 | h1. License
78 |
79 | *Fluent Mail API* is free software licensed under the "Apache 2.0 License":http://www.apache.org/licenses/. For more details, check "LICENSE.txt":https://github.com/guilhermechapiewski/fluent-mail-api/raw/master/LICENSE.txt.
--------------------------------------------------------------------------------
/build.properties:
--------------------------------------------------------------------------------
1 | project.jar.prefix=fluent-mail-api
2 | project.version=1.0
3 | project.revision=1
4 |
5 | project.jar.name=${project.jar.prefix}-${project.version}.${project.revision}.jar
--------------------------------------------------------------------------------
/build.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/builds/fluent-mail-api-0.1.32.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/builds/fluent-mail-api-0.1.32.jar
--------------------------------------------------------------------------------
/builds/fluent-mail-api-1.0.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/builds/fluent-mail-api-1.0.1.jar
--------------------------------------------------------------------------------
/lib-test/cglib-2.1_3-src.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/cglib-2.1_3-src.jar
--------------------------------------------------------------------------------
/lib-test/cglib-nodep-2.1_3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/cglib-nodep-2.1_3.jar
--------------------------------------------------------------------------------
/lib-test/hamcrest-core-1.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/hamcrest-core-1.1.jar
--------------------------------------------------------------------------------
/lib-test/hamcrest-library-1.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/hamcrest-library-1.1.jar
--------------------------------------------------------------------------------
/lib-test/jmock-2.4.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/jmock-2.4.0.jar
--------------------------------------------------------------------------------
/lib-test/jmock-junit3-2.4.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/jmock-junit3-2.4.0.jar
--------------------------------------------------------------------------------
/lib-test/jmock-junit4-2.4.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/jmock-junit4-2.4.0.jar
--------------------------------------------------------------------------------
/lib-test/jmock-legacy-2.4.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/jmock-legacy-2.4.0.jar
--------------------------------------------------------------------------------
/lib-test/junit-4.4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/junit-4.4.jar
--------------------------------------------------------------------------------
/lib-test/objenesis-1.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib-test/objenesis-1.0.jar
--------------------------------------------------------------------------------
/lib/mail.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guilhermechapiewski/fluent-mail-api/3ea3c618ad116714e50ee3ee03f4435cd8332a0d/lib/mail.jar
--------------------------------------------------------------------------------
/src-examples/examples/SendEmailExample.java:
--------------------------------------------------------------------------------
1 | package examples;
2 |
3 | import com.guilhermechapiewski.fluentmail.email.EmailMessage;
4 | import com.guilhermechapiewski.fluentmail.transport.EmailTransportConfiguration;
5 |
6 | public class SendEmailExample {
7 |
8 | public static void main(String[] args) {
9 | // put your e-mail address here
10 | final String yourAddress = "guilherme.chapiewski@gmail.com";
11 |
12 | // configure programatically your mail server info
13 | EmailTransportConfiguration.configure("smtp.server.com", true,
14 | false, "username", "password");
15 |
16 | // and go!
17 | new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress)
18 | .withSubject("Fluent Mail API")
19 | .withAttachment("file_name")
20 | .withBody("Demo message").send();
21 |
22 | System.out.println("Check your inbox!");
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src-test/com/guilhermechapiewski/fluentmail/email/EmailMessageTest.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.email;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertFalse;
5 | import static org.junit.Assert.assertNotNull;
6 | import static org.junit.Assert.assertTrue;
7 |
8 | import java.util.Set;
9 |
10 | import org.jmock.Expectations;
11 | import org.jmock.Mockery;
12 | import org.jmock.lib.legacy.ClassImposteriser;
13 | import org.junit.Before;
14 | import org.junit.Test;
15 |
16 | import com.guilhermechapiewski.fluentmail.transport.PostalService;
17 | import com.guilhermechapiewski.fluentmail.validation.EmailAddressValidator;
18 | import com.guilhermechapiewski.fluentmail.validation.IncompleteEmailException;
19 |
20 | public class EmailMessageTest {
21 |
22 | Mockery context = new Mockery() {
23 | {
24 | setImposteriser(ClassImposteriser.INSTANCE);
25 | }
26 | };
27 |
28 | @Before
29 | public void setup() {
30 | // cleaning dependencies
31 | EmailMessage.setEmailAddressValidator(new EmailAddressValidator());
32 | EmailMessage.setPostalService(new PostalService());
33 | }
34 |
35 | @Test
36 | public void should_send_mail_when_parameters_are_correct() {
37 |
38 | final EmailBuilder email = context.mock(EmailBuilder.class);
39 |
40 | context.checking(new Expectations() {
41 | {
42 | one(email).from("email@from.com");
43 | will(returnValue(email));
44 |
45 | one(email).to("email@to.com");
46 | will(returnValue(email));
47 |
48 | one(email).withSubject("subject");
49 | will(returnValue(email));
50 |
51 | one(email).withBody("body");
52 | will(returnValue(email));
53 |
54 | one(email).send();
55 | }
56 | });
57 |
58 | email.from("email@from.com").to("email@to.com").withSubject("subject")
59 | .withBody("body").send();
60 | }
61 |
62 | @Test
63 | public void should_allow_many_tos() {
64 | EmailMessage email = (EmailMessage) new EmailMessage().to("a@a.com")
65 | .to("b@b.com").to("c@c.com");
66 |
67 | Set addresses = email.getToAddresses();
68 |
69 | assertNotNull("Addresses should not be null", addresses);
70 | assertEquals("Should have the correct froms quantity", 3, addresses
71 | .size());
72 | assertTrue("Should contain the specified address", addresses
73 | .contains("a@a.com"));
74 | assertTrue("Should contain the specified address", addresses
75 | .contains("b@b.com"));
76 | assertTrue("Should contain the specified address", addresses
77 | .contains("c@c.com"));
78 | }
79 |
80 | @Test
81 | public void should_allow_many_tos_in_the_same_method() {
82 | EmailMessage email = (EmailMessage) new EmailMessage().to("a@a.com",
83 | "b@b.com", "c@c.com");
84 |
85 | Set addresses = email.getToAddresses();
86 |
87 | assertNotNull("Addresses should not be null", addresses);
88 | assertEquals("Should have the correct froms quantity", 3, addresses
89 | .size());
90 | assertTrue("Should contain the specified address", addresses
91 | .contains("a@a.com"));
92 | assertTrue("Should contain the specified address", addresses
93 | .contains("b@b.com"));
94 | assertTrue("Should contain the specified address", addresses
95 | .contains("c@c.com"));
96 | }
97 |
98 | @Test
99 | public void should_ignore_repeated_tos() {
100 | EmailMessage email = (EmailMessage) new EmailMessage().to("a@a.com")
101 | .to("a@a.com").to("a@a.com");
102 |
103 | Set addresses = email.getToAddresses();
104 |
105 | assertNotNull("Addresses should not be null", addresses);
106 | assertEquals("Should have the correct froms quantity", 1, addresses
107 | .size());
108 | assertTrue("Should contain the specified address", addresses
109 | .contains("a@a.com"));
110 | }
111 |
112 | @Test
113 | public void should_allow_many_ccs() {
114 | EmailMessage email = (EmailMessage) new EmailMessage().cc("a@a.com")
115 | .cc("b@b.com").cc("c@c.com");
116 |
117 | Set addresses = email.getCcAddresses();
118 |
119 | assertNotNull("Addresses should not be null", addresses);
120 | assertEquals("Should have the correct froms quantity", 3, addresses
121 | .size());
122 | assertTrue("Should contain the specified address", addresses
123 | .contains("a@a.com"));
124 | assertTrue("Should contain the specified address", addresses
125 | .contains("b@b.com"));
126 | assertTrue("Should contain the specified address", addresses
127 | .contains("c@c.com"));
128 | }
129 |
130 | @Test
131 | public void should_allow_many_ccs_in_the_same_method() {
132 | EmailMessage email = (EmailMessage) new EmailMessage().cc("a@a.com",
133 | "b@b.com", "c@c.com");
134 |
135 | Set addresses = email.getCcAddresses();
136 |
137 | assertNotNull("Addresses should not be null", addresses);
138 | assertEquals("Should have the correct froms quantity", 3, addresses
139 | .size());
140 | assertTrue("Should contain the specified address", addresses
141 | .contains("a@a.com"));
142 | assertTrue("Should contain the specified address", addresses
143 | .contains("b@b.com"));
144 | assertTrue("Should contain the specified address", addresses
145 | .contains("c@c.com"));
146 | }
147 |
148 | @Test
149 | public void should_ignore_repeated_ccs() {
150 | EmailMessage email = (EmailMessage) new EmailMessage().cc("a@a.com")
151 | .cc("a@a.com").cc("a@a.com");
152 |
153 | Set addresses = email.getCcAddresses();
154 |
155 | assertNotNull("Addresses should not be null", addresses);
156 | assertEquals("Should have the correct froms quantity", 1, addresses
157 | .size());
158 | assertTrue("Should contain the specified address", addresses
159 | .contains("a@a.com"));
160 | }
161 |
162 | @Test
163 | public void should_allow_many_bccs() {
164 | EmailMessage email = (EmailMessage) new EmailMessage().bcc("a@a.com")
165 | .bcc("b@b.com").bcc("c@c.com");
166 |
167 | Set addresses = email.getBccAddresses();
168 |
169 | assertNotNull("Addresses should not be null", addresses);
170 | assertEquals("Should have the correct froms quantity", 3, addresses
171 | .size());
172 | assertTrue("Should contain the specified address", addresses
173 | .contains("a@a.com"));
174 | assertTrue("Should contain the specified address", addresses
175 | .contains("b@b.com"));
176 | assertTrue("Should contain the specified address", addresses
177 | .contains("c@c.com"));
178 | }
179 |
180 | @Test
181 | public void should_allow_many_bccs_in_the_same_method() {
182 | EmailMessage email = (EmailMessage) new EmailMessage().bcc("a@a.com",
183 | "b@b.com", "c@c.com");
184 |
185 | Set addresses = email.getBccAddresses();
186 |
187 | assertNotNull("Addresses should not be null", addresses);
188 | assertEquals("Should have the correct froms quantity", 3, addresses
189 | .size());
190 | assertTrue("Should contain the specified address", addresses
191 | .contains("a@a.com"));
192 | assertTrue("Should contain the specified address", addresses
193 | .contains("b@b.com"));
194 | assertTrue("Should contain the specified address", addresses
195 | .contains("c@c.com"));
196 | }
197 |
198 | @Test
199 | public void should_ignore_repeated_bccs() {
200 | EmailMessage email = (EmailMessage) new EmailMessage().bcc("a@a.com")
201 | .bcc("a@a.com").bcc("a@a.com");
202 |
203 | Set addresses = email.getBccAddresses();
204 |
205 | assertNotNull("Addresses should not be null", addresses);
206 | assertEquals("Should have the correct froms quantity", 1, addresses
207 | .size());
208 | assertTrue("Should contain the specified address", addresses
209 | .contains("a@a.com"));
210 | }
211 |
212 | @Test
213 | public void should_allow_many_attachments(){
214 | EmailMessage email = (EmailMessage) new EmailMessage().withAttachment("C:\\java.png")
215 | .withAttachment("/home/danielbussade/teste.txt").withAttachment("C:\\teste.pdf");
216 |
217 | Set attachments = email.getAttachments();
218 | assertNotNull("Attachments should be null",attachments);
219 | assertEquals("Should have the correct froms quantity", 3, attachments
220 | .size());
221 | assertTrue("Should contain the specified attachments", attachments
222 | .contains("C:\\java.png"));
223 | assertTrue("Should contain the specified attachments", attachments
224 | .contains("/home/danielbussade/teste.txt"));
225 | assertTrue("Should contain the specified attachments", attachments
226 | .contains("C:\\teste.pdf"));
227 |
228 | }
229 |
230 | @Test
231 | public void should_allow_many_attachments_in_the_same_method(){
232 | EmailMessage email = (EmailMessage) new EmailMessage().withAttachment("C:\\java.png",
233 | "/home/danielbussade/teste.txt","C:\\teste.pdf");
234 |
235 | Set attachments = email.getAttachments();
236 | assertNotNull("Attachments should be null",attachments);
237 | assertEquals("Should have the correct froms quantity", 3, attachments
238 | .size());
239 | assertTrue("Should contain the specified attachments", attachments
240 | .contains("C:\\java.png"));
241 | assertTrue("Should contain the specified attachments", attachments
242 | .contains("/home/danielbussade/teste.txt"));
243 | assertTrue("Should contain the specified attachments", attachments
244 | .contains("C:\\teste.pdf"));
245 |
246 | }
247 |
248 | @Test
249 | public void should_require_minimum_info_to_send_message() throws Exception {
250 | final PostalService postalService = context.mock(PostalService.class);
251 | final EmailAddressValidator emailAddressValidator = context
252 | .mock(EmailAddressValidator.class);
253 | final EmailMessage email = new EmailMessage();
254 |
255 | EmailMessage.setPostalService(postalService);
256 | EmailMessage.setEmailAddressValidator(emailAddressValidator);
257 |
258 | context.checking(new Expectations() {
259 | {
260 | one(postalService).send(email);
261 |
262 | one(emailAddressValidator).validate("a@a.com");
263 | will(returnValue(true));
264 |
265 | one(emailAddressValidator).validate("b@b.com");
266 | will(returnValue(true));
267 | }
268 | });
269 |
270 | try_to_send_incomplete_mail(email);
271 |
272 | email.from("a@a.com");
273 |
274 | try_to_send_incomplete_mail(email);
275 |
276 | email.to("b@b.com");
277 |
278 | try_to_send_incomplete_mail(email);
279 |
280 | email.withSubject("test");
281 |
282 | try_to_send_incomplete_mail(email);
283 |
284 | email.withBody("test");
285 |
286 | try_to_send_complete_mail(email);
287 | }
288 |
289 | private void try_to_send_incomplete_mail(EmailMessage email) {
290 | boolean error = false;
291 | try {
292 | email.send();
293 | } catch (IncompleteEmailException e) {
294 | error = true;
295 | }
296 | assertTrue("Should throw exception", error);
297 | }
298 |
299 | private void try_to_send_complete_mail(EmailMessage email) {
300 | boolean error = false;
301 | try {
302 | email.send();
303 | } catch (Exception e) {
304 | error = true;
305 | }
306 | assertFalse("Should not throw any exception", error);
307 | }
308 |
309 | @Test
310 | public void should_send_email_using_java_mail_api() throws Exception {
311 | final EmailMessage email = (EmailMessage) new EmailMessage().from(
312 | "root@gc.org").to("john@doe.com").withSubject("Testing")
313 | .withBody("FluentMailAPI");
314 |
315 | final PostalService postalService = context.mock(PostalService.class);
316 |
317 | EmailMessage.setPostalService(postalService);
318 |
319 | context.checking(new Expectations() {
320 | {
321 | one(postalService).send(email);
322 | }
323 | });
324 |
325 | email.send();
326 | }
327 | }
--------------------------------------------------------------------------------
/src-test/com/guilhermechapiewski/fluentmail/transport/EmailTransportConfigurationTest.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.transport;
2 |
3 | import static org.junit.Assert.assertEquals;
4 |
5 | import org.junit.Test;
6 |
7 | public class EmailTransportConfigurationTest {
8 |
9 | EmailTransportConfiguration config = new EmailTransportConfiguration();
10 |
11 | @Test
12 | public void should_manage_configuration_correctly() {
13 | String smtpServer = "smtp.server.com";
14 | boolean authenticationRequired = true;
15 | boolean useSecureSmtp = false;
16 | String username = "john";
17 | String password = "doe";
18 |
19 | EmailTransportConfiguration.configure(smtpServer,
20 | authenticationRequired, useSecureSmtp, username, password);
21 |
22 | assertEquals("Should configure smtp server correctly", smtpServer,
23 | config.getSmtpServer());
24 | assertEquals("Should configure authentication correctly",
25 | authenticationRequired, config.isAuthenticationRequired());
26 | assertEquals("Should configure secure smtp correctly", useSecureSmtp,
27 | config.useSecureSmtp());
28 | assertEquals("Should configure username correctly", username, config
29 | .getUsername());
30 | assertEquals("Should configure password correctly", password, config
31 | .getPassword());
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src-test/com/guilhermechapiewski/fluentmail/transport/PostalServiceTest.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.transport;
2 |
3 | import static org.junit.Assert.assertEquals;
4 | import static org.junit.Assert.assertNotNull;
5 |
6 | import java.util.HashSet;
7 | import java.util.Set;
8 |
9 | import javax.mail.Message;
10 | import javax.mail.Session;
11 | import javax.mail.internet.MimeMultipart;
12 |
13 | import org.jmock.Expectations;
14 | import org.jmock.Mockery;
15 | import org.junit.BeforeClass;
16 | import org.junit.Test;
17 |
18 | import com.guilhermechapiewski.fluentmail.email.Email;
19 |
20 | public class PostalServiceTest {
21 |
22 | static final EmailTransportConfiguration config = new EmailTransportConfiguration();
23 |
24 | static String SMTP_SERVER = "smtp.server.com";
25 | static boolean AUTH_REQUIRED = true;
26 | static boolean USE_SECURE_SMTP = false;
27 | static String USERNAME = "john";
28 | static String PASSWORD = "doe";
29 |
30 | Mockery context = new Mockery();
31 |
32 | @BeforeClass
33 | public static void setup() {
34 | EmailTransportConfiguration.configure(SMTP_SERVER, AUTH_REQUIRED,
35 | USE_SECURE_SMTP, USERNAME, PASSWORD);
36 | }
37 |
38 | @Test
39 | public void should_choose_correct_protocol_when_using_secure_smtp_or_not() {
40 | PostalService postalService = new PostalService();
41 |
42 | EmailTransportConfiguration.configure(SMTP_SERVER, AUTH_REQUIRED,
43 | false, USERNAME, PASSWORD);
44 |
45 | assertEquals("Should use SMTP protocol", "smtp", postalService
46 | .getProtocol());
47 |
48 | EmailTransportConfiguration.configure(SMTP_SERVER, AUTH_REQUIRED, true,
49 | USERNAME, PASSWORD);
50 |
51 | assertEquals("Should use Secure SMTP protocol", "smtps", postalService
52 | .getProtocol());
53 | }
54 |
55 | @Test
56 | public void should_create_message_from_email() throws Exception {
57 | final Email email = context.mock(Email.class);
58 |
59 | final String from = "from.john@doe.com";
60 |
61 | final String to = "to.john@doe.com";
62 | final Set tos = new HashSet();
63 | tos.add(to);
64 |
65 | final String cc = "cc.john@doe.com";
66 | final Set ccs = new HashSet();
67 | ccs.add(cc);
68 |
69 | final String bcc = "bcc.john@doe.com";
70 | final Set bccs = new HashSet();
71 | bccs.add(bcc);
72 |
73 | final String subject = "subject";
74 |
75 | final String body = "text";
76 |
77 | context.checking(new Expectations() {
78 | {
79 | one(email).getFromAddress();
80 | will(returnValue(from));
81 |
82 | one(email).getToAddresses();
83 | will(returnValue(tos));
84 |
85 | one(email).getCcAddresses();
86 | will(returnValue(ccs));
87 |
88 | one(email).getBccAddresses();
89 | will(returnValue(bccs));
90 |
91 | one(email).getSubject();
92 | will(returnValue(subject));
93 |
94 | one(email).getAttachments();
95 | will(returnValue(new HashSet()));
96 |
97 | one(email).getBody();
98 | will(returnValue(body));
99 | }
100 | });
101 |
102 | PostalService postalService = new PostalService();
103 | Message message = postalService.createMessage(email);
104 |
105 | assertEquals(from, message.getFrom()[0].toString());
106 | assertEquals(to, message.getRecipients(Message.RecipientType.TO)[0]
107 | .toString());
108 | assertEquals(cc, message.getRecipients(Message.RecipientType.CC)[0]
109 | .toString());
110 | assertEquals(bcc, message.getRecipients(Message.RecipientType.BCC)[0]
111 | .toString());
112 | assertEquals(subject, message.getSubject());
113 |
114 | MimeMultipart mimeContent = (MimeMultipart)message.getContent();
115 | assertEquals(body, mimeContent.getBodyPart(0).getContent());
116 | }
117 |
118 | @Test
119 | public void should_get_session_with_correct_config() {
120 | EmailTransportConfiguration.configure(SMTP_SERVER, AUTH_REQUIRED,
121 | USE_SECURE_SMTP, USERNAME, PASSWORD);
122 |
123 | PostalService postalService = new PostalService();
124 | Session session = postalService.getSession();
125 |
126 | assertNotNull("Session cannot be null", session);
127 | assertEquals("Should get correct smtp server", SMTP_SERVER, session
128 | .getProperty("mail.smtp.host"));
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/src-test/com/guilhermechapiewski/fluentmail/validation/EmailAddressValidatorTest.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.validation;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | import com.guilhermechapiewski.fluentmail.validation.EmailAddressValidator;
8 |
9 | public class EmailAddressValidatorTest {
10 |
11 | EmailAddressValidator validator = new EmailAddressValidator();
12 |
13 | @Test
14 | public void should_validate_long_address() {
15 | assertTrue(validator
16 | .validate("guilherme.chapiewski@video.dev.wm.google.code.com"));
17 | }
18 |
19 | @Test
20 | public void should_validate_short_address() {
21 | assertTrue(validator.validate("g@g.com"));
22 | }
23 |
24 | @Test
25 | public void should_not_validate_invalid_addresses() {
26 | assertFalse(validator.validate("22 Acacia Avenue"));
27 | assertFalse(validator.validate("gc.com.br"));
28 | assertFalse(validator.validate("@test.com.br"));
29 | assertFalse(validator.validate(""));
30 | }
31 |
32 | @Test
33 | public void should_not_validate_null_address() {
34 | assertFalse(validator.validate(null));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/email/Email.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.email;
2 |
3 | import java.util.Set;
4 |
5 | public interface Email {
6 |
7 | String getFromAddress();
8 |
9 | Set getToAddresses();
10 |
11 | Set getCcAddresses();
12 |
13 | Set getBccAddresses();
14 |
15 | Set getAttachments();
16 |
17 | String getSubject();
18 |
19 | String getBody();
20 | }
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/email/EmailBuilder.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.email;
2 |
3 | public interface EmailBuilder {
4 |
5 | EmailBuilder from(String address);
6 |
7 | EmailBuilder to(String... addresses);
8 |
9 | EmailBuilder cc(String... addresses);
10 |
11 | EmailBuilder bcc(String... addresses);
12 |
13 | EmailBuilder withSubject(String subject);
14 |
15 | EmailBuilder withBody(String body);
16 |
17 | EmailBuilder withAttachment(String... attachments);
18 |
19 | void send();
20 | }
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/email/EmailMessage.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.email;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import com.guilhermechapiewski.fluentmail.transport.EmailTransportException;
7 | import com.guilhermechapiewski.fluentmail.transport.PostalService;
8 | import com.guilhermechapiewski.fluentmail.validation.EmailAddressValidator;
9 | import com.guilhermechapiewski.fluentmail.validation.IncompleteEmailException;
10 | import com.guilhermechapiewski.fluentmail.validation.InvalidEmailAddressException;
11 |
12 | public class EmailMessage implements EmailBuilder, Email {
13 |
14 | private static EmailAddressValidator emailAddressValidator = new EmailAddressValidator();
15 | private static PostalService postalService = new PostalService();
16 |
17 | private String fromAddress;
18 | private Set toAddresses = new HashSet();
19 | private Set ccAddresses = new HashSet();
20 | private Set bccAddresses = new HashSet();
21 | private Set attachments = new HashSet();
22 | private String subject;
23 | private String body;
24 |
25 | public void send() {
26 | validateRequiredInfo();
27 | validateAddresses();
28 | sendMessage();
29 | }
30 |
31 | protected void validateRequiredInfo() {
32 | if (fromAddress == null) {
33 | throw new IncompleteEmailException("From address cannot be null");
34 | }
35 | if (toAddresses.isEmpty()) {
36 | throw new IncompleteEmailException(
37 | "Email should have at least one to address");
38 | }
39 | if (subject == null) {
40 | throw new IncompleteEmailException("Subject cannot be null");
41 | }
42 | if (body == null) {
43 | throw new IncompleteEmailException("Body cannot be null");
44 | }
45 | }
46 |
47 | protected void sendMessage() {
48 | try {
49 | postalService.send(this);
50 | } catch (Exception e) {
51 | throw new EmailTransportException("Email could not be sent: "
52 | + e.getMessage(), e);
53 | }
54 | }
55 |
56 | public EmailBuilder from(String address) {
57 | this.fromAddress = address;
58 | return this;
59 | }
60 |
61 | public EmailBuilder to(String... addresses) {
62 | for (int i = 0; i < addresses.length; i++) {
63 | this.toAddresses.add(addresses[i]);
64 | }
65 | return this;
66 | }
67 |
68 | public EmailBuilder cc(String... addresses) {
69 | for (int i = 0; i < addresses.length; i++) {
70 | this.ccAddresses.add(addresses[i]);
71 | }
72 | return this;
73 | }
74 |
75 | public EmailBuilder bcc(String... addresses) {
76 | for (int i = 0; i < addresses.length; i++) {
77 | this.bccAddresses.add(addresses[i]);
78 | }
79 | return this;
80 | }
81 |
82 | public EmailBuilder withSubject(String subject) {
83 | this.subject = subject;
84 | return this;
85 | }
86 |
87 | public EmailBuilder withBody(String body) {
88 | this.body = body;
89 | return this;
90 | }
91 |
92 | public EmailBuilder withAttachment(String... attachments) {
93 | for (int i = 0; i < attachments.length; i++) {
94 | this.attachments.add(attachments[i]);
95 | }
96 | return this;
97 | }
98 |
99 | public String getFromAddress() {
100 | return fromAddress;
101 | }
102 |
103 | public Set getToAddresses() {
104 | return toAddresses;
105 | }
106 |
107 | public Set getCcAddresses() {
108 | return ccAddresses;
109 | }
110 |
111 | public Set getBccAddresses() {
112 | return bccAddresses;
113 | }
114 |
115 | public Set getAttachments() {
116 | return attachments;
117 | }
118 |
119 | public String getSubject() {
120 | return subject;
121 | }
122 |
123 | public String getBody() {
124 | return body;
125 | }
126 |
127 | protected EmailBuilder validateAddresses() {
128 | if (!emailAddressValidator.validate(fromAddress)) {
129 | throw new InvalidEmailAddressException("From: " + fromAddress);
130 | }
131 |
132 | for (String email : toAddresses) {
133 | if (!emailAddressValidator.validate(email)) {
134 | throw new InvalidEmailAddressException("To: " + email);
135 | }
136 | }
137 |
138 | return this;
139 | }
140 |
141 | public static void setEmailAddressValidator(
142 | EmailAddressValidator emailAddressValidator) {
143 | EmailMessage.emailAddressValidator = emailAddressValidator;
144 | }
145 |
146 | public static void setPostalService(PostalService postalService) {
147 | EmailMessage.postalService = postalService;
148 | }
149 |
150 |
151 |
152 | }
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/transport/EmailTransportConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.transport;
2 |
3 | import java.io.InputStream;
4 | import java.util.Properties;
5 |
6 | public class EmailTransportConfiguration {
7 |
8 | private static final String PROPERTIES_FILE = "fluent-mail-api.properties";
9 | private static final String KEY_SMTP_SERVER = "smtp.server";
10 | private static final String KEY_AUTH_REQUIRED = "auth.required";
11 | private static final String KEY_USE_SECURE_SMTP = "use.secure.smtp";
12 | private static final String KEY_USERNAME = "smtp.username";
13 | private static final String KEY_PASSWORD = "smtp.password";
14 |
15 | private static String smtpServer = "";
16 | private static boolean authenticationRequired = false;
17 | private static boolean useSecureSmtp = false;
18 | private static String username = null;
19 | private static String password = null;
20 |
21 | static {
22 | Properties properties = loadProperties();
23 |
24 | String smtpServer = properties.getProperty(KEY_SMTP_SERVER);
25 | boolean authenticationRequired = Boolean
26 | .parseBoolean(KEY_AUTH_REQUIRED);
27 | boolean useSecureSmtp = Boolean.parseBoolean(KEY_USE_SECURE_SMTP);
28 | String username = properties.getProperty(KEY_USERNAME);
29 | String password = properties.getProperty(KEY_PASSWORD);
30 |
31 | configure(smtpServer, authenticationRequired, useSecureSmtp, username,
32 | password);
33 | }
34 |
35 | private static Properties loadProperties() {
36 | Properties properties = new Properties();
37 |
38 | InputStream inputStream = EmailTransportConfiguration.class
39 | .getResourceAsStream(PROPERTIES_FILE);
40 |
41 | if (inputStream == null) {
42 | inputStream = EmailTransportConfiguration.class
43 | .getResourceAsStream("/" + PROPERTIES_FILE);
44 | }
45 |
46 | try {
47 | properties.load(inputStream);
48 | } catch (Exception e) {
49 | // Properties file not found, no problem.
50 | }
51 |
52 | return properties;
53 | }
54 |
55 | /**
56 | * Configure mail transport to use the specified SMTP server. Because this
57 | * configuration mode does not require to inform username and password, it
58 | * assumes that authentication and secure SMTP are not required.
59 | *
60 | * @param smtpServer
61 | * The SMTP server to use for mail transport. To use a specific
62 | * port, user the syntax server:port.
63 | */
64 | public static void configure(String smtpServer) {
65 | configure(smtpServer, false, false, null, null);
66 | }
67 |
68 | /**
69 | * @param smtpServer
70 | * The SMTP server to use for mail transport. To use a specific
71 | * port, user the syntax server:port.
72 | * @param authenticationRequired
73 | * Informs if mail transport needs to authenticate to send mail
74 | * or not.
75 | * @param useSecureSmtp
76 | * Use secure SMTP to send messages.
77 | * @param username
78 | * The SMTP username.
79 | * @param password
80 | * The SMTP password.
81 | */
82 | public static void configure(String smtpServer,
83 | boolean authenticationRequired, boolean useSecureSmtp,
84 | String username, String password) {
85 | EmailTransportConfiguration.smtpServer = smtpServer;
86 | EmailTransportConfiguration.authenticationRequired = authenticationRequired;
87 | EmailTransportConfiguration.useSecureSmtp = useSecureSmtp;
88 | EmailTransportConfiguration.username = username;
89 | EmailTransportConfiguration.password = password;
90 | }
91 |
92 | public String getSmtpServer() {
93 | return smtpServer;
94 | }
95 |
96 | public boolean isAuthenticationRequired() {
97 | return authenticationRequired;
98 | }
99 |
100 | public String getUsername() {
101 | return username;
102 | }
103 |
104 | public String getPassword() {
105 | return password;
106 | }
107 |
108 | public boolean useSecureSmtp() {
109 | return useSecureSmtp;
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/transport/EmailTransportException.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.transport;
2 |
3 | public class EmailTransportException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 959435017940801299L;
6 |
7 | public EmailTransportException(String message, Exception cause) {
8 | super(message, cause);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/transport/PostalService.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.transport;
2 |
3 | import java.util.Calendar;
4 | import java.util.Properties;
5 |
6 | import javax.activation.DataHandler;
7 | import javax.activation.FileDataSource;
8 | import javax.mail.Message;
9 | import javax.mail.MessagingException;
10 | import javax.mail.Multipart;
11 | import javax.mail.NoSuchProviderException;
12 | import javax.mail.Session;
13 | import javax.mail.internet.AddressException;
14 | import javax.mail.internet.InternetAddress;
15 | import javax.mail.internet.MimeBodyPart;
16 | import javax.mail.internet.MimeMessage;
17 | import javax.mail.internet.MimeMultipart;
18 |
19 | import com.guilhermechapiewski.fluentmail.email.Email;
20 | import com.sun.mail.smtp.SMTPTransport;
21 |
22 | public class PostalService {
23 |
24 | private static EmailTransportConfiguration emailTransportConfig = new EmailTransportConfiguration();
25 | private static Session session;
26 |
27 | public void send(Email email) throws AddressException, MessagingException {
28 | Message message = createMessage(email);
29 | send(message);
30 | }
31 |
32 | protected Session getSession() {
33 | if (session == null) {
34 | Properties properties = System.getProperties();
35 | properties.put("mail.smtp.host", emailTransportConfig
36 | .getSmtpServer());
37 | properties.put("mail.smtp.auth", emailTransportConfig
38 | .isAuthenticationRequired());
39 |
40 | session = Session.getInstance(properties);
41 | }
42 |
43 | return session;
44 | }
45 |
46 | protected Message createMessage(Email email) throws MessagingException {
47 | Multipart multipart = new MimeMultipart();
48 |
49 | MimeBodyPart mimeText = new MimeBodyPart();
50 | mimeText.setText(email.getBody());
51 | multipart.addBodyPart(mimeText);
52 |
53 | Message message = new MimeMessage(getSession());
54 | message.setFrom(new InternetAddress(email.getFromAddress()));
55 |
56 | for (String to : email.getToAddresses()) {
57 | message.setRecipients(Message.RecipientType.TO, InternetAddress
58 | .parse(to));
59 | }
60 |
61 | for (String cc : email.getCcAddresses()) {
62 | message.setRecipients(Message.RecipientType.CC, InternetAddress
63 | .parse(cc));
64 | }
65 |
66 | for (String bcc : email.getBccAddresses()) {
67 | message.setRecipients(Message.RecipientType.BCC, InternetAddress
68 | .parse(bcc));
69 | }
70 |
71 | for (String attachment : email.getAttachments()) {
72 | MimeBodyPart mimeAttachment = new MimeBodyPart();
73 | FileDataSource fds = new FileDataSource(attachment);
74 | mimeAttachment.setDataHandler(new DataHandler(fds));
75 | mimeAttachment.setFileName(fds.getName());
76 | multipart.addBodyPart(mimeAttachment);
77 | }
78 |
79 | message.setContent(multipart);
80 | message.setSubject(email.getSubject());
81 | message.setHeader("X-Mailer", "Fluent Mail API");
82 | message.setSentDate(Calendar.getInstance().getTime());
83 |
84 | return message;
85 | }
86 |
87 | protected void send(Message message) throws NoSuchProviderException,
88 | MessagingException {
89 | SMTPTransport smtpTransport = (SMTPTransport) getSession()
90 | .getTransport(getProtocol());
91 | if (emailTransportConfig.isAuthenticationRequired()) {
92 | smtpTransport.connect(emailTransportConfig.getSmtpServer(),
93 | emailTransportConfig.getUsername(), emailTransportConfig
94 | .getPassword());
95 | } else {
96 | smtpTransport.connect();
97 | }
98 | smtpTransport.sendMessage(message, message.getAllRecipients());
99 | smtpTransport.close();
100 | }
101 |
102 | protected String getProtocol() {
103 | String protocol = "smtp";
104 | if (emailTransportConfig.useSecureSmtp()) {
105 | protocol = "smtps";
106 | }
107 | return protocol;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/validation/EmailAddressValidator.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.validation;
2 |
3 | import javax.mail.internet.AddressException;
4 | import javax.mail.internet.InternetAddress;
5 |
6 | public class EmailAddressValidator {
7 |
8 | /**
9 | * Checks if an e-mail address is valid.
10 | *
11 | * @param emailAddress
12 | * The address to validate.
13 | * @return true if the address is valid, false otherwise.
14 | */
15 | public boolean validate(String emailAddress) {
16 | if (emailAddress == null) {
17 | return false;
18 | }
19 |
20 | try {
21 | // Validate using Java Mail API
22 | // Don't know if this is the best way, but it's good enough for now
23 | new InternetAddress(emailAddress, true);
24 | } catch (AddressException e) {
25 | return false;
26 | }
27 |
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/validation/IncompleteEmailException.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.validation;
2 |
3 | public class IncompleteEmailException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = -5356669884453957632L;
6 |
7 | public IncompleteEmailException(String message) {
8 | super(message);
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/com/guilhermechapiewski/fluentmail/validation/InvalidEmailAddressException.java:
--------------------------------------------------------------------------------
1 | package com.guilhermechapiewski.fluentmail.validation;
2 |
3 | public class InvalidEmailAddressException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 7521502257697884074L;
6 |
7 | public InvalidEmailAddressException(String message) {
8 | super(message);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------