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 <friend@whatever.com>");
helper.setFrom("Myself <myself@whatever.com>");
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);

mailSender.send(message);

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

    <bean id="mailSender"
        class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host"><value>mail.server.com</value></property>
        <property name="username"><value>smtpusername</value></property>
        <property name="password"><value>smtppassword</value></property>
    </bean>