woniper

이메일 전송 본문

Spring

이메일 전송

woniper 2014.07.13 09:36

1. 개발환경

  • Spring 4.0.3
  • Maven
  • JavaConfig

2. pom.xml

   

        
            org.springframework
            spring-support
            2.0.8
        
        
            javax.mail
            mail
            1.4.7
        


3. MailSender 설정(javaConfig)

config.xml




    smtp.gmail.com
    25
    UTF-8
    이메일 주소
    이메일 비밀번호
    true


javaConfig

    import com.woniper.service.MailService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.MailSender;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.stereotype.Service;

    @Value("${mail.host}")      private String mailHost;
    @Value("${mail.port}")      private int mailPort;
    @Value("${mail.username}")  private String mailUserName;
    @Value("${mail.password}")  private String mailPassword;
    @Value("${mail.encoding}")  private String mailEncoding;
    @Value("${mail.smtp.auth}") private boolean smtpAuth;

    @Bean
    public MailSender javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(mailHost);
        javaMailSender.setPort(mailPort);
        javaMailSender.setUsername(mailUserName);
        javaMailSender.setPassword(mailPassword);
        javaMailSender.setDefaultEncoding(mailEncoding);
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", smtpAuth);
        properties.put("mail.smtp.starttls.enable", smtpAuth);
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }

4. Service 구현

import com.woniper.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

/**
 * Created by woniper on 2014. 6. 20..
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired private MailSender mailSender;

    @Override
    public void sendMail(String to, String subject, String msg){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(msg);
        mailSender.send(message);
    }
}

5. Service 사용(Controller)

import com.woniper.service.MailService;

@Controller
public class MailController {
    @Autowired private MailService mailService;

    @RequestMapping(value="/email")
    public @ResponseBody void emailTest() throws Exception {
        mailService.sendMail("lkw1989@naver.com", "mail test title", "mail test Contents");
    }
}


0 Comments
댓글쓰기 폼