发送HTML类型的电子邮件:
1.在前端输入页面要在上个的基础上加入对邮件类型的判断
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>
<head>
<title>JavaMail2.html</title>
</head>
<body>
<form action="SEND2" method="post">
From:<input type="text" name="from"><br>
TO:<input type="text" name="to"><br>
Subject:<input type="text" name="subject"><br>
type:<select name="type" size="1">
<option value="text/plain">Text</option>
<option value="text/html">Html</option>
</select><br>
Context:<textarea rows="3" cols="40" name="context"></textarea><br>
<input type="submit" value="send">
</form>
</body>
</html>
2.编写servlet : SEND2.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SEND2 extends HttpServlet ...{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("gb2312");
String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String context = request.getParameter("context");
String type=request.getParameter("type");
// 确定要发送的邮件服务器的地址
String mailserver = "codedestiny-pc";
try ...{
// 设置邮件的传输协议
Properties prop = System.getProperties();
prop.put("mail.smtp.host", mailserver);
// 建立邮件发送的连接
Session session = Session.getDefaultInstance(prop, null);
// 创建发送的信息的载体
Message msg = new MimeMessage(session);
// 设置相关的邮件属性
msg.setFrom(new InternetAddress(from));
// 点到点的发送
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
/**//*
* 群发 msg.setRecipients(Message.RecipientType.TO, new
* InternetAddress[]{new InternetAddress(to),new
* InternetAddress(to)}); //借助循环的标准发送
*/
msg.setSubject(subject);
msg.setSentDate(new Date());
//判断发送的Mime类型
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
//设置邮件发送数据的类型
mbp.setContent(context, type+";charset=GB18030");
//text/plain或text/html;charset=GB18030,将发送的数据进行封装
mp.addBodyPart(mbp);
msg.setContent(mp);
// 发送
Transport.send(msg);
} catch (Exception e) ...{
e.printStackTrace();
}
out.print("send ok");
out.flush();
out.close();
}
}