附件以超文本形式,很常用,与普通的邮件,只是查了一些设置,只有处理方式有些细微的差别
代码如下:
<%@ page contentType="text/html;charset=GBK" %>
<%@ page import="java.util.*"%>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*"%>
<%@ page import="javax.activation.*" %>
<%
try{
request.setCharacterEncoding("GBK");
String from=request.getParameter("from");
String to=request.getParameter("to");
String subject=request.getParameter("subject");
String messageText=request.getParameter("content");
String password=request.getParameter("password");
//****如果是在Internet上发送电子邮件,使用这段代码自动生成SMTP的主机名称********/
//int n =from.indexOf('@');
//int m=from.length() ;
//String mailserver ="smtp."+from.substring(n+1,m);
/******************************************************************************/
String mailserver="mrlx"; //在局域网上发送电子邮件使用这句代码指定SMTP服务器
Properties prop =new Properties();
prop.put("mail.smtp.host",mailserver);
prop.put("mail.smtp.auth","true");
Session sess =Session.getInstance(prop);
sess.setDebug(true);
MimeMessage message=new MimeMessage(sess);
//给消息对象设置收件人、发件人、主题、发信时间
InternetAddress mail_from =new InternetAddress(from);
message.setFrom(mail_from);
InternetAddress mail_to =new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO,mail_to);
message.setSubject(subject);
message.setSentDate(new Date());
Multipart mul=new MimeMultipart(); //新建一个MimeMultipart对象来存放多个BodyPart对象
BodyPart mdp=new MimeBodyPart(); //新建一个存放信件内容的BodyPart对象
mdp.setContent(messageText,"text/html;charset=GBK");
mul.addBodyPart(mdp); //将含有信件内容的BodyPart加入到MimeMulitipart对象中
message.setContent(mul); //把mul作为消息对象的内容
message.saveChanges();
Transport transport = sess.getTransport("smtp");
//以smtp方式登陆邮箱,第1个参数是发送邮件用的邮件服务器SMTP地址,第2个参数为用户名,第3个参数为密码
transport.connect(mailserver,from,password);
transport.sendMessage(message,message.getAllRecipients());
transport.close();
out.println("<script language='javascript'>alert('邮件已发送!');window.location.href='index.jsp';</script>");
}catch(Exception e){
System.out.println("发送邮件产生的错误:"+e.getMessage());
out.println("<script language='javascript'>alert('邮件发送失败!');window.location.href='index.jsp';</script>");
}
%>