一个简单的SMTP服务JAVA示例

就几行代码,直接上:

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;
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值