The email operation class has been encapsulated in Spring, and the spring configuration file can be easily injected into controllers, actions and other places.
Here is the configuration:
<!-- mail sender --> <bean id="mailSender" p:host="${mail.host}" p:port="${mail.port}" p:username="${mail.user}" p:password="${mail.passwd}"></bean>
mail configuration
Email Configuration: mail.host=smtp.163.com mail.port=25 [email protected] mail.passwd=xxxxxxx [email protected]
Inject mailSender into the controller:
@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>
Send emails with attachments:
try{ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); senderImpl.setHost("smtp.163.com"); senderImpl.setUsername("zhangfl85"); senderImpl.setPassword("851010"); senderImpl.setJavaMailProperties(props); MimeMessage mimeMessge = senderImpl.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessge,true); mimeMessageHelper.setTo("[email protected]"); mimeMessageHelper.setFrom("[email protected]"); mimeMessageHelper.setSubject("Add attachment test"); mimeMessageHelper.setText("test",true); FileSystemResource img = new FileSystemResource(new File("I:/liang.jpg")); mimeMessageHelper.addAttachment(MimeUtility.encodeWord("3M sample warehouse standard delivery order template.jpg"),,img); senderImpl.send(mimeMessge); }catch(Exception e){ e.printStackTrace(); }