Sending e-mails with Spring

The Spring Framework allows a very simple way to send e-mails.

/* Create a MIME message */
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
helper.setTo("My friend <>");
helper.setFrom("Myself <>");
helper.setSubject("The subject");

/* Send plaintext */
String plaintext = "The text of the mail";
helper.setText(plaintext, false);

/* Send html */
String htmltext = "<html><body><p>The text of the mail</p></body></html>";
//helper.setText(htmltext, true);

/* Send both (multipart) */
//helper.setText(plaintext, htmltext);


The mailSender can be injected with the following xml in the application context.

    <bean id="mailSender"
        <property name="host"><value></value></property>
        <property name="username"><value>smtpusername</value></property>
        <property name="password"><value>smtppassword</value></property>

4 thoughts on “Sending e-mails with Spring

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s