分类:
2008-05-15 16:10:29
邮件模板的套用:
1.编写前端页面,简单起见只输入注册用户名及邮箱地址
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaMail4.html</title>
</head>
<body>
<form action="SEND4" method="post">
username:<input type="text" name="uname"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
2.编写一个回复的HTML模板,起名为mail.properties
message=<html><body><h2>Hi,<font color=red> {0} </font>, your password is : {1} , Welcome to : <a href="http://blog.csdn.net/CodeDestiny/">My Blog</a></h2></body></html>
3.编写servlet : SEND4.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;
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 SEND4 extends HttpServlet ...{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{
response.setContentType("text/html;charset=GB18030");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("GB18030");
//绑定邮件模版,mail对应mail.properties
ResourceBundle messages = ResourceBundle.getBundle("mail");
String from = "admin@codedestiny-pc.com";
String to = request.getParameter("email");
String subject = "欢迎你注册";
String uname = request.getParameter("uname");
String upass = "codedestiny-pc";
// 确定要发送的邮件服务器的地址
String mailserver = "codedestiny-pc";
try ...{
Object[] args = ...{uname,upass};
//新建标准的格式
MessageFormat formatter = new MessageFormat("");
//从资源文件中获取相应的模版信息
formatter.applyPattern(messages.getString("message"));
//填充模版,产生回复信息
String msgtext = formatter.format(args);
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.setSubject(subject);
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(msgtext, "text/html;charset=GB18030");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
// 发送
Transport.send(msg);
} catch (Exception e) ...{
e.printStackTrace();
}
out.print("Register is OK!
");
out.print("查看信件");
out.flush();
out.close();
}
}