Spring send email program for explaing the usage of javamailsender interface of javax.mail dependency. Send email example in Java using Spring framework.
Learn to send emails in Spring provided JavaMailSender interface. Here is a step-by-step example of sending emails via Gmail SMTP server. We will use javax.mail maven dependency to send emails while configuring mail properties in JavaMailSenderImpl class that implements JavaMailSender interface.
2. Sending a SimpleMailMessage using JavaMailSender
2.1. Configuring JavaMailSenderImpl and Email Template
Given is Java configuration for JavaMailSender which has been configured to use Gmail SMTP settings and we have configured a sample email template preconfigured with sender/receiver emails and email text.
We can further customize the configuration as per our needs.
The EmailService class uses the beans configured in applicationContext.xml file and uses them to send messages.
EmailService.java
importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.mail.javamail.JavaMailSender;importorg.springframework.mail.SimpleMailMessage;importorg.springframework.stereotype.Service;@Service("emailService")publicclassEmailService{@AutowiredprivateJavaMailSender mailSender;@AutowiredprivateSimpleMailMessage preConfiguredMessage;/**
* This method will send compose and send a new message
* */publicvoidsendNewMail(Stringto,String subject,String body){SimpleMailMessage message =newSimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);}/**
* This method will send a pre-configured message
* */publicvoidsendPreConfiguredMail(String message){SimpleMailMessage mailMessage =newSimpleMailMessage(preConfiguredMessage);
mailMessage.setText(message);
mailSender.send(mailMessage);}}
3. Using JavaMailSender and MimeMessagePreparator
The recommended way of using JavaMailSender interface is the MimeMessagePreparator mechanism and using a MimeMessageHelper for populating the message.
It is easy to send simple mail messages containing only HTML, with no attachments or inline elements. However, inline elements and attachments are still a major compatibility issue between email clients.
Please use the appropriate MULTIPART_MODE and test the code thoroughly before pushing the code into production.
5.1. Email Attachments
To attach a file with email, use MimeMessageHelper to attach the file with a MimeMessage.
publicvoidsendMailWithAttachment(Stringto,String subject,String body,String fileToAttach){MimeMessagePreparator preparator =newMimeMessagePreparator(){publicvoidprepare(MimeMessage mimeMessage)throwsException{
mimeMessage.setRecipient(Message.RecipientType.TO,newInternetAddress(to));
mimeMessage.setFrom(newInternetAddress("admin@gmail.com"));
mimeMessage.setSubject(subject);
mimeMessage.setText(body);FileSystemResource file =newFileSystemResource(newFile(fileToAttach));MimeMessageHelper helper =newMimeMessageHelper(mimeMessage,true);
helper.addAttachment("logo.jpg", file);}};try{
mailSender.send(preparator);}catch(MailException ex){// simply log it and go on...System.err.println(ex.getMessage());}}
5.2. Inline Resources
Sometimes, we may want to attach inline resources such as inline images in email body. Inline resources are added to the MimeMessage by using the specified Content ID. Be sure first to add the text and then the resources. If you are doing it the other way around, it does not work.
publicvoidsendMailWithInlineResources(Stringto,String subject,String fileToAttach){MimeMessagePreparator preparator =newMimeMessagePreparator(){publicvoidprepare(MimeMessage mimeMessage)throwsException{
mimeMessage.setRecipient(Message.RecipientType.TO,newInternetAddress(to));
mimeMessage.setFrom(newInternetAddress("admin@gmail.com"));
mimeMessage.setSubject(subject);MimeMessageHelper helper =newMimeMessageHelper(mimeMessage,true);
helper.setText("<html><body><img src='cid:identifier1234'></body></html>",true);FileSystemResource res =newFileSystemResource(newFile(fileToAttach));
helper.addInline("identifier1234", res);}};try{
mailSender.send(preparator);}catch(MailException ex){// simply log it and go on...System.err.println(ex.getMessage());}}
6. Demo
Time to test the spring mail sender program code. I am sending two messages from the test code. One is instantiated and composed in the test class itself, and the other is a pre-configured message from applicationContext.xml file.
importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.FileSystemXmlApplicationContext;publicclassSpringEmailTest{publicstaticvoidmain(String[] args){//Create the application contextApplicationContext context =newFileSystemXmlApplicationContext("classpath:com/howtodoinjava/core/email/applicationContext.xml");//Get the mailer instanceEmailService mailer =(EmailService) context.getBean("emailService");//Send a composed mail
mailer.sendMail("somebody@gmail.com","Test Subject","Testing body");//Send a pre-configured mail
mailer.sendPreConfiguredMail("Exception occurred everywhere.. where are you ????");}}
The above call will send the emails.
Happy Learning !!
Comments
Subscribe
14 Comments
Most Voted
NewestOldest
Inline Feedbacks
View all comments
Lokesh Gupta
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments