注:是本人完成的一个系统的一部分.
DB是postgresql,
需要自己配置一下MailServer(TOMCAT那本大厚书里带的光盘上有个试用版的,30天)
还需要几个jar包,回头找找,再传上来~
由于开发时间较早,没来得及加注释,
======================
package utils;
import java.util.*;
import javax.mail.*;
import java.io.*;
import java.util.*;
import javax.mail.internet.*;
import javax.activation.*;
import business.*;
import business.postgresql.*;
public class DTSMail {
public static void sendMail (String from,
String to,
String subject,
String body) {
try {
Properties props = new Properties();
// 路径自己配置哦~
InputStream is = new FileInputStream("C:/Tomcat 5.0/webapps/DTS/WEB-INF/classes/utils/JavaMail.properties");
props.load(is);
String host = (String)props.get("smtphost");
String name = (String)props.get("username");
String pwd = (String)props.get("password");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.auth","true");
Session ssn = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(ssn);
InternetAddress fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = ssn.getTransport("smtp");
transport.connect(host,name,pwd);
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.send(message);
transport.close();
} catch(Exception m) {
System.out.println(m.toString());
}
}
}
============================
JavaMail.properties里面自己写:
smtphost = localhost
username = david
password = 12345
============================
JavaMailProperties.java :是来读JavaMail.properties里面内容的
import java.io.*;
import java.util.*;
class JavaMailProperties {
public static void main(String[] args) throws Exception {
Properties javamail = new Properties();
InputStream in = new FileInputStream("JavaMail.properties");
javamail.load(in);
System.out.println(javamail.get("smtphost"));
System.out.println(javamail.get("username"));
System.out.println(javamail.get("password"));
}
}
=========================================
以上三个文件放到同级目录下,本人编译后放在了WEB-INF\classes\utils
(utils与action,business,entity并列)
=========================================
另外,需要在JSP上BUTTON所调用的action里加上
//MAIL SERVER 自己配置
String from = "DTS@mydomain.com";
// DAO里的方法需要自己动手拉~我的是根据姓名取得email,其实可以直接写进去
String email = userDAO.getEmailByUsername(assignTo);
String to = email;
//MAIL 的标题(写死的)
String subject = "HELLO~!";
//MAIL的内容(写死的)
String body = "\hi~BABY.";
DTSMail.sendMail(from, to, subject, body);
[此贴子已经被作者于2005-12-14 15:11:32编辑过]