RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:30-18:00
你可能遇到了下面的问题
关闭右侧工具栏
在jsp中发送email
  • 作者:xiaoxiao
  • 发表时间:2020-12-23 10:36
  • 来源:未知

一、我们可以通过任何支持sun规范中的sun.net.smtp包的JSP引擎(如JSWDK)发送mail。 (警告:使用内置的internal Sun规范包,这将影响到你的jsp程序的可移植性。) 以下scriptlet利用SmtpClient类在jsp文件中发送email。

<%@ page import="sun.net.smtp.SmtpClient, java.io.*" %><%String from="gseshadri@hotmail.com";String to="govind@jguru.com, govi@bigfoot.com";try{SmtpClient client = new SmtpClient("mail.xxxxx.xxx");client.from(from);client.to(to);PrintStream message = client.startMessage();message.println("To: " + to);message.println("Subject: Sending email from JSP!");message.println("This was sent from a JSP page!");message.println();message.println("Cool beans! :-)");message.println();message.println("Govind Seshadri");message.println("jGuru.com");message.println();client.closeServer();}catch (IOException e){ System.out.println("ERROR SENDING EMAIL:"+e);}%>

二、 JavaMail是官方的 Java mail API,可参考 http://java.sun.com/products/javamail/。虽然该API比 sun.net.smtp.SmtpClient更丰富或者说更复杂,但它是可移植的。这里重新创建了一个 MailSender类,它包含了 JavaMail API。如下所示:

// ms_ prefix is for MailSender class variables// str prefix is for String// astr prefix is for array of Strings// strbuf prefix is for StringBuffers, etc.public MailSender(String strFrom, // senderString[] astrTo, // recipient(s)String[] astrBCC, // bcc recipient(s), optionalString strSubject, // subjectboolean debugging){ms_strFrom = strFrom; // who the message is fromms_astrTo = astrTo; // who (plural) the message is toms_debugging = debugging; // who (plural) the message is to

// set the hostProperties props = new Properties();props.put("mail.smtp.host", ms_strSMTPHost);

// create some properties and get the default SessionSession session = Session.getDefaultInstance(props, null);session.setDebug(ms_debugging);

try {// create a messagems_msg = new MimeMessage(session);

// set the fromInternetAddress from = new InternetAddress(strFrom);ms_msg.setFrom(from);

// set the toInternetAddress[] address = new InternetAddress[astrTo.length];for (int i = 0; i astrTo.length; ++i){address[i] = new InternetAddress(astrTo[i]);}ms_msg.setRecipients(Message.RecipientType.TO, address);

// set the bcc recipientsif (astrBCC != null){address = new InternetAddress[astrBCC.length];for (int i = 0; i astrBCC.length; ++i){eh.dbg("astrBCC[" + i + "] is: '" + astrBCC[i] + "'");address[i] = new InternetAddress(astrBCC[i]);}ms_msg.setRecipients(Message.RecipientType.BCC, address);}