電子メール操作クラスは春にカプセル化されており、Spring構成ファイルはコントローラー、アクション、その他の場所に簡単に挿入できます。
これが構成です:
<! - メール送信者 - > <bean id = "mailsender" p:host = "$ {mail.host}" p:port = "$ {mail.port}" p:username = "$ {mail.user}" p:password = "$ {mail.passwd}"> </bean> </bean>
メール構成
電子メールの構成:mail.host = smtp.163.com mail.port = 25 mail.user = [email protected] mail.passwd = xxxxxxx mail.from = [email protected]
メールセンダーをコントローラーに注入します。
@controller public class emailController {private mailsender mailsender; @value( "$ {mail.from}")文字列emailfrom; @autowired public void setmailsender(mailsender mailsender){this.mailsender = mailsender; } @RequestMapping(value = "/sendemail"、method = requestmethod.post)public modelandview sendemail(@modelattribute( "newemail")コンタクトマイルnewemail、bindingResult bindResult、sessionstatus status){simplemailmessageメッセージ= new simplemailmessage(); message.setto(newemail.getto()); message.setfrom(emailfrom); message.setsubject(newemail.getSubject()); message.settext(newemail.getContent());文字列結果= ""; try {mailsender.send(message); result = "電子メールが送信されました!"; } catch(mailException e){result = "電子メールの送信失敗!<br/> <hr/>"+e.getmessage(); } modelandView View = new ModelAndView( "EmailResult"); view.addobject( "result"、result);戻りビュー。 }}メールフォーム:
<form:form action = "sendemail.do" method = "post" commandname = "newemail"> <div> <p> to:<form:input path = "to" cssstyle = "width:260px;"/> <form:errors path = "to" cssstyle = "to" to "cssstyle =" coler:red; cssstyle = "width:260px;"/> <form:errors path = "subject" cssstyle = "color:red;"/> </p> <p> content:<form:textarea path = "content" rows = "5" cols = "60"> </form:textarea> <br/> < <p> <入力タイプ= "submit" value = "確認と送信"/> </p> </div> </form>
添付ファイル付きのメールを送信します:
try {javamailsenderimpl senderimpl = new javamailsendermpl(); 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( "添付ファイルテストの追加"); mimemessagehelper.settext( "test"、true); filesystemResource IMG = new FilesystemResource(new File( "i:/liang.jpg")); mimemessagehelper.addattachment(mimeutility.encodeword( "3mサンプル倉庫標準配達命令template.jpg"),, img); senderimpl.send(mimemessge); } catch(Exception e){e.printstacktrace(); }