首先在你的class或src下面建一个properties文件,我新建了一个内容如下:
emailTemplate = <html> <BODY><h2>Hi\uff0c</h2><b> {0} </b><br/>\u4f60\u7684\u7528\u6237\u540d\u4e3a\uff1a{1}\uff0c\u5bc6\u7801\u662f\uff1a{2}\u6b22\u8fce\u8bbf\u95ee\uff1a<a href="http://zmx.iteye.com">\u6211\u7684IT\u6280\u672f\u6742\u8c08</a></BODY></HTML>
原文是:Hi,{0}你的用户名为:{1},密码是:{2} 欢迎访问:我的IT技术杂谈
注册页面如下:
<form action="SendTemplate"> <table align="center"> <tr> <td align="center">用户名:</td> <td> <input type="text" name="uname"> </td> </tr> <tr> <td align="center">Email:</td> <td> <input type="text" name="uemail"> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="注册"> </td> </tr> </table> </form>
注册的servlet如下:
public class SendTemplate extends HttpServlet { /** * */ private static final long serialVersionUID = -7597646570845508429L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("GBK"); // 获得邮件模板信息 ResourceBundle mailTemplateRb = ResourceBundle.getBundle("emailTemplate"); // 由管理员发送 String from = "[email protected]"; // 注册的用户邮箱 String to = request.getParameter("uemail"); // 设置主题 String subject = "欢迎来到http://zmx.iteye.com"; // 注册用户的用户名 String uname = request.getParameter("uname"); // 注册用户的密码 String upassword = "123456"; // 服务器地址 String mailServer = "PC200904071715"; // 模板参数 Object[] args = new Object[] { uname, uname, upassword }; MessageFormat formater = new MessageFormat(""); formater.applyPattern(mailTemplateRb.getString("emailTemplate")); String messageText = formater.format(args); // 设置邮件的传输协议信息 Properties transProp = System.getProperties(); // 邮件服务器地址 transProp.put("mail.smtp.host", mailServer); // 邮件传输协议中的接收协议:smtp transProp.put("mail.transport.protocol", "smtp"); // 是否通过验证 transProp.put("mail.smtp.auth", "true"); // 服务器端口 transProp.put("mail.smtp.port", "25");// 默认端口25 Session mailSession = Session.getDefaultInstance(transProp,new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("admin",""); } }); Message mailMessage = new MimeMessage(mailSession); try { mailMessage.setFrom(new InternetAddress(from)); mailMessage.setRecipient(RecipientType.TO, new InternetAddress(to)); mailMessage.setSubject(subject); mailMessage.setSentDate(new Date()); Multipart mp = new MimeMultipart(); MimeBodyPart mbp = new MimeBodyPart(); mbp.setContent(messageText, "text/html;charset=GB2312"); mp.addBodyPart(mbp); mailMessage.setContent(mp); Transport.send(mailMessage); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } response.sendRedirect("ok.jsp"); } }