JSP與JavaMail之4(發送HTML格式郵件)

來源:互聯網
上載者:User
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();
%>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.