Java tutorial
package com.local.ask.controller.mail; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Olayinka */ import com.local.ask.model.UserTemp; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; @Repository @Service public class MailManagerImpl implements MailManager { @Autowired private JavaMailSender mailSender; private final String template = getTemplate(); @Override public void confirmRegistration(UserTemp userTemp) { try { MimeMessage message = mailSender.createMimeMessage(); message.setSubject("Local Ask - Confirm Registration"); message.setFrom(new InternetAddress("local.ask.com@gmail.com")); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(userTemp.getEmail()); String text; text = template.replace("{displayName}", userTemp.getDisplayName()) .replace("{email}", userTemp.getEmail()).replace("{id}", userTemp.getConfirmCode()); helper.setText(text, true); mailSender.send(message); } catch (MessagingException ex) { Logger.getLogger(MailManagerImpl.class.getName()).log(Level.SEVERE, null, ex); } } private String getTemplate() { try { URL url = getClass().getResource("mail.html"); File file = new File(url.getPath()); byte[] encoded = Files.readAllBytes(Paths.get(file.getAbsolutePath())); return new String(encoded, "UTF-8"); } catch (IOException ex) { Logger.getLogger(MailManagerImpl.class.getName()).log(Level.SEVERE, null, ex); } return ""; } }