You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SendingEmailFromJavaApplications.asciidoc 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. ---
  2. title: Sending Email From Java Applications
  3. order: 12
  4. layout: page
  5. ---
  6. [[sending-email-from-java-applications]]
  7. = Sending email from Java Applications
  8. [[introduction]]
  9. Introduction
  10. ^^^^^^^^^^^^
  11. Sending email is a common feature required in many business applications.
  12. From simple notifications containing plain text to complex reports with
  13. links and multiple attachments, email is a common way of asynchronous
  14. communication with end users.
  15. This tutorial shows how to send email messages in two different ways:
  16. 1. Using the Apache Commons Email library which offers a simplified API on top of the JavaMail API.
  17. 2. Using Spring Mail Support, a utility library that encapsulates the specifics of the mailing system, also implemented on top of the JavaMail API. 
  18. Although
  19. email operations include sending, receiving, deleting, setting flags,
  20. and others depending on the specific email server in use, this tutorial
  21. only discusses email sending through SMTP.
  22. [[how-does-email-work]]
  23. How does Email Work?
  24. ~~~~~~~~~~~~~~~~~~~~
  25. Let’s start
  26. with a quick overview of the email communication process. It all begins
  27. with the end user composing a message using a client desktop or web
  28. application. The message is sent through multiple networking devices
  29. until it reaches its destination at the recipient’s machine. The
  30. relevant elements of this process are depicted in the following figure:
  31. image:https://lh5.googleusercontent.com/GbbTWnXnPml4ijiQU1mMO8tkmGSGAcmpXEGwHQJwGOFGGI3zD98_rgYaGi-0OX18M9iTtkHyif8FnJNdKX1ubdE8MXIQ4k-Ww5qu0-MC4aoOhiqjKz56p8KLyN-QdonMZzSKEEGS[javamail-tutorial]
  32. Once the end
  33. user has triggered the action to send the email, the client application
  34. connects to its configured email server, the SMTP Server, which can be
  35. described as a program capable of communicating with other SMTP Servers
  36. using the Simple Mail Transfer Protocol (SMTP). This SMTP Server can be
  37. your own server running software, such as Apache James Server, Postfix,
  38. Sendmail, qmail, or a server managed by a third party, such as Gmail,
  39. Outlook, and Yahoo Mail. 
  40. Your SMTP
  41. Server (managed by yourself or by a third party) sends the email message
  42. to the recipient’s SMTP Server. Once the message reaches its
  43. destination, it is stored in the recipient’s inbox at the recipient’s
  44. SMTP Server. Finally, the recipient can read the message by requesting
  45. it from the SMTP Server.
  46. Nowadays,
  47. SMTP is used to send email messages and IMAP (Internet Message Access
  48. Protocol) or POP (Post Office Protocol) to receive messages. In this
  49. case, your client application will use SMTP to send the message and the
  50. recipient’s SMTP Server will use SMTP to receive the message and IMAP or
  51. POP to serve the message when the recipient requests it. You don’t need
  52. to understand the specifics of these protocols in order to send email
  53. from a Java application but you might want to understand them deeper, if
  54. you are planning to implement operations such as receiving, deleting,
  55. and setting flags, or if your applications require sending zillions of
  56. emails in a batch.
  57. [[configuring-a-test-smtp-server]]
  58. Configuring a Test SMTP Server
  59. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  60. For the
  61. purposes of this tutorial, we are going to use FakeSMTP, a free email
  62. server that offers a convenient GUI for testing email sending. You can
  63. download it from the following website: https://nilhcem.github.io/FakeSMTP/download.html[https://nilhcem.github.io/FakeSMTP/download.html]
  64. Extract the
  65. content of the downloaded zip file and execute the extracted jar. You
  66. can configure a port in the Listening port option (we will use 9090 in
  67. this tutorial). Once ready, click the Start server button to start
  68. getting emails.
  69. Please note
  70. that with FakeSMTP you don’t need to provide any authentication values
  71. (they will be ignored).
  72. [[javamail-api]]
  73. JavaMail API
  74. ~~~~~~~~~~~~
  75. The JavaMail
  76. API is defined by the JSR 919 and is included in Java EE (but not in EJB
  77. Lite nor Java EE Web Profile). It provides an abstraction over mail
  78. systems which makes its API more verbose than those of Apache Commons
  79. Email and Spring Mail Support. We are not covering JavaMail in this
  80. tutorial. However, we provide an example application that uses JavaMail
  81. to send emails. You can get the code from the following link: https://github.com/alejandro-du/java-email-tutorial/blob/master/javamail-example/src/main/java/com/example/javamail/JavaMailService.java[https://github.com/alejandro-du/java-email-tutorial/blob/master/javamail-example/src/main/java/com/example/javamail/JavaMailService.java]
  82. [[apache-commons-email]]
  83. Apache Commons Email
  84. ~~~~~~~~~~~~~~~~~~~~
  85. Apache
  86. Commons Email is built on top of JavaMail and hides much of its
  87. complexity. Therefore, it offers an API that simplifies the code to
  88. implement email sending from Java applications.
  89. You must
  90. download the Commons Email jar file from the following link:
  91. https://commons.apache.org/proper/commons-email/download_email.cgi[https://commons.apache.org/proper/commons-email/download_email.cgi],
  92. or add the dependency using a dependency management system. For example,
  93. if you are using Maven, you can add the following to your pom.xml:
  94. [source, xml]
  95. ....
  96. <dependency>
  97. <groupId>org.apache.commons</groupId>
  98. <artifactId>commons-email</artifactId>
  99. <version>1.4</version>
  100. </dependency>
  101. ....
  102.  
  103. With Commons
  104. Email, you can send emails with HTML content using the `HtmlEmail` class.
  105. This class offers an abstraction to send emails with attachments. For
  106. example, during testing you can configure the `HtmlEmail` instance as
  107. follows:
  108. [source,java]
  109. ....
  110. HtmlEmail email = new HtmlEmail();
  111. email.setHostName("localhost");
  112. email.setSmtpPort(9090);
  113. email.setAuthentication("sender@test.com", "password");
  114. ....
  115.  
  116. Or if you want to use Gmail:
  117. [source,java]
  118. ....
  119. HtmlEmail email = new HtmlEmail();
  120. email.setHostName("smtp.gmail.com");
  121. email.setSmtpPort(465);
  122. email.setSSLOnConnect(true);
  123. email.setAuthentication("your-account-name@gmail.com", "your-password");
  124. ....
  125. Keep in mind
  126. that hard-coding connection parameters like this is not good practice.
  127. Instead, you should read the values from an external source (such as a
  128. properties file) so that you can use different configurations for
  129. different environments (development, testing, production). 
  130. You can use
  131. the email instance to set the sender’s email address, add recipients,
  132. and set the subject and the text of the message:
  133. [source,java]
  134. ....
  135. email.setFrom("sender@test.com");
  136. email.addTo("recipient1@test.com", "recipient2@test.com");
  137. email.setSubject("The subject");
  138. email.setHtmlMsg("This is the message.");
  139. ....
  140. The `HtmlEmail`
  141. class also exposes the attach method to add attachments to the message.
  142. You can provide these attachments as an `InputStream` so that its content
  143. can be dynamically generated at runtime if required (`FileInputStream` is
  144. always an option in case you have `File` instances instead):
  145. [source,java]
  146. ....
  147. ByteArrayDataSource dataSource = new ByteArrayDataSource(inputStream, "text/plain");
  148. DataHandler dataHandler = new DataHandler(dataSource);
  149. email.attach(dataSource, "attachment.txt", "description");
  150. ....
  151.  
  152. The `attach`
  153. method is overloaded with multiple implementations offering different
  154. ways to attach files. The one used in the previous example requires to
  155. specify a description for the attachment.
  156. You can find
  157. a complete implementation of a utility class that implements email
  158. sending using the Commons Email in the following link: https://github.com/alejandro-du/java-email-tutorial/blob/master/commons-email-example/src/main/java/com/example/javamail/CommonsEmailService.java[https://github.com/alejandro-du/java-email-tutorial/blob/master/commons-email-example/src/main/java/com/example/javamail/CommonsEmailService.java]
  159. [[spring-email-support]]
  160. Spring Email Support
  161. ~~~~~~~~~~~~~~~~~~~~
  162. Similarly to
  163. the Apache Commons Email library, Spring offers an API on top of
  164. JavaMail which abstracts away the details of the mailing system. You
  165. need to add the `spring-context-support` dependency using Maven or Gradle.
  166. There is no official download site for this dependency, but you can
  167. download it directly from the following link if required: http://mvnrepository.com/artifact/org.springframework/spring-context-support/4.2.4.RELEASE[http://mvnrepository.com/artifact/org.springframework/spring-context-support/4.2.4.RELEASE].
  168. If you are
  169. using Maven you can add the following dependency to your pom.xml:
  170. [source,xml]
  171. ....
  172. <dependency>
  173. <groupId>org.springframework</groupId>
  174. <artifactId>spring-context-support</artifactId>
  175. <version>4.2.4.RELEASE</version>
  176. </dependency>
  177. ....
  178. You start by
  179. obtaining an implementation of the `MailSender` interface. Spring provides
  180. the `JavaMailSenderImpl` class that implements `MailSender`. You can obtain
  181. an instance of this class either by configuring and injecting a bean, if
  182. you are already using Spring Framework and have configured an
  183. application context, or by direct instantiation: 
  184. [source,java]
  185. ....
  186. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  187. ....
  188. The
  189. connection to the SMTP server is configured using properties. The
  190. following example shows how to configure the `mailSender` to connect to
  191. Gmail’s SMTP server:
  192. [source,java]
  193. ....
  194. Properties properties = new Properties();
  195. properties.put("mail.smtp.host", "smtp.gmail.com");
  196. properties.put("mail.smtp.port", "465");
  197. properties.put("mail.smtp.ssl.enable", "true");
  198. mailSender.setJavaMailProperties(properties);
  199. ....
  200.  
  201. Alternatively,
  202. you can use methods defined in the `MailSender` interface to configure the
  203. host and port, but in the case of SMTP servers using SSL, you will have
  204. to provide at least the `mail.smtp.ssl.enable` property through a
  205. `Properties` object. For this reason, we prefer to configure all the
  206. settings using properties in this example.
  207. The authentication credentials are configured using the `MailSender` instance
  208. as follows:
  209. [source,java]
  210. ....
  211. mailSender.setUsername("sender@test.com");
  212. mailSender.setPassword("password");
  213. ....
  214. The next step is to create a `MimeMessage` and a `MimeMessageHelper`:
  215. [source,java]
  216. ....
  217. MimeMessage message = mailSender.createMimeMessage();
  218. MimeMessageHelper helper = new MimeMessageHelper("The message body", true);
  219. ....
  220. The second
  221. parameter is set to true to create a multipart message that will allow
  222. us to add attachments later. The `MimeMessageHelper` exposes a handful of
  223. methods to directly set up the message:
  224. [source,java]
  225. ....
  226. helper.setFrom("sender@test.com");
  227. helper.setSubject("subject");
  228. helper.setText(text, true); // true to activate multipart
  229. helper.addTo("recipient@test.com");
  230. ....
  231. There are
  232. several overloaded methods in the `MimeMessageHelper` that provide
  233. different ways to attach files. The following example uses the
  234. `ByteArrayDataSource` class to provide an attachment from an `InputStream`:
  235. [source,java]
  236. ....
  237. ByteArrayDataSource dataSource = new ByteArrayDataSource(inputStream, "text/plain");
  238. helper.addAttachment("file.txt", dataSource);
  239. ....
  240. Finally, you can send the email using the `MailSender` instance:
  241. [source,java]
  242. ....
  243. mailSender.send(message);
  244. ....
  245.  
  246. You can find
  247. a complete implementation of a utility class that implements email
  248. sending using Spring Email Support in the following link: https://github.com/alejandro-du/java-email-tutorial/blob/master/spring-mail-example/src/main/java/com/example/javamail/SpringEmailService.java[https://github.com/alejandro-du/java-email-tutorial/blob/master/spring-mail-example/src/main/java/com/example/javamail/SpringEmailService.java]
  249. [[an-example-web-application]]
  250. An Example Web Application
  251. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  252. Let’s create
  253. a Java web application to test this functionality. The application
  254. consists of a text field where users can type an email address and a
  255. button that will send an email with an attachment to the specified
  256. address.
  257. We are going
  258. to use the https://vaadin.com[Vaadin Framework] which allows us to quickly create a web
  259. application by using only the Java Programming Language. This way, we
  260. don’t need to worry about writing any HTML or JavaScript at all.
  261. Although most
  262. IDEs have plugins to easily generate a new Vaadin project, we are going
  263. to use a Maven archetype to generate the project that you can later
  264. import into your favorite IDE. You can create a new Vaadin project with
  265. Maven using the following command line: 
  266. [source]
  267. ....
  268. mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-application -DarchetypeVersion=7.6.2
  269. ....
  270. After
  271. specifying a group and artifact id, you can run `mvn clean install` to
  272. compile the project and `mvn jetty:run` to deploy and run the application.
  273. Open your browser and navigate to http://localhost:8080[http://localhost:8080] to see the application
  274. running.
  275. Open the `MyUI.java` file (it should be the only Java file in the project) and change the `init` method to the following:
  276. [source,java]
  277. ....
  278. //... imports mostly from com.vaadin package
  279. public class MyUI extends UI {
  280.    @Override
  281.    protected void init(VaadinRequest vaadinRequest) {
  282.        // the text field where users will specify their email address
  283.        TextField textField = new TextField("Your email:");
  284.        // a button with a click listener that sends the email
  285.        Button button = new Button("Send me the PDF", e -> sendEmail(textField.getValue()));
  286.        // a layout containing the previous components
  287.        VerticalLayout layout = new VerticalLayout(textField, button);
  288.        layout.setMargin(true);
  289.        layout.setSpacing(true);
  290.        setContent(layout); // sets the content for this UI
  291.    }
  292.    ...
  293. }
  294. ....
  295. Add the missing `sendEmail` method and implement it as follows:
  296. [source,java]
  297. ....
  298. private void sendEmail(String to) {
  299.     try {
  300.         // all values as variables to clarify its usage
  301.         InputStream inputStream = getClass().getResourceAsStream("/dock-magazine.pdf");
  302. String from = "sender@test.com";
  303.        String subject = "Your PDF";
  304.         String text = "Here there is your <b>PDF</b> file!";
  305.         String fileName = "file.pdf";
  306.         String mimeType = "application/pdf";
  307.         CommonsEmailService.send(from, to, subject, text, inputStream, fileName, mimeType);
  308.         Notification.show("Email sent");
  309.     } catch (MessagingException | IOException e) {
  310.         e.printStackTrace();
  311.         Notification.show("Error sending the email", Notification.Type.ERROR_MESSAGE);
  312.     }
  313. }
  314. ....
  315.  
  316. At this point
  317. you might want to create the missing `CommonsEmailService` class (or
  318. `SpringMailService` class) and implement the send method as an exercise.
  319. But if you prefer, you can take the example implementation from the
  320. following link: https://github.com/alejandro-du/java-email-tutorial/blob/master/commons-email-example/src/main/java/com/example/javamail/CommonsEmailService.java[https://github.com/alejandro-du/java-email-tutorial/blob/master/commons-email-example/src/main/java/com/example/javamail/CommonsEmailService.java]
  321. Finally, add
  322. a PDF file with the name file.pdf in the resources directory of your
  323. Maven project. You may want to use a small file so that SMTP servers
  324. would be able to accept it.
  325. Stop the
  326. Jetty server if necessary, run `mvn clean install` again, and reload the
  327. web page in the browser. The following is a screenshot of the web
  328. application: image:https://lh5.googleusercontent.com/zcy_LwtCa9TW-sP3phTlczRP9lBvE9ozaxd0Ae4yJghOjQnAjxOlhYp2n5ruLiLlroZ9HW_LEoJN-5qPJI60rXMiFvGuHcibvP5txCMhiS9ZPn1wCMYkN43Zkjqbuw1kTi0nXn_v[screenshot.png,width=622,height=433]
  329. If you have
  330. FakeSMTP running, you should be able to see the email messages sent
  331. through the web application.
  332. [[which-approach-to-use]]
  333. Which Approach to Use?
  334. ~~~~~~~~~~~~~~~~~~~~~~
  335. Choosing an
  336. option depends on different factors. However, I would recommend to use
  337. Spring Email Support if you are developing a Spring application. If not,
  338. go with Apache Commons Email, it offers the most intuitive API. Also,
  339. Apache Commons Email jar is lighter than the spring-context-support jar,
  340. as the later includes more than just the email support classes. Using
  341. the JavaMail API directly may be convenient only when you need lower
  342. level interaction with the mailing system.
  343. You can experiment with the code by downloading the example web applications
  344. from GitHub:
  345. [source]
  346. ....
  347. $ git clone https://github.com/alejandro-du/java-email-tutorial
  348. $ cd java-email-tutorial
  349. $ cd commons-email-example
  350. # (Or cd spring-mail-example)
  351. $ mvn clean install
  352. $ mvn jetty:run
  353. ....
  354.  
  355. Don’t forget to configure run FakeSMTP before using the web application deployed at
  356. http://localhost:8080[http://localhost:8080].