JSP與JavaMail之4(發送HTML格式郵件) - 中國WEB開發者網絡 (http://www.webasp.net) -- 技術教程 (http://www.webasp.net/article/) --- JSP與JavaMail之4(發送HTML格式郵件) (http://www.webasp.net/article/18/17597.htm) |
| -- 作者:未知 -- 發佈日期: 2005-04-18 |
| 5.發送HTML格式的郵件 所謂HTML格式,就是超文本格式.你的郵件可以用HTML代碼編寫,發給對方後,對方收到的將是信息將是超文本,超文本比純文本好看多了.下以面是在以前例子的基礎上修改的程序: <%@ page contentType="text/html;charset=GB2312" %> <%request.setCharacterEncoding("gb2312");%> <%@ page import="java.util.*,javax.mail.*"%> <%@ page import="javax.mail.internet.*"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>發送成功</title> </head> <body> <% try{ String tto=request.getParameter("to"); String ttitle=request.getParameter("title"); String tcontent=request.getParameter("content"); Properties props=new Properties(); props.put("mail.smtp.host","127.0.0.1"); props.put("mail.smtp.auth","true"); Session s=Session.getInstance(props); s.setDebug(true); MimeMessage message=new MimeMessage(s); //給消息對像設置發件人/收件人/主題/發信時間 InternetAddress from=new InternetAddress("xxf@cafe.com"); message.setFrom(from); InternetAddress to=new InternetAddress(tto); message.setRecipient(Message.RecipientType.TO,to); message.setSubject(ttitle); message.setSentDate(new Date()); //給消息對像設置內容 BodyPart mdp=new MimeBodyPart();//新建一個存放信件內容的BodyPart對像 mdp.setContent(tcontent,"text/html;charset=gb2312");//給BodyPart對像設置內容和格式/編碼方式 Multipart mm=new MimeMultipart();//新建一個MimeMultipart對像用來存放BodyPart對 //象(事實上可以存放多個) mm.addBodyPart(mdp);//將BodyPart加入到MimeMultipart對像中(可以加入多個BodyPart) message.setContent(mm);//把mm作為消息對象的內容 message.saveChanges(); Transport transport=s.getTransport("smtp"); transport.connect("127.0.0.1","xxf","coffee"); transport.sendMessage(message,message.getAllRecipients()); transport.close(); %> <div align="center"> <p><font color="#FF6600">發送成功!</font></p> <p><a href="recmail.jsp">去看看我的信箱</a><br> <br> <a href="index.htm">再發一封</a> </p> </div> <% }catch(MessagingException e){ out.println(e.toString()); } %> </body> </html> 注:撰寫郵件的html文件仍然和前面(請參考jsp和Java Mail(三))那個一樣,不需要作任何修改. 怎麼樣,這個程序是不是很簡單呢?如果還有什麼不懂的話,請在下面留言.下一次我們將要講一講怎樣發送附件. (待續) |
| webasp.net |