Join us
@sofiatarhonska ・ Sep 22,2022 ・ 7 min read ・ 2274 views ・ Originally posted on mailtrap.io
A step-by-step guide on how to create a landing page that sends a welcome email to subscribers (source)
This article is a step-by-step guide on how to create a landing page that sends a welcome email to subscribers. This will be developed with Java and Spring Boot. It will also show all the required processes for the download of tools and the test for running the web application.
Starting any application with Spring is a good way to use Spring Tools as it improves the IDEs and brings features to facilitate the codification. This article will be using the Spring Tool 4 for Eclipse on Mac OS. However, it’s also available for Visual Studio Code and Theia, and it can be downloaded from Spring Tools. Choose which one is better for you and download it.
Another useful tool for starting a Spring Boot project is the Spring Initializr (https://start.spring.io/), which has a web interface where the configuration of the project can be set up and the dependencies can be chosen. After filling out the form, the project can be downloaded and imported from Spring Tools with the Import Spring Getting Started Content option.
Another way to create a Spring project is using Spring Tools, which provides a feature called Create a New Spring Starter Project. It’s a wizard with the same options available on the web interface.
This article will be using a Gradle Project with Java 15. The dependencies used are:
The image below shows the Spring Initializr form filled out to guide you. Note that the Group field represents the project packages and must be filled with com.domain.
After filling, click on the GENERATE button to download your initialized project. Then, open Spring Tools and click on Import Spring Getting Started Content to open your downloaded project.
If you prefer to do this directly on Spring Tools, click on Create New Spring Starter Project. In the window, the New Spring Starter Project fills the text inputs with the full name and description and chooses the options listed below.
Click on Next and choose the dependencies Spring Web and Java Mail Sender. Now, just click Finish to create your project.
A project created with the wizard on Spring Initializr or on Spring Tools will have the build.gradle file filled with the configurations that the project needs to run. Check if your build.gradle has the Thymeleaf as dependencies, it will be necessary to associate the pages with the model in the next steps.
In the LandingApplication.java file, we will define the listener on our web application. It is basically a class with a main method and @SpringBootApplication. This class will create the ApplicationContext and launch the web application. Inside the main method, we need to call run from SpringApplication to start it.
The class model will be used to store the name and email used in the form. These pieces of information will navigate across the controller and mailer. We need to create a new package to put the model in. Usually, the package will have the model and the controller separating the code by subjects. Following this package structure helps the Spring Boot to scan and find the classes. Another way is to separate a package for models and another for controllers – this is also a valid approach.
The first version of our controller implements two routes: GET and POST methods. A method called showForm will receive a subscribe object and mapping to render the form page. This page will have a form with fields for name and email, and also a Submit button. This submits our second method submitForm, which also receives the subscribing object as a parameter. For now, this method will only redirect to the successful subscribe page.
It’s important to highlight that the addViewControllers method is necessary for registering the view that will be used for redirection with the POST method.
In the src/main/resources/templates package, we’ll create a package called Subscribe to store our HTML files for our views and pages. The form.html file will contain the form and will be the page shown when accessed.
Note that the object has to be the same name as your parameter on the submitForm and the action must be the same as defined on PostMapping.
The confirmation.html file has only a message informing us that everything works. This will be shown after submitting the form.
Start your application by clicking on the Run button, or open a terminal, go to the project directory, run ./gradlew bootRun on the terminal, and access the URL http://localhost:8080 – it’ll show a page similar to the image below.
Fill out the form and click on the Subscribe button to see the redirect in action and the confirmation page.
If you see this, you can move forward, so let’s implement the sending email.
To test our sending emails, we’ll use Mailtrap. Mailtrap is a service for inspecting the email content received before sending it in production. Mailtrap is free for personal side projects, so we can send 500 emails per month and test our application in development and even staging environments.
To start using Mailtrap access https://mailtrap.io/ home page, create your account, and log in to it.
On the sidebar, access the Testing > Inboxes menu. In the shows Projects panel, click on Add Inbox.
Fill the Inbox name field with a meaningful name, such as Subscribers, and then click on the Save button.
Now click on Subscribers to access the configuration page.
Click on Show Credentials to see the SMTP information required to send the email. This information will be added to the Properties in our Mail class.
We also need to get the email used as the sender. To get this, click on the Email Address tab and copy the Inbox Email Address.
Create a new package called Mailer and a new class called Mail. In this class, create constants to store the configuration that you got from Mailtrap. The setProperties method assigns the constants to the Properties object that will be used to create a session authentication with Mailtrap credentials.
The send method creates a message with email fields such as from, recipient, subject, content, and date. The send method of Transport class is responsible for sending the message to Mailtrap inbox.
With Mail class created, we need to call the send method when the form was submitted. To do this, create a new instance from Mail in the submitForm method on SubscribeController. This instance will call the send method to pass the subscribe as a parameter. This parameter contains the email and name used to mount the email that will be sent. It’ll throw AddressException, MessagingException and IOException exceptions, and will also need to import these packages.
Run the application again, access http://localhost:8080, fill the form and click on the Subscribe button. Go back to Mailtrap and access Inboxes > Subscribers to see the received email.
Now let’s try sending emails with attachments. Add an image to src/main/resources/static. In my case, I used an image called fine.jpeg.
We need to change the content of the email body to work with multipart to add the message and the attachment. The multipart instance will be initialized on the Mail constructor and will be accessed by the receiver. Two new methods were created: the setMessage to include the multipart as content and the setAttachment to attach the file. After adding this body’s parties to multipart, we can set the multipart as the content of the MimeMessage instance.
Re-run the application, access http://localhost:8080, fill out the form, and click on the Subscribe button. Go back to Mailtrap and access Inboxes > Subscribers to view the received email with the attachment. You can download it to check whether the image arrived without any issues.
When we set the content, we can parse the type of our content. In the example above, we are already parsing text/html as a type. Using this configuration, we can parse any HTML code inside a string and send the email with HTML formatting. Something like this will work and send a formatted email.
But we can improve it using StringBuffer to create a string with all the content.
Another more sophisticated option is to use some templates for our email and pass the variable as a parameter to the HTML file. Some options that work well with Spring Boot are Thymeleaf and FreeMaker.
One more time, run the application, access http://localhost:8080, fill out the form, and click on the Subscribe button. Go back to Mailtrap and access Inboxes > Subscribers to see the received email with HTML and CSS formatting.
Click on the HTML Source tab to see the generated HTML.
Another awesome feature of Mailtrap is showing whether the HTML and CSS in our email are valid in the email clients. Click on the Check HTML tab to verify the errors.
There are other ways to send an email with Spring Boot. With fewer changes, we can, for example, move the authentication constants from Mail class to the application.properties. We can also use some templates to improve the HTML emails. It’s important to see other possibilities to refactor and grow our code. Did you see something to improve here? Let’s talk!
Thanks for reading our guide on how to send emails using Java Spring, which was originally published in the Mailtrap Blog. I hope you had a great time!
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.