socket实现邮件发送(二)

2014-11-24 09:53:35 · 作者: · 浏览: 1
comm.setText("");
// sendMail();
// return null;
// }
// }.execute();
}
});
}


public void sendMail()
{
try
{
Socket s = new Socket(smtpServer.getText(), 25);

InputStream inStream = s.getInputStream();
OutputStream outStream = s.getOutputStream();

in = new Scanner(inStream);
out = new PrintWriter(outStream, true /* autoFlush */);

String hostName = InetAddress.getLocalHost().getHostName();

receive();
send("HELO " + hostName);
receive();
send("MAIL FROM: <" + from.getText() + ">");
receive();
send("RCPT TO: <" + to.getText() + ">");
receive();
send("DATA");
receive();
send(message.getText());
send(".");
receive();
s.close();
}
catch (IOException e)
{
comm.append("Error: " + e);
}
}

public void send(String s) throws IOException
{
comm.append(s);
comm.append("\n");
out.print(s.replaceAll("\n", "\r\n"));
out.print("\r\n");
out.flush();
}

public void receive() throws IOException
{
String line = in.nextLine();
comm.append(line);
comm.append("\n");
}

private Scanner in;
private PrintWriter out;
private JTextField from;
private JTextField to;
private JTextField smtpServer;
private JTextArea message;
private JTextArea comm;

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
}