Thứ Hai, 4 tháng 8, 2014

Gửi mail trong spring mvc

Ví dụ này mình sẽ demo cách gửi mail (gmail) trong Spring MVC  sử dụng javax.mail.
Nội dung bao gồm:

  • Gửi mail với from, to, subject, body truyền vào.
  • Gửi mail với template được tạo sẵn.
  • Gửi mail với một file đính kèm.
Demo:





Steps:
Trước hết thêm thư viện của javax.mail.

   javax.mail
   mail
   1.4.4
  

Mình sẽ tạo một service để thực hiện việc send mail.
@Service("MailService")
public class MailService {
 @Autowired
 private MailSender mailSender;
 @Autowired
 private SimpleMailMessage templateMailMessage;
 @Autowired
 private JavaMailSenderImpl javaMailSender;
}
Hàm để gửi mail theo from, to, subject, body:
public void sendMail(String from, String to, String subject, String body) {
  SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
  simpleMailMessage.setFrom(from);
  simpleMailMessage.setTo(to);
  simpleMailMessage.setSubject(subject);
  simpleMailMessage.setText(body);
  mailSender.send(simpleMailMessage);
 }
Hàm gửi mail theo một template được định nghĩa sẵn. Ta sẽ truyền vào tên và blog cho template body.
public void sendMailWithTemplate(String name, String blog) {
  SimpleMailMessage message = new SimpleMailMessage(templateMailMessage);
  message.setText(String.format(templateMailMessage.getText(), name, blog));
  mailSender.send(message);
 }
Hàm gửi mail và attach một file đính kèm( truyền path của file)
public void sendMailWithAttachment(String name, String blog, String filePath) {
  MimeMessage message = javaMailSender.createMimeMessage();
  try {
   MimeMessageHelper helper = new MimeMessageHelper(message, true);
   helper.setFrom(templateMailMessage.getFrom());
   helper.setTo(templateMailMessage.getTo());
   helper.setSubject(templateMailMessage.getSubject());
   helper.setText(String.format(templateMailMessage.getText(), name, blog));
   FileSystemResource file = new FileSystemResource(filePath);
   helper.addAttachment(file.getFilename(), file);
  } catch (MessagingException e) {
   throw new MailParseException(e);
  }
  javaMailSender.send(message);
 }
Bây giờ ta sẽ viết controller để gọi service.
@Controller
public class MailController {
 private static final Logger logger = LoggerFactory.getLogger(MailController.class);
 @Autowired
 MailService mailService;

 @RequestMapping("sendmail")
 public String send(HttpServletRequest request) {
  String from = "abc@gmail.com";
  String to = "def@gmail.com";
  String subject = "hello";
  String body = "content of my email";
  String name = "diepdv";
  String blog = "http://diepviends.blogspot.com";
  String filePath = request.getSession().getServletContext().getRealPath("/") + "/WEB-INF/classes/hello.txt";
  logger.info("send mail simple");
  mailService.sendMail(from, to, subject, body);
  logger.info("send mail with template");
  mailService.sendMailWithTemplate(name, blog);
  logger.info("send mail with file attachment");
  mailService.sendMailWithAttachment(name, blog, filePath);
  return "success";
 }
}
Đối với file attach: file hello.txt là file được đọc từ resources.
Bây giờ đến phần quan trọng nhất. config mail trong servlet:

  
   
    classpath:mailconfig.properties
    classpath:mailtemplate.properties
   
  
 
 
 
  
  
  
  
  
   
    ${mail.smtp.auth}
    ${mail.smtp.starttls.enable}
    ${mail.smtp.ssl.trust}
   
  
 
 
 
  
  
  
  
 
File mailconfig.properties
mail.host=smtp.gmail.com
mail.post=587
mail.username=abc@gmail.com
mail.password=1234567890
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.ssl.trust=smtp.gmail.com
File mailtemplate.properties
mail.from=abc@gmail.com
mail.to=def@gmail.com
mail.subject=Send mail example
mail.text=Xin chào %s, \u0111ây là n\u1ED9i dung mail template, tham kh\u1EA3o thêm t\u1EA1i %s.
Source code: https://www.mediafire.com/?7qvk2di9osc71sa

Không có nhận xét nào:

Đăng nhận xét