home *** CD-ROM | disk | FTP | other *** search
- package de.trantor.mail;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Vector;
-
- public class SmtpClient {
- private String host;
- private Connection socket;
- private InputStream input;
- private OutputStream output;
- private boolean debug = false;
- private String localhost;
-
- public SmtpClient(String localhost) {
- this.localhost = localhost;
- }
-
- public void open(String host) throws Exception, IOException, ClassNotFoundException, SmtpException {
- if (this.connected()) {
- this.close();
- }
-
- this.socket = Connection.createConnection();
- this.socket.open(host, 25);
-
- try {
- this.input = this.socket.getInputStream();
- this.output = this.socket.getOutputStream();
- this.receive();
- this.execute("HELO " + this.localhost);
- } catch (SmtpException var3) {
- this.socket.close();
- this.socket = null;
- this.input = null;
- this.output = null;
- throw var3;
- }
- }
-
- public void close() throws IOException, SmtpException {
- if (this.connected()) {
- this.execute("QUIT");
- }
-
- this.socket.close();
- this.input = null;
- this.output = null;
- this.socket = null;
- }
-
- public boolean connected() {
- return this.socket != null;
- }
-
- private void send(String s) throws IOException, SmtpException {
- if (this.debug) {
- System.out.println("[SMTP/SEND] " + s);
- }
-
- this.output.write(s.getBytes());
- this.output.write(13);
- this.output.write(10);
- }
-
- private String receive() throws IOException, SmtpException {
- StringBuffer buffer = new StringBuffer("");
-
- char c;
- do {
- c = (char)this.input.read();
- if (c != -1 && c != '\r' && c != '\n') {
- buffer.append(c);
- }
- } while(c != '\r');
-
- if (this.debug) {
- System.out.println("[SMTP/RECV] " + buffer);
- }
-
- return new String(buffer);
- }
-
- private String execute(String command) throws IOException, SmtpException {
- this.send(command);
- String result = this.receive();
- char c = result.charAt(0);
- if (c != '4' && c != '5') {
- return result;
- } else {
- throw new SmtpException(result);
- }
- }
-
- public void sendMessage(Message message) throws IOException, SmtpException {
- this.sendMessage(new Envelope(message, true));
- }
-
- public void sendMessage(Envelope envelope) throws IOException, SmtpException {
- this.execute("MAIL FROM:" + envelope.getSender());
-
- for(int i = 0; i < envelope.getRecipientCount(); ++i) {
- this.execute("RCPT TO:" + envelope.getRecipient(i));
- }
-
- this.execute("DATA");
- Vector lines = envelope.getMessage().getLines();
-
- for(int i = 0; i < lines.size(); ++i) {
- String s = (String)lines.elementAt(i);
- if (s.length() != 0 && s.charAt(0) == '.') {
- s = '.' + s;
- }
-
- this.send(s);
- }
-
- this.execute(".");
- }
-
- public boolean getDebug() {
- return this.debug;
- }
-
- public void setDebug(boolean value) {
- this.debug = value;
- }
- }
-