This article introduces Javamail applications based on the SSM framework (Spring 4.0 + SpringMVC + Mybatis). If the email is based on Tencent's QQ mailbox, it is actually also a Foxmail mailbox.
First, we need to understand SMTP protocol and SSL encryption
SMTP: called Simple Mail Transfer Protocal, the goal is to provide users with efficient and reliable mail transmission. SMTP is a protocol for request response, that is, the client sends a request to the remote server. The server responds and listens to the port 25, so its working modes are two: sending SMTP and receiving SMTP.
SSL encryption: used to ensure the security of browsers and website servers. The principle is explained in the translation:
When your browser requests a secure web page from the server (usually https://)
The server sends its certificate and public key back
The browser checks whether the certificate is issued by a trusted institution, confirms that the certificate is valid and that this certificate is for this website.
A random symmetric key is encrypted using a public key, which includes the encrypted URL to send to the server together
The server decrypts the key you sent with its own private key. Then use this symmetric encryption key to decrypt the URL you requested.
The server uses the symmetric key you sent to encrypt the web page you requested. You can decrypt the web page you sent back with the same key
Then introduce how to implement javamail sending emails. First, you need to download the jar of javamail: http://xiazai.VeVB.COM/201612/yuanma/mail_jb51.jar
To enable SMTP service on the QQ mailbox that acts as a server:
Write a business class to send emails:
package com.appms.email;import java.util.Date;import java.util.Properties;import javax.mail.Address;import javax.mail.Message;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import com.sun.mail.util.MailSSLSocketFactory;public class JavaEmailSender { public static void sendEmail(String toEmailAddress,String emailTitle,String emailContent)throws Exception{ Properties props = new Properties(); // Enable debug debugging props.setProperty("mail.debug", "true"); // The sending server requires authentication props.setProperty("mail.smtp.auth", "true"); // Set the mail server host name props.setProperty("mail.host", "smtp.qq.com"); // The sending mail protocol name props.setProperty("mail.transport.protocol", "smtp"); /**SSL authentication, note that Tencent mailbox is based on SSL encryption, and all you need to enable to use **/ MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf); //Create session Session session = Session.getInstance(props); //Send messages, designed based on observer mode Message msg = new MimeMessage(session); msg.setSubject(emailTitle); //Use StringBuilder, because StringBuilder loads faster than String, and it is also very thread-safe. StringBuilder builder = new StringBuilder(); builder.append("/n"+emailContent); builder.append("/n time" + new Date()); msg.setText(builder.toString()); msg.setFrom(new InternetAddress("Your QQ Mailbox")); Transport transport = session.getTransport(); transport.connect("smtp.qq.com", "your QQ mailbox", "the independent password for you to enable the SMTP service"); //Send a message transport.sendMessage(msg, new Address[] { new InternetAddress(toEmailAddress) }); transport.close(); }}Then write a Controller class for SpringMVC framework:
/** * Jump to send email page* @return * @throws Exception */ @RequestMapping("/goSendEmail") public ModelAndView goSendEmail(HttpServletRequest request)throws Exception{ ModelAndView mv = this.getModelAndView(); String email = request.getParameter("email"); if(email!=null&&!"".equals(email)){ email = email.trim(); mv.setViewName("member/send_email"); mv.addObject("email", email); } return mv; } /** * Send email* @return * @throws Exception */ @RequestMapping(value="/sendEmail",produces="application/json;charset=UTF-8") @ResponseBody public Object sendEmail(HttpServletRequest request)throws Exception{ Map<String,String> map = new HashMap<String,String>(); String msg = "ok"; //Send status String toEMAIL = request.getParameter("EMAIL"); //Other mailbox String TITLE = request.getParameter("TITLE"); //Title String CONTENT = request.getParameter("CONTENT"); //Content JavaEmailSender.sendEmail(toEMAIL, TITLE, CONTENT); map.put("result", msg); return map; }Here we use the jQuery TIP plug-in for verification prompts, so we need to introduce the corresponding Jquery file.
<script type="text/javascript" src="source/js/jquery-1.7.2.js"></script> <!--Tip Box--> <script type="text/javascript" src="source/js/jquery.tips.js"></script>
Jquery form validation and Ajax asynchronous requests:
<!-- Send email--> <script type="text/javascript">//Send function sendEm(){ if($("#TYPE").val()=="1"){ $("#CONTENT").val(getContentTxt()); }else{ $("#CONTENT").val(getContent()); } if($("#EMAIL").val()==""){ $("#EMAIL").tips({ side:3, msg:'Please enter the email', bg:'#AE81FF', time:2 }); $("#EMAIL").focus(); return false; } if($("#TITLE").val()==""){ $("#TITLE").tips({ side:3, msg:'Please enter the title', bg:'#AE81FF', time:2 }); $("#TITLE").focus(); return false; } if($("#CONTENT").val()==""){ $("#nr").tips({ side:1, msg:'Please enter the content', bg:'#AE81FF', time:3 }); return false; } var EMAIL = $("#EMAIL").val(); var TYPE = $("#TYPE").val(); var TITLE = $("#TITLE").val(); var CONTENT = $("#CONTENT").val(); $("#zhongxin").hide(); $("#zhongxin2").show(); $.ajax({ type: "POST", url: 'retroaction/sendEmail.do?tm='+new Date().getTime(), data: {EMAIL:EMAIL,TITLE:TITLE,CONTENT:CONTENT}, dataType:'json', //beforeSend: validateData, cache: false, success: function(data){ if("ok" == data.result){ $("#msg").tips({ side:3, msg:'Send successfully!', bg:'#68B500', time:5 }); setTimeout("showdiv()",1000); }else{ $("#msg").tips({ side:3, msg:'Send failed!', bg:'#68B500', time:5 }); } } });}</script>Calls to JSP pages:
<!-- Edit email --> <div> <table > <tr> <td style="margin-top:0px;"> <div style="float: left;"><textarea name="EMAIL" id="EMAIL" rows="1" cols="50" placeholder="Please select input the other party's email address, please separate multiple email addresses with (;) semicolons">${email}</textarea></div> <div style="float: right;"><a class='btn btn-mini btn-info' onclick="dialog_open();">Edit email address</i></a></div> </td> </tr> <tr> <td> <input type="text" name="TITLE" id="TITLE" value="" placeholder="Please select input email title"/> </td> </tr> <td id="nr"> <script id="editor" type="text/plain"></script> </td> </tr> <tr> <td style="text-align: center;"> <a onclick="sendEm();">Send</a> <a onclick="top.Dialog.close();">Cancel</a> </td> </tr> </table> </div> <div id="zhongxin2" style="display:none"><br/><img src="assets/images/jzx.gif" id='msg' /><br/><h4 id='msg'>Send...</h4></div>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.