Search code examples
javaspring-boothtml-email

Spring boot java mail with template html


I am using an html template which is used as content in my JavaMail. the problem is The font-family is not working. if i run the html program on the browser, it works. but when sent as email content, this font does not work. the system uses the default font instead.

Content html :

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title></title>
    <link rel="icon" href="#"/>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;600;700;800;900&display=swap" rel="stylesheet" />

    <style>
        body {
          font-family: 'Nunito', sans-serif;
          margin: 0;
        }
        .wrapper {
          width: 100%;
          max-width: 800px;
          margin: 0 auto;
          background-color: #ffffff;
          font-size: 14px;
        }
        .email-body {
          padding: 20px;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <div class="email-body">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tempus at velit ac vehicula. 
           Sed ut porta augue, id cursus massa. Cras aliquam tempus lacus nec eleifend. Fusce enim odio,
           finibus eu ligula et, imperdiet placerat lorem. Fusce feugiat neque tincidunt, 
           placerat urna ullamcorper, laoreet tortor. Nulla congue ante eget odio egestas, ut eleifend justo volutpat. 
           Aliquam malesuada, quam nec pharetra ultrices, metus lacus elementum nisl, sed viverra eros nulla vitae nunc. Donec aliquet luctus mauris, sit amet dignissim risus lacinia id. Aliquam suscipit, turpis eu scelerisque tristique, mi turpis consequat sem, ac euismod elit turpis ac diam.</p>
    </div>
</div>
</body>
</html>

JavaMail.class

public void sendEmail(String host, String port, String username, String password, List<String> to, String subject, String content) throws MessagingException {
        
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,password);
            }
        });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            InternetAddress[] toAddress = new InternetAddress[to.size()];

            for( int i = 0; i < to.size(); i++ )
                toAddress[i] = new InternetAddress(to.get(i));
            
            for( int i = 0; i < toAddress.length; i++)
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            
            message.setSubject(subject);
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(content, "utf-8", "html"); //here the email template is inputted
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            
            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            logger.info("Send Email Success To : " + to.get(0));
        } catch (MessagingException e) {
            logger.info("Send Email Error Caused By : " + e.getMessage());
        }
    }

how to solve this problem?


Solution

  • I changed the font fetch method like this. and it worked

    This is deleted

    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;600;700;800;900&display=swap" rel="stylesheet" />
    

    Add this inside the <style> tag

    @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;600;700;800;900&display=swap');