就几行代码,直接上:
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(25);
Socket s;
do {
s = ss.accept();
deal(s);
}while(true);
}
static void deal(Socket s) throws IOException{
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
PrintWriter out = new PrintWriter(os, true);
out.println("220");
String line;
while( !"DATA".equals((line = br.readLine())) )
out.println("250");
out.println("354");
StringBuilder data = new StringBuilder();
try {
while( (line = br.readLine()) != null){
if(".".equals(line))break;
data.append(line).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
do {
out.println("250");
}while( !"QUIT".equals((line = br.readLine())) );
out.println("221 bye");
CloseableUtil.close(is, os, s);
System.out.println(data);
}
这只是个简单的示例。内容一般为base64编码,subject、from、to如果有中文,需要解码:
//subject解码
static String decode(String subject){
//=?UTF-8?B?5L2g5aW977yM6YKu5Lu25Y+R6YCB5rWL6K+V?=
//=?GBK?B?1vfM4jEyM7Ch?=
Pattern p = Pattern.compile("^=\\?(.*?)\\?(.)\\?(.*)\\?=$");
Matcher m = p.matcher(subject);
if(m.find()){
Charset charset = Charset.forName(m.group(1));
String type = m.group(2);
String value = m.group(3);
byte[]bytes = null;
switch(type){
case "B"://base64
return new String(Base64.getDecoder().decode(value), charset);
case "Q"://?
//=?GBK?Q?=D6=F7=CC=E2123?=
p = Pattern.compile("(=[A-F\\d]{2})+");
m = p.matcher(value);
StringBuffer sb = new StringBuffer();
while(m.find()){
String[]tmp = m.group().split("=");
bytes = new byte[tmp.length - 1];
for(int i = 1; i < tmp.length; i++){
bytes[i - 1] = (byte) Integer.parseInt(tmp[i], 16);
}
m.appendReplacement(sb, new String(bytes, charset));
}
m.appendTail(sb);
return sb.toString();
}
}
return subject;
}