Importjavax.mail.MessagingException;ImportJavax.mail.internet.MimeMessage;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.core.io.FileSystemResource;Importorg.springframework.mail.MailParseException;ImportOrg.springframework.mail.SimpleMailMessage;ImportOrg.springframework.mail.javamail.JavaMailSender;ImportOrg.springframework.mail.javamail.MimeMessageHelper;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.ResponseBody, @Controller @requestmapping ("/api") Public classSendmailcontroller {@AutowiredPrivateJavamailsender MailSender; PrivateSimplemailmessage Simplemailmessage =NewSimplemailmessage (); @RequestMapping (Value= "/sendmsg", method =requestmethod.get) @ResponseBody PublicString sendMessage () {Simplemailmessage.setsubject ("~-test-~"); Simplemailmessage.settext ("Test"); Simplemailmessage.setfrom ("[Email protected]"); Simplemailmessage.setto ("[Email protected]"); Mailsender.send (Simplemailmessage); return"Mail Sent"; } @RequestMapping (Value= "/sendmessagewithattachment", method =requestmethod.get) @ResponseBody PublicString sendmessagewithattachment () {simplemailmessage=NewSimplemailmessage (); Simplemailmessage.setfrom ("[Email protected]"); Simplemailmessage.setto ("[Email protected]"); Simplemailmessage.setsubject ("Xxxxy" ); Simplemailmessage.settext ("Dear davidwangwei456" + "\ r \ n Xxxxy" + ", see Attachment"); Sendmailwithattachment ("Xxxxy.xls", Simplemailmessage); return"Mail Sent"; } Private voidsendmailwithattachment (String filename,simplemailmessage simplemailmessage) {//Send mailMimeMessage message =Mailsender.createmimemessage (); Try{Mimemessagehelper Helper=NewMimemessagehelper (Message,true, "UTF-8"); Helper.setfrom (Simplemailmessage.getfrom ()); Helper.setto (Simplemailmessage.getto ()); Helper.setsubject (Simplemailmessage.getsubject ()); Helper.settext (Simplemailmessage.gettext ()); Filesystemresource file=NewFilesystemresource (fileName); Helper.addattachment (File.getfilename (), file); } Catch(messagingexception e) {Throw Newmailparseexception (e); } mailsender.send (message); } @RequestMapping (Value= "/hello", method =requestmethod.get) @ResponseBody PublicString Gethello () {return"Hello"; }
Spring Send mail code sample (with attachments and without attachments)