Overall effect:
Send end: NetEase mailbox, receiving end: QQ mailbox.
1.web Front End
2. In NetEase mailbox "sent" can see the message sent through the Java code
3. Also can see this kind of effect in QQ mailbox
Implementation process:
1.web Front End (bootstrap layout)
<form action= "Mailaction!sendmail" method= "post" name= "Mailform" id= "Mailformid" > <ul class= "List-group" > <li class= "List-group-item" > <div class= "Input-group" > <span class= "Input-group-addon" id= " Basic-addon1 "> Name:</span> <input type=" text "class=" Form-control "placeholder=" Your Name "Name=" MailForm. Name "aria-describedby=" Basic-addon1 "> </div> </li> <li class=" List-group-item "> <d IV class= "Input-group" > <span class= "Input-group-addon" id= "Basic-addon2" > Telephone:</span> <input ty Pe= "text" class= "Form-control" placeholder= "Your Phone" name= "Mailform.phone" aria-describedby= "Basic-addon1" > & lt;/div> </li> <li class= "List-group-item" > <div class= "Input-group" > <span class= "Input-group-addon" id= "Basic-addon2" > Mail:</span> <input type= "text" class= "Form-control" placeholder= " Your e-mail "name=" Mailform.e_mail "aria-describedby= "Basic-addon1" > </div> </li> <li class= "List-group-item" style= "Padding-top:2" 0px; " > <span class= "label Label-default blog-label-1" > Message:</span> <br><br> <textarea r Ows= "style=" width:100% "name=" mailform.content "placeholder=" Please enter a message (do not exceed 500 characters) "></textarea> </li > <li class= "List-group-item" > <center><button onclick= "$ (' #mailFormId '). Submit ();" Type= "but
Ton "class=" btn btn-success "> Send mail </button></center> </li> </ul> </form>
2. First prepare an XML template (<xml-body> contains text in HTML format for the message).
<?xml version= "1.0" encoding= "UTF-8"?> <!--replace the spaces with full-width spaces to ensure that the HTML does not filter out the spaces--> <xml-body>
There will be some identifiers in the template, such as {i}, the table or the reserved position of the string, and then format the message through Messageformat, and then insert the formatted string into the appropriate position in the pattern.
Get XML template
String Xml_path = Servletactioncontext.getservletcontext (). Getrealpath ("/mailtemplate") + "/ Mymailtemplete.xml ";
String str=new Readerxml (). read (Xml_path);
Object[] Obj=new object[]{mailform.getname (), Mailform.getphone (), Mailform.gete_mail (), Mailform.getcontent (), "E_ Mail ", left", "right", "TW", "FB"};
Messageformat can format such a message, and then insert the formatted string into the appropriate position in the pattern
string tcontent = Messageformat.format (str, obj);
The {i} in the final XML template was replaced by obj[i] respectively.
3. Write a class readerxml to the XML template
public class Readerxml {public
string read (string path) {
string str=null;
Str=reader (path);
return str;
}
private string Reader (string path) {
saxreader reader=new saxreader ();
String Str=null;
try {
Document d=reader.read (new File (path));
Element e=d.getrootelement ();
Element htmle=e.element ("html");
Str=htmle.asxml ();
} catch (Documentexception e) {
e.printstacktrace ();
}
return str;
}
}
4. The final is our controller class Mailaction
The inclusion of a picture in the body of the HTML format is the unique identifier of the corresponding resource file using the Setcontentid () method of the MimeBodyPart class, that is, the Content-id header field in the structure organization format of the message, the MIME protocol. Corresponds to the Cid:{i} identity in the XML template, such as (Note: {i} will be replaced with the corresponding string by Messageformat.format)
public class Mailaction extends actionsupport{private mailform mailform;
Public Mailform Getmailform () {return mailform;
public void Setmailform (Mailform mailform) {this.mailform = Mailform; ///Add inline Picture private MimeBodyPart Createimagemimebodypart (String imagename) throws Messagingexception, Unsupportedencodi ngexception{filedatasource fds=new Filedatasource (Servletactioncontext.getservletcontext (). GetRealPath ("/image")
+ "/" + imagename + ". gif");
MimeBodyPart mbp=new MimeBodyPart ();
DataHandler dh=new DataHandler (FDS);
Mbp.setdatahandler (DH);
Sets the unique identifier for the corresponding resource file, that is, the Content-id header field in the structure of the message that the MIME protocol organizes; Mbp.setheader ("Content-id", imagename);
Mbp.setfilename (Mimeutility.encodetext (Fds.getname ()));
return MBP;
Public String SendMail () {try {httpservletrequest request = Servletactioncontext.getrequest (); string pwd = "************";//Sender's mailbox password String mailfrom = "***********@163.com"; NetEase's mailbox StRing Wangyifrom = mailfrom.substring (0, Mailfrom.indexof (' @ '));/NetEase mailbox username String tu = "163.com"; The suffix name String tto= "********** @qq. com" for the sender's mailbox;
Mail-Receiving mailbox String ttitle= "Someone contacted you---from Hu Junxian's personal website"; According to its physical path, the XML template String Xml_path = Servletactioncontext.getservletcontext (). Getrealpath ("/mailtemplate") + "/
Mymailtemplete.xml ";
String str=new Readerxml (). read (Xml_path); Object[] Obj=new object[]{mailform.getname (), Mailform.getphone (), Mailform.gete_mail (), Mailform.getcontent (), "E_
Mail ", left", "right", "TW", "FB"};
Messageformat can format such a message, and then insert the formatted string into the appropriate position in the pattern string tcontent = Messageformat.format (str, obj);
Properties Props=new properties (); Props.put ("Mail.smtp.host", "SMTP.")
+TU);//mailbox SMTP server address port props.put ("Mail.smtp.auth", "true");//This will validate session s=session.getinstance (props);
S.setdebug (TRUE);
MimeMessage message=new MimeMessage (s); Set sender/Recipient/subject/Letter to Message ObjectBetween internetaddress from;
from = new InternetAddress (mailfrom),//Sender's QQ mailbox Message.setfrom (from);
InternetAddress to=new internetaddress (tto);//Recipient's mailbox Message.setrecipient (MESSAGE.RECIPIENTTYPE.TO,TO);
Message.setsubject (Ttitle);
Message.setsentdate (New Date ()); Set content for the message object BodyPart mbp=new MimeBodyPart ()//Create a new BodyPart object that holds the contents of the letter mbp.setcontent (tcontent, "Text/html;charset =gb2312 ")//To BodyPart object set content and Format/encoding///for combining text and pictures," related "Mimemultipart object Multipart mm=new (" R Elated ");/create a new Mimemultipart object to hold the BodyPart object (in fact, multiple) Mm.addbodypart (MBP);//Add BodyPart to the Mimemultipart object (
Can join multiple BodyPart)//Add Picture Mm.addbodypart (Createimagemimebodypart ("E_Mail"));
Mm.addbodypart (Createimagemimebodypart ("left"));
Mm.addbodypart (Createimagemimebodypart ("right"));
Mm.addbodypart (Createimagemimebodypart ("TW"));
Mm.addbodypart (Createimagemimebodypart ("FB")); MessAge.setcontent (mm);//mm as the content of the Message object Message.savechanges ();
Transport Transport=s.gettransport ("SMTP"); Transport.connect ("SMTP." +tu, Wangyifrom, PWD);
Here Wangyifrom for the sender NetEase account transport.sendmessage (Message,message.getallrecipients ());
Transport.close ();
Actioncontext.getcontext (). GetSession (). Put ("Operations", "Mail sent successfully, please be patient and wait for reply!");
catch (Exception e) {System.out.println (e.tostring ());
Actioncontext.getcontext (). GetSession (). Put ("Errors", e.tostring ());
return "errors";
Return to "SendMail"; }
}
The above is the entire content of this article, I hope to help you learn.