現(xiàn)貼出主要類,主要流程都在這個類中:
package com.blankenhorn.net.mail;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.StringTokenizer;
/**
* Provides a simple way to send emails to an SMTP server.
*
* @author Kai Blankenhorn <<a href="mailto:pub01@bitfolge.de">pub01@bitfolge.de</a>>
*/
public class EasySMTPConnection {
private String server = null;
private BufferedReader in = null;
private BufferedWriter out = null;
private Socket socket = null;
/**
* Usage example.
*/
public static void main(String[] args) {
try {
EasySMTPConnection smtp = new EasySMTPConnection("127.0.0.1");
Message msg = new Message();
msg.setTo("");
String[] source = {
"From: Test User <test.user@foo.bar>",
"To: Kai Blankenhorn <pub01@bitfolge.de>,
Somebody <somebodysaddress@somebodysserver.com>",
"Subject: EasySMTPConnection Test",
"Date: insertdate",
"Content-Type: text/plain; charset=iso-8859-1",
// you may set the message ID, but you don't have to
// "Message-ID:
"+EasySMTPConnection.createMessageID("yourserver.com"),
"",
"first line,",
"second line",
"as you can see, no need for newlines (\\n)",
""
};
msg = new Message(source);
smtp.sendMessage(msg);
} catch(MailProtocolException e) {
e.printStackTrace();
}
catch(InstantiationException e) {
e.printStackTrace();
}
}
/**
* Creates a unique message ID for an email message.
*
* @param hostName the internet name of the computer the mail is being sent from
*/
public static String createMessageID(String hostName) {
String msgID = new Date().getTime() + ".";
msgID += Thread.currentThread().hashCode();
msgID += hostName;
msgID = "<"+msgID+">";
return msgID;
}
/**
* Establishes a connection to the specified SMTP server.
*
* @param server the SMTP server to connect to
*/
public EasySMTPConnection(String server) throws InstantiationException {
this.server = server;
try {
this.open();
} catch(SocketTimeoutException e) {
throw new InstantiationException("Timeout: " + e.getMessage());
}
catch(IOException e) {
throw new InstantiationException("IO error: " + e.getMessage());
}
}
/**
* Opens the connection to the server stored in <code>server</code>.
*/
protected void open() throws SocketTimeoutException, IOException {
socket = new Socket(server, 25);
socket.setSoTimeout(5000);
socket.setKeepAlive(true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String response = read();
if(!response.startsWith("220")) {
throw new IOException(response);
}
writeln("HELO " + InetAddress.getByName(InetAddress.getLocalHost().getHostAddress())
.getHostName());
response = read();
if(!response.startsWith("2")) {
throw new IOException(response);
}
}
/**
* Close the connection.
*/
public void close() {
try {
writeln("QUIT");
socket.close();
} catch(SocketTimeoutException e) {
}
catch(IOException e) {
}
}
private String read() throws SocketTimeoutException, IOException {
String line = in.readLine();
return line;
}
private void writeln(String line) throws SocketTimeoutException, IOException {
out.write(line);
out.newLine();
out.flush();
}
/**
* Reads the server's response and checks the response code.
*
* @throws MailProtocolException if the code from the server is an error code (4xx or 5xx)
* @throws SocketTimeoutException if there was a timeout while reading from the server
* @throws IOException if there was some sort of network error
*/
protected void checkResponse() throws MailProtocolException, SocketTimeoutException, IOException {
String response = read();
if(response.startsWith("4") || response.startsWith("5")) {
throw new MailProtocolException(response);
}
}
/**
* Sends an array of Strings to the server. This method just constructs a new Message object
* based on <code>msgSource</code> and then calls {@link #sendMessage(Message)}
*
* @param msgSource An array of Strings, each element containing one line of the message source.
*
Note that
there has to be an empty line to seperate header and body of the
message.
*
You don't have
to (and you're not able to) end your message with a "." line, though.
*/
public void send(String[] msgSource) throws MailProtocolException {
Message msg = new Message(msgSource);
this.sendMessage(msg);
}
/**
* Sends a Message through the server corresponding to this instance of EasySMTPConnection.
*
* @param msg the Message to send
* @throws MailProtocolException if the server replied an error to one of the commands
*/
public void sendMessage(Message msg) throws MailProtocolException {
if (msg.getMessageID()==null || msg.getMessageID().equals("")) {
msg.setMessageID(EasySMTPConnection.createMessageID("yourserver.com"));
}
try {
socket.setSoTimeout(10000);
writeln("MAIL FROM:" + extractEmail(msg.getFrom()));
checkResponse();
StringTokenizer t = new StringTokenizer(msg.getTo(), ";,");
while(t.hasMoreTokens()) {
writeln("RCPT TO:" + extractEmail(t.nextToken()));
checkResponse();
}
t = new StringTokenizer(msg.getCC(), ";,");
while(t.hasMoreTokens()) {
writeln("RCPT TO:" + extractEmail(t.nextToken()));
checkResponse();
}
t = new StringTokenizer(msg.getBCC(), ";,");
while(t.hasMoreTokens()) {
writeln("RCPT TO:" + extractEmail(t.nextToken()));
checkResponse();
}
writeln("DATA");
checkResponse();
for(int i = 0; i < msg.getHeader().length; i++) {
writeln(encodeDot(msg.getHeader()[i]));
}
writeln("X-Sent-Through: EasySMTPConnection Java class
(http://www.bitfolge.de/en)");
writeln("");
for(int i = 0; i < msg.getBody().length; i++) {
writeln(encodeDot(msg.getBody()[i]));
}
writeln(".");
checkResponse();
} catch(IOException io) {
throw new MailProtocolException(io);
}
}
protected String extractEmail(String nameAndEmail) {
String result = nameAndEmail;
if(nameAndEmail.indexOf('<') > -1) {
result =
nameAndEmail.substring(nameAndEmail.indexOf('<') + 1,
nameAndEmail.indexOf('>'));
}
return result;
}
protected String encodeDot(String line) {
String result = line;
if(line.startsWith(".")) {
result = "." + result;
}
return result;
}
/**
* Closes the connection to the server upon finalization.
*/
public void finalize() {
this.close();
}
}
只有注冊用戶登錄后才能閱讀該文。
閱讀全文
log4j配置文件的位置應(yīng)該放在class文件的根目錄下(或者源文件根根目錄下),不要放在子目錄下,否則會由于找不到log4j配置文件而出錯.
一個quartz用的log4j配置文件內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="default" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%p] %d{dd MMM hh:mm:ss.SSS aa} %t [%c]%n%m%n%n"/>
</layout>
</appender>
<logger name="org.quartz">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="default" />
</root>
</log4j:configuration>
#DEBUG用來定義輸出級別,比DEBUG高的都可以輸出,后面的stdout,F(xiàn)ile為輸出日志的輸出地方
log4j.rootLogger=DEBUG, stdout,FILE
#定義stdout輸出的格式
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n
#定義文件輸出的格式
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=d:\\log.txt
log4j.appender.FILE.Append=true
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[send mail info] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#其中,Log4j提供的appender有以下幾種:
#org.apache.log4j.ConsoleAppender(控制臺),
#org.apache.log4j.FileAppender(文件),
#org.apache.log4j.DailyRollingFileAppender(每天產(chǎn)生一個日志文件),
#org.apache.log4j.RollingFileAppender(文件大小到達(dá)指定尺寸的時候產(chǎn)生一個新的文件),
#org.apache.log4j.WriterAppender(將日志信息以流格式發(fā)送到任意指定的地方)
#其中,Log4j提供的layout有以下幾種:
#org.apache.log4j.HTMLLayout(以HTML表格形式布局),
#org.apache.log4j.PatternLayout(可以靈活地指定布局模式),
#org.apache.log4j.SimpleLayout(包含日志信息的級別和信息字符串),
#org.apache.log4j.TTCCLayout(包含日志產(chǎn)生的時間、線程、類別等等信息)
# 下面是步驟,共10步
#1 定義了兩個輸出端
#log4j.rootLogger = debug, A1, A2
#2 定義A1輸出到控制器
#log4j.appender.A1 = org.apache.log4j.ConsoleAppender
#3 定義A1的布局模式為PatternLayout
#log4j.appender.A1.layout = org.apache.log4j.PatternLayout
#4 定義A1的輸出格式
#log4j.appender.A1.layout.ConversionPattern = %-4r [%t] %-5p %c - %m%n
#5 定義A2輸出到文件
#log4j.appender.A2 = org.apache.log4j.RollingFileAppender
#6 定義A2要輸出到哪一個文件
#log4j.appender.A2.File = D:\\hello.log
#7 定義A2的輸出文件的最大長度
#log4j.appender.A2.MaxFileSize = 1KB
#8 定義A2的備份文件數(shù)
#log4j.appender.A2.MaxBackupIndex = 3
#9 定義A2的布局模式為PatternLayout
#log4j.appender.A2.layout = org.apache.log4j.PatternLayout
#10 定義A2的輸出格式
#log4j.appender.A2.layout.ConversionPattern = %d{yyyy-MM-dd hh:mm:ss}:%p %t %c
#log4j.appender.R=org.apache.log4j.RollingFileAppender //指定以文件的方式輸出日志
#log4j.appender.R.File=c:/sys.html //文件位置
#log4j.appender.R.MaxFileSize=500KB //文件最大尺寸
#log4j.appender.R.MaxBackupIndex=1 //備份數(shù)
#log4j.appender.R.layout=org.apache.log4j.HTMLLayout //文件的格式為Html格式
#log4j.appender.R.layout=org.apache.log4j.PatternLayout
#log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
#輸出格式
#%m 輸出代碼中指定的消息
#%p 輸出優(yōu)先級,即DEBUG,INFO,WARN,ERROR,F(xiàn)ATAL
#%r 輸出自應(yīng)用啟動到輸出該log信息耗費(fèi)的毫秒數(shù)
#%c 輸出所屬的類目,通常就是所在類的全名
#%t 輸出產(chǎn)生該日志事件的線程名
#%n 輸出一個回車換行符,Windows平臺為“\r\n”,Unix平臺為“\n”
#%d 輸出日志時間點(diǎn)的日期或時間,默認(rèn)格式為ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},輸出類似:2002年10月18日 22:10:28,921
#%l 輸出日志事件的發(fā)生位置,包括類目名、發(fā)生的線程,以及在代碼中的行數(shù)。舉例:Testlog4.main(TestLog4.java:10)
#一個教程網(wǎng)址:http://www.solol.org/technologic/java/j-log4j/
http://jakarta.apache.org/commons/email/userguide.html.
注意要設(shè)置字符集
email.setCharset("gb2312");
Properties props = System.getProperties();
props.setProperty("proxySet", "true");
props.setProperty("http.proxyHost", "192.168.0.200");
props.setProperty("http.proxyPort", "3128");