当前位置: 代码迷 >> Java Web开发 >> 基于SMTP的邮件发送程序
  详细解决方案

基于SMTP的邮件发送程序

热度:513   发布时间:2011-11-18 14:13:06.0
基于SMTP的邮件发送程序
程序代码:
package mail;

public class MailMessage
{

    private String from;

    private String to;

    private String datafrom;

    private String datato;

    private String subject;

    private String content;

    private String date;

    private String user;

    private String password;

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {

        this.password = password;
    }

    public String getUser()
    {

        return user;
    }

    public void setUser(String user)
    {

        this.user = user;

    }

    public String getContent()
    {
        return content;
    }

    public void setContent(String content)
    {

        this.content = content;
    }

    public String getDatafrom()
    {

        return datafrom;

    }

    public void setDatafrom(String datafrom)
    {

        this.datafrom = datafrom;

    }

    public String getDatato()
    {

        return datato;
    }

    public void setDatato(String datato)
    {

        this.datato = datato;
    }

    public String getDate()
    {

        return date;
    }

    public void setDate(String date)
    {

        this.date = date;
    }

    public String getFrom()
    {

        return from;
    }

    public void setFrom(String from)
    {

        this.from = from;
    }

    public String getSubject()
    {

        return subject;
    }

    public void setSubject(String subject)
    {

        this.subject = subject;
    }

    public String getTo()
    {

        return to;
    }

    public void setTo(String to)
    {
        this.to = to;
    }
}

//SMTPClient.java
package mail;

/*

* 邮件客户机
* 窗口
*/
//package 邮件客户机;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FromStringTerm;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;

import sun.misc.BASE64Encoder;

import java.awt.TextField;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;

public class SMTPClient extends JFrame implements ActionListener
{

    private JPanel contentPane;
    JLabel lblFrom, lblTo, lblSubject, lblMessage,lblUser,lblPassword;
    TextField textField_From, textField_To, textField_Subject,textField_User,textField_Password;
    TextArea textArea_Message;
    Button button_Send, button_Clear, button_Quit;
    //private Properties properties;
   
//private Session mailSession;
   
//private MimeMessage mailMessage;
   
//private Transport trans;
    private Socket socket;
    boolean flag;
   
    private boolean debug=true;
     BASE64Encoder encode=new BASE64Encoder();//用于加密后发送用户名和密码
    /**
     * Launch the application.
     
*/
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    SMTPClient frame = new SMTPClient();
                    frame.setVisible(true);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     
*/
    public SMTPClient()
    {

        /*
         * 窗口标题设置 窗口容器设置
         
*/
        setTitle("Java Mailclient");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 455, 330);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        /*
         * "From"选项标题设置
         
*/
        lblFrom = new JLabel("From:");
        lblFrom.setBounds(10, 3, 45, 15);
        contentPane.add(lblFrom);

        /*
         * 发送地址输入框
         
*/
        textField_From = new TextField();
        textField_From.setBounds(61, 3, 373, 23);
        contentPane.add(textField_From);
      
        /*
         * "User:"选项标题设置
         
*/
        lblUser = new JLabel("User:");
        lblUser.setBounds(10, 30, 62, 15);
        contentPane.add(lblUser);
        /*
         * 用户名输入框
         
*/
        textField_User = new TextField();
        textField_User.setBounds(61, 30, 100, 23);
        contentPane.add(textField_User);
      
        /*
         * "Password"选项标题设置
         
*/
        lblPassword = new JLabel("Password:");
        lblPassword.setBounds(190, 30, 62, 15);
        contentPane.add(lblPassword);
        /*
         * 密码输入框
         
*/
        textField_Password = new TextField();
        textField_Password.setBounds(280, 30, 150, 23);
        contentPane.add(textField_Password);
      
        /*
         * 目的地址框
         
*/
        lblTo = new JLabel("To:");
        lblTo.setBounds(10, 58, 27, 15);
        contentPane.add(lblTo);

        /*
         * 目的地址输入框
         
*/
        textField_To = new TextField();
        textField_To.setBounds(51, 58, 383, 23);
        contentPane.add(textField_To);

        /*
         * 标题框
         
*/
        lblSubject = new JLabel("Subject:");
        lblSubject.setBounds(10, 88, 62, 15);
        contentPane.add(lblSubject);

        /*
         * 标题输入框
         
*/
        textField_Subject = new TextField();
        textField_Subject.setBounds(71, 88, 363, 23);
        contentPane.add(textField_Subject);

        /*
         * 邮件内容栏
         
*/
        lblMessage = new JLabel("Message:");
        lblMessage.setBounds(10, 115, 62, 15);
        contentPane.add(lblMessage);

        /*
         * 邮件内容输入框
         
*/
        textArea_Message = new TextArea();
        textArea_Message.setBounds(0, 135, 434, 125);
        contentPane.add(textArea_Message);

        /*
         * 发送按钮
         
*/
        button_Send = new Button("Send");
        button_Send.setBounds(0, 258, 141, 23);
        button_Send.addActionListener(this);
        contentPane.add(button_Send);

        /*
         * 清除按钮
         
*/
        button_Clear = new Button("Clear");
        button_Clear.setBounds(146, 258, 141, 23);
        button_Clear.addActionListener(this);
        contentPane.add(button_Clear);

        /*
         * 退出按钮
         
*/
        button_Quit = new Button("Quit");
        button_Quit.setBounds(293, 258, 141, 23);
        button_Quit.addActionListener(this);
        contentPane.add(button_Quit);
    }
    //清除内容
    public void clear_Mail()
    {
        /*textField_From.setText("");
        textField_User.setText("");
        textField_Password.setText("");
        textField_To.setText("");
*/
        textField_Subject.setText("");
        textArea_Message.setText("");
    }

    @Override
    public void actionPerformed(ActionEvent e)//按钮事件
    {
        // TODO Auto-generated method stub
        if (e.getSource() == button_Send)
        {
            send_Button();
        } else if (e.getSource() == button_Clear)
        {
            clear_Mail();
        } else if (e.getSource() == button_Quit)
        {
            System.exit(0);
        }
    }

    public void send_Button()//发送邮件
    {
        MailMessage message=new MailMessage();
        message.setFrom(textField_From.getText());//发件人
        message.setTo(textField_To.getText());//收件人
        String server="smtp.sohu.com";//邮件服务器
        message.setSubject(textField_Subject.getText());//邮件主题
        message.setContent(textArea_Message.getText());//邮件内容
        message.setDatafrom(textField_From.getText());//发件人,在邮件的发件人栏目中显示
        message.setDatato(textField_To.getText());//收件人,在邮件的收件人栏目中显示
        message.setUser(textField_User.getText());//登陆邮箱的用户名
        message.setPassword(textField_Password.getText());//登陆邮箱的密码
      
         try{
               socket=new Socket(server,25);
              }catch(SocketException e){
               System.out.println(e.getMessage());
              }catch(Exception e){
               e.printStackTrace();
              }finally{
               System.out.println("已经建立连接!");
              }
         flag=sendMail(message,server);
          if(flag){
           System.out.println("邮件发送成功!");
          }
          else{
           System.out.println("邮件发送失败!");
          }

/*        try
        {
            properties = new Properties();
            // 设置邮件服务器
            properties.put("mail.smtp.host", "smtp.sohu.com");
            // 验证
            properties.put("mail.smtp.auth", "true");
            // 根据属性新建一个邮件会话
            mailSession = Session.getInstance(properties, new Authenticator()
            {
                public PasswordAuthentication getPasswordAuthentication()
                {
                    return new PasswordAuthentication(textField_User.getText(), textField_Password.getText());
                }
            });
            mailSession.setDebug(true);
            // 建立消息对象
            mailMessage = new MimeMessage(mailSession);
            // 发件人
            mailMessage.setFrom(new InternetAddress(textField_From.getText()));
            // 收件人
            mailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(textField_To.getText()));
            // 主题
            mailMessage.setSubject(textField_Subject.getText());
            // 内容
            mailMessage.setText(textArea_Message.getText());
            // 发信时间
            mailMessage.setSentDate(new Date());
            // 存储信息
            mailMessage.saveChanges();
            //
            trans = mailSession.getTransport("smtp");
            // 发送
            trans.send(mailMessage);
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
        }
*/
    }

    public void helo(String server,BufferedReader in,BufferedWriter out) throws IOException{
          int result;
          result=getResult(in);
          //连接上邮件服务后,服务器给出220应答
          if(result!=220){
           throw new IOException("连接服务器失败");
          }
          result=sendServer("HELO "+server,in,out);
          //HELO命令成功后返回250
          if(result!=250)
          {
           throw new IOException("注册邮件服务器失败!");
          }
         }
        
         private int sendServer(String str,BufferedReader in,BufferedWriter out) throws IOException{
          out.write(str);
          out.newLine();
          out.flush();
          if(debug)
          {
           System.out.println("已发送命令:"+str);
          }
          return getResult(in);
         }
         public int getResult(BufferedReader in){
          String line="";
          try{
           line=in.readLine();
           if(debug){
            System.out.println("服务器返回状态:"+line);
           }
          }catch(Exception e){
           e.printStackTrace();
          }
          //从服务器返回消息中读出状态码,将其转换成整数返回
          StringTokenizer st=new StringTokenizer(line," ");
          return Integer.parseInt(st.nextToken());
         }
        
         public void authLogin(MailMessage message,BufferedReader in,BufferedWriter out) throws IOException{
          int result;
          result=sendServer("AUTH LOGIN",in,out);
          if(result!=334){
           throw new IOException("用户验证失败!");
          }
         
           result=sendServer(encode.encode(message.getUser().getBytes()),in,out);
           if(result!=334){
           throw new IOException("用户名错误!");
           }
           result=sendServer(encode.encode(message.getPassword().getBytes()),in,out);
         
           if(result!=235){
            throw new IOException("验证失败!");
          }
         }
         //开始发送消息,邮件源地址
         public void mailfrom(String source,BufferedReader in,BufferedWriter out) throws IOException{
          int result;
          result=sendServer("MAIL FROM:<"+source+">",in,out);
          if(result!=250){
           throw new IOException("指定源地址错误");
          }
         }
         // 设置邮件收件人
         public void rcpt(String touchman,BufferedReader in,BufferedWriter out) throws IOException{
          int result;
          result=sendServer("RCPT TO:<"+touchman+">",in,out);
          if(result!=250){
           throw new IOException("指定目的地址错误!");
          }
         }
        
         //邮件体
         public void data(String from,String to,String subject,String content,BufferedReader in,BufferedWriter out) throws IOException{
          int result;
          result=sendServer("DATA",in,out);
          //输入DATA回车后,若收到354应答后,继续输入邮件内容
          if(result!=354){
           throw new IOException("不能发送数据");
          }
          out.write("From: "+from);
          out.newLine();
          out.write("To: "+to);
          out.newLine();
          out.write("Subject: "+subject);
          out.newLine();
          out.newLine();
          out.write(content);
          out.newLine();
          //句号加回车结束邮件内容输入
          result=sendServer(".",in,out);
          System.out.println(result);
          if(result!=250)
          {
           throw new IOException("发送数据错误");
          }
         }
        
         //退出
         public void quit(BufferedReader in,BufferedWriter out) throws IOException{
          int result;
          result=sendServer("QUIT",in,out);
          if(result!=221){
           throw new IOException("未能正确退出");
          }
         }
        
         public boolean sendMail(MailMessage message,String server){
              try{
               BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
               BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
               helo(server,in,out);//HELO命令
               authLogin(message,in,out);//AUTH LOGIN命令
               mailfrom(message.getFrom(),in,out);//MAIL FROM
               rcpt(message.getTo(),in,out);//RCPT
               data(message.getDatafrom(),message.getDatato(),message.getSubject(),message.getContent(),in,out);//DATA
               quit(in,out);//QUIT
              }catch(Exception e){
               e.printStackTrace();
               return false;
              
              }
              return true;
             }


}

这个程序是基于SMTP的,现在的问题是到验证密码的时候总是不通过,请用SOHU的邮箱来发送,请大家看看
搜索更多相关主题的帖子: content  color  

----------------解决方案--------------------------------------------------------
  相关解决方案