Spring中已经封装了邮件操作类,通过spring配置文件可以便捷地注入到controller、action等地方。
下面是配置:
mail配置
控制器中注入mailSender:
@Controller public class EmailController { private MailSender mailSender; @Value("${mail.from}") String emailFrom; @Autowired public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } @RequestMapping(value="/sendEmail",method=RequestMethod.POST) public ModelAndView sendEmail(@ModelAttribute("newEmail") ContactEmail newEmail, BindingResult bindResult,SessionStatus status){ SimpleMailMessage message = new SimpleMailMessage(); message.setTo(newEmail.getTo()); message.setFrom(emailFrom); message.setSubject(newEmail.getSubject()); message.setText(newEmail.getContent()); String result = ""; try{ mailSender.send(message); result = "Email was sent!"; }catch(MailException e){ result = "Sending email failed!<br/><hr/>"+e.getMessage(); } ModelAndView view = new ModelAndView("emailResult"); view.addObject("result", result); return view; } }mail form:
<form:form action="sendEmail.do" method="post" commandName="newEmail"> <div> <p> to:<form:input path="to" cssStyle="width:260px;"/> <form:errors path="to" cssStyle="color:red;"/></p> <p>subject:<form:input path="subject" cssStyle="width:260px;"/> <form:errors path="subject" cssStyle="color:red;"/></p> <p>content:<form:textarea path="content" rows="5" cols="60"></form:textarea><br/> <form:errors path="content" cssStyle="color:red;"/></p> <p><input type="submit" value="confirm and send"/></p> </div> </form:form>发送带附件的邮件: