1, first add the mail send configuration in the spring configuration file
<BeanID= "MailSender"class= "Org.springframework.mail.javamail.JavaMailSenderImpl"> < Propertyname= "Protocol"value= "${mail.protocol}"/> < Propertyname= "Host"value= "${mail.host}"/> < Propertyname= "Port"value= "${mail.port}" /> < Propertyname= "username"value= "${mail.username}"/> < Propertyname= "Password"value= "${mail.password}"/> < Propertyname= "Javamailproperties"> <Props> <propKey= "Mail.smtp.auth">True</prop> <propKey= "Mail.smtp.starttls.enable">True</prop> </Props> </ Property> </Bean>
2, the parameters in the configuration can be written in the properties configuration file
Mail.protocol=smtpmail. from=*@*.comMail. host=smtp. *. commail. port=mail. username=Mail. password=
Code in the 3,java
First, you can define a generic mail bean
Importjava.io.Serializable;ImportOrg.springframework.web.multipart.MultipartFile; Public classEmailImplementsserializable{Private Static Final LongSerialversionuid = 1L; /**Sender **/ PrivateString Sender; /**Recipient **/ Privatestring[] address; /**Copy to **/ Privatestring[] cc; /**Dark to give **/ Privatestring[] BCC; /**Reply to **/ PrivateString ReplyTo; /**Message Subject **/ PrivateString subject;/**Message Content*/ PrivateString content; /**Accessories **/ Privatemultipartfile[] Attachment =NewMultipartfile[0]; //////////////////////////Getters & Setters//////////////////////////////
}
Send code
@Resource (name = "MailSender")PrivateJavamailsender MailSender; Public voidSendmailbysynchronizationmode (email) {MimeMessage MIME=Mailsender.createmimemessage (); Mimemessagehelper Helper; String content=email.getcontent (); Try{Helper=NewMimemessagehelper (MIME,true, "Utf-8"); Helper.setfrom (Email.getsender ());//SenderHelper.setto (Email.getaddress ());//Recipient if(Commonutils.isnotempty (EMAIL.GETCC ())) {HELPER.SETCC (EMAIL.GETCC ());//cc } if(Commonutils.isnotempty (EMAIL.GETBCC ())) {HELPER.SETBCC (EMAIL.GETBCC ());//Dark Send } if(Commonutils.isnotempty (Email.getreplyto ())) {Helper.setreplyto (Email.getreplyto ());//Reply to} helper.setsubject (Email.getsubject ());//Message SubjectHelper.settext (Content,true);//true to set HTML formatting//Handling Attachments for(Multipartfile file:email.getAttachment ()) {if(File = =NULL||File.isempty ()) { Continue; } String fileName=File.getoriginalfilename (); Try{fileName=NewString (Filename.getbytes ("Utf-8"), "Iso-8859-1"); } Catch(Exception e) {} helper.addattachment (FileName,NewBytearrayresource (File.getbytes ())); } mailsender.send (MIME); } Catch(Exception e) {e.printstacktrace (); } }
Java sends mail via Springmail