emailsender.java

来自「J2ME 无线通信技术应用开发源代码」· Java 代码 · 共 57 行

JAVA
57
字号
import java.io.*;
import java.net.*;
import java.util.Date;

public class EmailSender {

  public EmailSender() {
  }

  public void send(String from, String to, String subject, String msg) {
     Socket smtpSocket = null; 
     DataOutputStream os = null;
     DataInputStream is = null;

     try {
       smtpSocket = new Socket("202.112.241.118", 25);
       os = new DataOutputStream(smtpSocket.getOutputStream());
       is = new DataInputStream(smtpSocket.getInputStream());
     } catch (UnknownHostException e) {
       System.err.println("Don't know about host: hostname");
     } catch (IOException e) {
       System.err.println("Couldn't get I/O for the connection to: hostname");
     }

     if (smtpSocket != null && os != null && is != null) {
      try {
        os.writeBytes("HELO there"+"\r\n"); 
        os.writeBytes("MAIL FROM: "+ from +"\r\n");
        os.writeBytes("RCPT TO: "+ to + "\r\n");
        os.writeBytes("DATA\r\n");
        os.writeBytes("Date: "+ new Date() + "\r\n"); // stamp the msg with date
        os.writeBytes("From: "+from+"\r\n");
        os.writeBytes("To: "+to+"\r\n");
        os.writeBytes("Subject: "+subject+"\r\n");
        os.writeBytes(msg+"\r\n"); // message body
        os.writeBytes(".\r\n");
        os.writeBytes("QUIT\r\n");
        // debugging
        String responseLine;
        while ((responseLine = is.readLine()) != null) {
          System.out.println("Server: " + responseLine);
          if (responseLine.indexOf("delivery") != -1) {
             break;
          }
        }

        os.close();
        is.close();
        smtpSocket.close(); 
      } catch (UnknownHostException e) {
        System.err.println("Trying to connect to unknown host: " + e);
      } catch (IOException e) {
        System.err.println("IOException: " + e);
      }
    }
  } 
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?