sndu
sndu

Reputation: 1033

Sending HTML email using Java spring?

I use following code to send an email using java spring. I can send a normal text message successfully using this code. But I added the part below this (/////////) in order to send a html email. After that the message is not sending. (You can see I have added //////////// to separate my code below. above that part is working fine)

public void sendUserRegisterEmail(String receiver, String receiverEmailAddress){
            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    message.setSubject(USER_REGISTER_MESSAGE_SUBJECT);
                    message.setTo(receiverEmailAddress);
                    message.setFrom(SENDER_EMAIL_ADDRESS);
                    message.setText(String.format(USER_REGISTER_MESSAGE_BODY, receiver));

                    //////////////////////////////////////////////////////////////////////
                    Properties properties= getProperties();
                    Session session = Session.getDefaultInstance(properties);
                    MimeMessage msg = new MimeMessage(session);
                    msg.setFrom(new InternetAddress(SENDER_EMAIL_ADDRESS, "Admin"));
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(receiverEmailAddress, "user"));

                    msg.setSubject(USER_REGISTER_MESSAGE_SUBJECT,"UTF-8");

                    Multipart mp = new MimeMultipart();
                    MimeBodyPart htmlPart = new MimeBodyPart();
                    htmlPart.setContent(message,"E:\\test.html");
                    mp.addBodyPart(htmlPart);
                    msg.setContent(mp);
                    Transport.send(msg);

                }
            };
            sendEmail(preparator);
        }

This is my console after running the code. How ever I can't see any errors either. I use Itellij IDE and Jetty as the server.

DEBUG: JavaMail version 1.5.6
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map

Edit: I also followed this example and tried to send a html email. But I was unable to integrate that with my code.

This is my html file

<html>
this is s HTML text
</html>

Upvotes: 4

Views: 6341

Answers (2)

Kumar Panchal
Kumar Panchal

Reputation: 186

You can try initialise your html file in String or StringBuffer variable assume htmContent and provide as first parameter in setContent type method.

htmlPart.setContent(htmContent.toString(), "text/html");

Upvotes: 0

alex.b
alex.b

Reputation: 1528

Ok, try my snippets, they are working.

You can even put it all to one place without Spring IOC, f.e. into main() method and run.

Configuration (beans declaration)

  @Bean(name = "javaMailSender")
  public JavaMailSender javaMailSender(@Value("${mail.smtp.host}") String smtpHost,
                                       @Value("${mail.smtp.port}") int smtpPort,
                                       @Value("${mail.name}") String mailName,
                                       @Value("${mail.cred}") String mailCred) {
    Properties props = new Properties();
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");

    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setHost(smtpHost);
    javaMailSender.setPort(smtpPort);
    javaMailSender.setUsername(mailName);
    javaMailSender.setPassword(mailCred);
    javaMailSender.setJavaMailProperties(props);
    return javaMailSender;
  }

Email service

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Service("mailNotificationService")
public class MailNotificationService {
  @Value("${mail.name}")
  String mailFrom;

  @Resource
  private JavaMailSender javaMailSender;

  public void notify(String to, String subject, String message) {
    try {
      InternetAddress[] parsed;
      try {
        parsed = InternetAddress.parse(to);
      } catch (AddressException e) {
        throw new IllegalArgumentException("Not valid email: " + to, e);
      }

      MimeMessage mailMessage = javaMailSender.createMimeMessage();
      mailMessage.setSubject(subject, "UTF-8");

      MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true, "UTF-8");
      helper.setFrom(mailFrom);
      helper.setTo(parsed);
      helper.setText(message, true);

      javaMailSender.send(mailMessage);
    } catch (MessagingException ex) {
      throw new RuntimeException(ex);
    }
  }
}

Upvotes: 4

Related Questions