Send Email Spring
Java provides API to send email easily but it takes time to write program and include all configuration information. Spring makes very easy to send email as its provides all the boiler plates codes only thing you will have to is just use the API and call its method to send an email. In this example I will show how easy to send email using Spring framework.
- To understand completely I will create simple maven project name: SpringSendEmail as complete project structure is below:
- pom.xml: It shows what are dependencies you will have to add:
- spring-context.xml: As we are using Spring framework and this is heart of the application from where we are loading all our beans and configuration. It’s self explanatory as I assumed you have knowledge of Spring framework.
- JavaHonk.properties: I am also including properties file where you can keep all email related properties ourside of the application so that if you want to change properties based on environments.
- log4j2.xml: Mandatory for any project I am also including its configuration:
- MailHelper.java: Main class to send an email:
- SendEmail.java: Test class to send an email:
- To test this application you could use your company SMTP host if due to some reason SMTP host is not available you could use FakeSMTP server which you could download from here. In this demo I will also use FakeSMTP server to test email functionality. To test please run SendEmail.java as Java application and it run successfully you will below out on FakeSMTP server as below:
In example above we have sent three message as below:
- Email with XLS sheet attachment
- Simple message configure in spring context file
- Error template to send message in case of error
For more information please visit Spring official site here
Download Project: SpringSendEmail