How do I send HTML email in Spring MVC?
Asked Answered
F

7

69

I have successfully sent simple email using this:

SimpleMailMessage mailMessage = new SimpleMailMessage();

mailMessage.setTo("[email protected]");
mailMessage.setSubject("This is the test message for testing gmail smtp server using spring mail");
mailMessage.setFrom("[email protected]");
mailMessage.setText("This is the test message for testing gmail smtp server using spring mail. \n" +
        "Thanks \n Regards \n Saurabh ");
mailSender.send(mailMessage);

What setting I need to chnage so that I can send HTML emails

Forerunner answered 13/3, 2011 at 14:3 Comment(1)
There is an another post here on how to send an email with spring. Its uses the velocity template for the HTML content of the email, in the example it used Gmail for sending emails. But I think you can configure any mail server for your use. Its also has attachment example. Send Email with Spring Using Velocity Template.Radack
W
21

I don't think that SimpleMailMessage class has such options.

I'm sure that you can do it with JavaMailSender and MimeMessagePreparator, because you need to set MIME content type for HTML.

See this link for help:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mail.html

Wheelbase answered 13/3, 2011 at 14:28 Comment(0)
P
151
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.MimeMessageHelper;

MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8");
String htmlMsg = "<h3>Hello World!</h3>";
//mimeMessage.setContent(htmlMsg, "text/html"); /** Use this or below line **/
helper.setText(htmlMsg, true); // Use this or above line.
helper.setTo("[email protected]");
helper.setSubject("This is the test message for testing gmail smtp server using spring mail");
helper.setFrom("[email protected]");
mailSender.send(mimeMessage);
Phenetole answered 19/11, 2012 at 14:5 Comment(2)
Thanks. Your answer helps. I found out that you can also use helper.setText(htmlMsg, true); which the true flag indicate the text included is HTML. It will apply content type "text/html" for an HTML mail so you don't need to line mimeMessage.setContent(htmlMsg, "text/html");Violative
You can also call helper.setText(plainText, htmlText) if you want to offer both options to email clients.Cabinda
S
25

In Spring this should be done this way:

Your email class:

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class HTMLMail
{
    private JavaMailSender mailSender;


    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String from, String to, String subject, String msg) {
        try {

            MimeMessage message = mailSender.createMimeMessage();

            message.setSubject(subject);
            MimeMessageHelper helper;
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setText(msg, true);
            mailSender.send(message);
        } catch (MessagingException ex) {
            Logger.getLogger(HTMLMail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


}

beans:(Spring-Mail.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com" />
        <property name="port" value="587" />
        <property name="username" value="[email protected]" />
        <property name="password" value="yourpassword" />

        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
    </bean>
    <bean id="htmlMail" class="com.mohi.common.HTMLMail">
        <property name="mailSender" ref="mailSender" />
    </bean>
</beans>

Usage:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Mail.xml");

        HTMLMail mm = (HTMLMail) context.getBean("htmlMail");
        String html="<p>Hi!</p><a href=\"google.com\">Link text</a>";
    mm.sendMail("[email protected]",
            "[email protected]",
            "test html email",
            html);

Full example here .

Stocktonontees answered 28/6, 2014 at 21:35 Comment(0)
W
21

I don't think that SimpleMailMessage class has such options.

I'm sure that you can do it with JavaMailSender and MimeMessagePreparator, because you need to set MIME content type for HTML.

See this link for help:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mail.html

Wheelbase answered 13/3, 2011 at 14:28 Comment(0)
P
9

You might be interested in checking this article: "Rich HTML email in Spring with Thymeleaf" http://www.thymeleaf.org/doc/articles/springmail.html

It uses Thymeleaf as a templating view layer, but the concepts and Spring-specific code explained there are common to all Spring applications.

Besides, it has a companion example application which source code you can use as a base for your needs.

Regards, Daniel.

Paravane answered 22/2, 2012 at 11:43 Comment(0)
L
5

Class Level:

public String sendEmailToUsers(String emailId,String subject, String name){
    String result =null;
    MimeMessage message =mailSender.createMimeMessage();
    try {

        MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
        String htmlMsg = "<body style='border:2px solid black'>"
                    +"Your onetime password for registration is  " 
                        + "Please use this OTP to complete your new user registration."+
                          "OTP is confidential, do not share this  with anyone.</body>";
        message.setContent(htmlMsg, "text/html");
        helper.setTo(emailId);
        helper.setSubject(subject);
        result="success";
        mailSender.send(message);
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }finally {
        if(result !="success"){
            result="fail";
        }
    }

    return result;

}

XML Level:

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="********@gmail.com" />
    <property name="password" value="********" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>
Linter answered 14/11, 2017 at 10:46 Comment(0)
N
0

Try this.

public class Emailer{
@Autowired
JavaMailSender mailSender;

public void sendMail() throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, "utf-8");
    helper.setFrom("[email protected]");
    helper.setTo(new InternetAddress[] {
            new InternetAddress("[email protected]"),
            new InternetAddress("[email protected]")
            });
    helper.setSubject("my subject");
    
    StringBuffer sb = new StringBuffer();
    sb.append("<table>");
    for (BlogDto dto:newBlog) {
        sb.append("<tr>");
        sb.append("<td>");
        sb.append("Cell");
        sb.append("</td>");
        sb.append("</tr>");
    }
    sb.append("</table>");
    this.mailSender.send(message);
    this.logger.info("Email sent");
    return;
}

}

Newell answered 6/5, 2023 at 5:9 Comment(0)
B
-1
String emailMessage = report.toString();
            Map velocityContext = new HashMap();
            velocityContext.put("firstName", "messi");
            velocityContext.put("Date",date );  
            velocityContext.put("Exception",emailMessage );
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "VelocityTemplate.vm","UTF-8", velocityContext);
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper;
            helper = new MimeMessageHelper(message, true);
            helper.setTo("[email protected]");
            helper.setFrom("[email protected]");
            helper.setSubject("new email");
            helper.setText(text, true);         
            mailSender.send(message);
Belayneh answered 6/8, 2015 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.