在SMTP中用PringWriter类进行发送密令,用println方法可以实现自动flush。
println()方法发送"data"后,会收到消息 End data with <CR><LF>.<CR><LF> ,这时即可开始发生邮件正文。
发送消息如下:
//正文主体(包括标题,发送方,接收方,内容,点)
pw.println("subject:test");
pw.println("from:"+SendUser);
pw.println("to:"+ReceiveUser);
pw.println("Content-Type: text/plain;charset=\"gb2312\"");//设置编码格式可发送中文内容
pw.println();
pw.println("可以了");
pw.println(".");
可看出在最后确实是以 \r\n.\r\n结束。但这只是在windows系统上操是这样的。如果是在linux系统上程序运行到这里就会出现 504 format error。
因为PrintWriter的println()方法自动换行功能,查看源码可看到
public PrintWriter(Writer out,
boolean autoFlush) {
super(out);
this.out = out;
this.autoFlush = autoFlush;
lineSeparator = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
lineSeparator即是PrintWriter根据当前操作系统所得到的该操作系统的换行符,当使用println()发送时就会用lineSeparator生成newLine()实现换行。在windows上换行符为“\r\n”,但在Linux上则为“\n”。所以如果在LInux上运行时,发送最终消息为"\n.\n",而不是\r\n.\r\n。导致格式错误。所以在发送正文时,要手动加上“\r\n”,且不要用println()方法。修改代码:
pw.println("subject:test");
pw.println("from:"+SendUser);
pw.println("to:"+ReceiveUser);
pw.println("Content-Type: text/plain;charset=\"gb2312\"");//设置编码格式可发送中文内容
pw.println();
pw.println("可以了");
pw.print("\r\n.\r\n");
pw.flush();