package MailSender;
import java.io.*;
import java.net.*;
public class MailSender
{
private String smtpServer = "smtp.163.com" ;
private int port = 25 ;
public static void main(String args[])
{
Message msg = new Message("123@163.com","456@qq.com","Testmail","Hi,This is a test mail from CZW2.");
new MailSender().sendMail(msg);
}
public void sendMail(Message msg)
{
Socket socket = null ;
try
{
socket = new Socket(smtpServer,port); //连接到服务器
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
String username = "123";
String password = "111";
username = new sun.misc.BASE64Encoder().encode(username.getBytes());
password = new sun.misc.BASE64Encoder().encode(password.getBytes());
sendAndReceive(null,br,pw); //仅仅为了接收服务器响应数据
sendAndReceive("helo 163.com",br,pw);
sendAndReceive("AUTH LOGIN",br,pw);
sendAndReceive(username,br,pw);
sendAndReceive(password,br,pw);
sendAndReceive("mail from:<" + msg.from + ">",br,pw);
sendAndReceive("rcpt to:<" + msg.to +">",br,pw);
sendAndReceive("data
",br,pw);
pw.println(msg.data);
System.out.println("Client>" + msg.data);
sendAndReceive(".",br,pw); //邮件发送完毕
sendAndReceive("quit",br,pw);
}catch(IOException e)
{
e.printStackTrace();
}finally
{
try
{
if(socket!=null)
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
/*发送一行字符串,并接收一行服务器响应*/
private void sendAndReceive(String str,BufferedReader br,PrintWriter pw)throws IOException
{
if(str != null)
{
System.out.println("client>" + str);
pw.println(str);
}
String response;
if((response = br.readLine()) != null)
{
System.out.println("Server>" + response);
}
}
private PrintWriter getWriter(Socket socket)throws IOException
{
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket)throws IOException
{
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
}
class Message
{
String from ;
String to ;
String subject;
String content;
String data;
public Message(String from,String to,String subject,String content)
{
this.from=from;
this.to=to;
this.subject=subject;
this.content=content;
data="Subject:" + subject + "
" + content;
}
}
问题解决,在69行所在循环体出错,改为这里的if,删掉下一个读取就好。
亲测成功!!!!