Sending e-mail with Java/Spring

Posted on 13-02-2013 21:24 by graham
This tutorial describes how to send e-mails using Java and Spring Framework.

Overview


To send e-mails using Spring we will need to have three items:
- a working mail service on our local system - this needs to be configured differently depending on what system your application is running on and will not be described in this tutorial
- a org.springframework.mail.javamail.JavaMailSenderImpl bean
- a sender method

Defining a JavaMailSender bean


To define this bean, you need to put the following declaration among your definitions, e.g. in the applicationContext.xml file.
applicationContext.xml
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="localhost" />
<property name="port" value="25" />
<property name="username" value="<username>" />
<property name="password" value="<password>" />

<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>

Sending e-mail


Now it's time to build a service that will use the JavaMailSender bean and will send e-mails. The complete code for the service looks like this:
EmailService.java
@Service
public class EmailService
{
@Inject
JavaMailSender mailSender;

public void sendEmail (String subject, List<String> recipients, String fromAddress, String content)
{
MimeMessage message = mailSender.createMimeMessage();

MimeMessageHelper helper;
try
{
helper = new MimeMessageHelper(message, true);

for (String recipient : recipients)
{
helper.addTo(recipient);
}

helper.setFrom(fromAddress);
helper.setSubject(subject);
helper.setText(content);

mailSender.send(message);
}
catch (javax.mail.MessagingException e)
{
e.printStackTrace();
}
}
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems