Chapter 8: Sending email with Javalin

Dependencies

First, we need to create a Maven project with some dependencies: (→ Tutorial)

pom.xml
 1 <dependencies>
 2     <dependency>
 3         <groupId>io.javalin</groupId>
 4         <artifactId>javalin</artifactId> <!-- For handlin\
 5 g http-requests -->
 6         <version>{{site.javalinversion}}</version>
 7     </dependency>
 8     <dependency>
 9         <groupId>org.apache.commons</groupId>
10         <artifactId>commons-email</artifactId> <!-- For s\
11 ending emails -->
12         <version>1.4</version>
13     </dependency>
14     <dependency>
15         <groupId>com.j2html</groupId>
16         <artifactId>j2html</artifactId> <!-- For creating\
17  HTML form -->
18         <version>1.0.0</version>
19     </dependency>
20     <dependency>
21         <groupId>org.slf4j</groupId>
22         <artifactId>slf4j-simple</artifactId> <!-- For lo\
23 gging -->
24         <version>1.7.25</version>
25     </dependency>
26 </dependencies>

Setting up the backend

We need three endpoints: GET '/', POST '/contact-us' and GET '/contact-us/success':

example
  1 import org.apache.commons.mail.*;
  2 import io.javalin.Javalin;
  3 import static j2html.TagCreator.*;
  4 
  5 public class Main {
  6 
  7     public static void main(String[] args) {
  8 
  9         Javalin app = Javalin.create()
 10             .port(7000)
 11             .start();
 12 
 13         app.get("/", ctx -> ctx.html(
 14             form().withAction("/contact-us").withMethod("\
 15 post").with(
 16                 input().withName("subject").withPlacehold\
 17 er("Subject"),
 18                 br(),
 19                 textarea().withName("message").withPlaceh\
 20 older("Your message ..."),
 21                 br(),
 22                 button("Submit")
 23             ).render()
 24         ));
 25 
 26         app.post("/contact-us", ctx -> {
 27             Email email = new SimpleEmail();
 28             email.setHostName("smtp.googlemail.com");
 29             email.setSmtpPort(465);
 30             email.setAuthenticator(new DefaultAuthenticat\
 31 or("YOUR_EMAIL", "YOUR_PASSWORD"));
 32             email.setSSLOnConnect(true);
 33             email.setFrom("YOUR_EMAIL");
 34             email.setSubject(ctx.formParam("subject")); /\
 35 / subject from HTML-form
 36             email.setMsg(ctx.formParam("message")); // me\
 37 ssage from HTML-form
 38             email.addTo("RECEIVING_ADDRESS");
 39             email.send(); // will throw email-exception i\
 40 f something is wrong
 41             ctx.redirect("/contact-us/success");
 42         });
 43 
 44         app.get("/contact-us/success", ctx -> ctx.html("Y\
 45 our message was sent"));
 46 
 47     }
 48 
 49 }
 50 ~~~~~~
 51 
 52 In order to get the above code to work, you need to make \
 53 some changes:
 54 
 55 * Change `YOUR_EMAIL` to your gmail account <small>(youre\
 56 mail@gmail.com)</small>
 57 * Change `YOUR_PASSWORD` to your gmail password*
 58 * Change `RECEIVING_ADDRESS` to where you want the email \
 59 to be sent
 60 
 61 **It might be a good idea to create a test-account instea\
 62 d of using your real gmail credentials.*
 63 
 64 When you have made the changes to the code, run the progr\
 65 am and go to `http://localhost:7000`.
 66 You will see a simple unstyled form with an input field, \
 67 a textarea and a button.
 68 Fill in the form and click the button to test your email \
 69 server. After you click the button, your browser
 70 is redirected to `/contact-us/success` (if the email was \
 71 sent).
 72 
 73 Any emails you have sent will show up in your `Sent` fold\
 74 er in the gmail web-interface.
 75 
 76 {bump-link-number}
 77 
 78 {leanpub-filename="chapter9.txt"}
 79 
 80 # Chapter 9: Deploying Javalin apps to Heroku
 81 
 82 ## What is Heroku?
 83         Heroku is a cloud application platform  a new wa\
 84 y of building and deploying web apps.
 85         Our service lets app developers spend their time \
 86 on their application code,
 87         not managing servers, deployment, ongoing operati\
 88 ons, or scaling.
 89         &mdash; <a href="https://www.heroku.com/about">he\
 90 roku.com</a>
 91 
 92 Heroku takes care of everything related to deployment, an\
 93 d gives
 94 you easy access to key commands via their tool Heroku Too\
 95 lbelt.
 96 It's very easy to get started with (as you'll soon learn)\
 97 , and it
 98 provides a nice free-tier that you can use to deploy your\
 99  webapps.
100 
101 ## Initial Setup
102 Before we get started, there are a few things we need to \
103 do:
104 
105 * Create a free Heroku account [(sign up)](https://signup\
106 .heroku.com/dc)
107 * Install [Heroku Toolbelt](https://toolbelt.heroku.com/)
108 * Install [Maven](https://maven.apache.org/guides/getting\
109 -started/maven-in-five-minutes.html)
110 * Set up the Javalin Hello World example with Maven [( T\
111 utorial)](/tutorials/maven-setup)
112 
113 ## Configuring Maven
114 This is actually where most of the work is done. In order\
115  to easily
116 deploy a Java application anywhere, you have to create a \
117 jar file
118 containing your application and all of its dependencies.
119 Open the pom.xml of your Javalin Maven project and add the
120 following configuration (below your dependencies tag):
121 
122 {title="pom.xml", lang=xml}

<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>Main</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build>

Configuring Heroku

Before we can configure anything, we actually have to create a Heroku application. This can be done by using the heroku create command.
Open a terminal and navigate to your project root, then enter:

1 heroku create javalin-heroku-example #choose your own app\
2 lication name

Now that you have a Heroku application, we have to configure how to deploy it using Maven. This is pretty straightforward using the Heroku Maven plugin.

We specify the JDK version and the app-name, along with the launch config:

pom.xml
 1 <plugin>
 2     <groupId>com.heroku.sdk</groupId>
 3     <artifactId>heroku-maven-plugin</artifactId>
 4     <version>1.1.3</version>
 5     <configuration>
 6         <jdkVersion>1.8</jdkVersion>
 7         <appName>javalin-heroku-example</appName>
 8         <processTypes>
 9             <!-- Tell Heroku how to launch your applicati\
10 on -->
11             <web>java -jar ./target/javalin-heroku-exampl\
12 e-1.0-jar-with-dependencies.jar</web>
13         </processTypes>
14     </configuration>
15 </plugin>

When you’ve added the Heroku config to your pom, it should look like this

Making Javalin Listen on the Correct Port

The only thing left is making sure Javalin can handle your requests. Heroku assigns your application a new port every time you deploy it, so we have to get this port and tell Javalin to use it:

 1 import io.javalin.Javalin;
 2 
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         Javalin app = Javalin.create()
 7             .port(getHerokuAssignedPort())
 8             .start()
 9             .get("/", ctx -> ctx.result("Hello Heroku"));
10     }
11 
12     private static int getHerokuAssignedPort() {
13         ProcessBuilder processBuilder = new ProcessBuilde\
14 r();
15         if (processBuilder.environment().get("PORT") != n\
16 ull) {
17             return Integer.parseInt(processBuilder.enviro\
18 nment().get("PORT"));
19         }
20         return 7000;
21     }
22 
23 }

Now we can deploy our application using mvn heroku:deploy.

Again, make sure you’re in your project root, then enter:

1 mvn heroku:deploy

That’s it. Our application is now available at https://<appname>.herokuapp.com/