现在大多数smtp服务器都需要身份认证,若用javamail写一个邮件收发客户端,怎么来实现这种功能呢?下面是一个简单的列子,模拟foxmail对认证功能的实现。 package jmail;
import javax.mail.*; import java.util.*; import java.sql.*; import javax.swing.*; import java.awt.*;
public class MailAuthenticator extends Authenticator{ String authenName; //用户名 String authenPass; //密码 public MailAuthenticator(String authenName,String authenPass) { super(); this.authenName=authenName; this.authenPass=authenPass; } public PasswordAuthentication getPasswordAuthentication(){ /*若服务器需要身份认证,Sission会自动调用这个方法 String temp=null; if(authenPass.equals("")||authenPass==null){ /*若密码为空*/ Option op=new Option(null,"身份验证",true); /*弹出要求用户输入密码的对话框,Option是自定义的JDialog,包含一个密码域*/ temp=op.showDialog(); /*Option的返回输入的密码*/ authenPass=temp; } return new PasswordAuthentication(authenName,authenPass); } } /* 下面是Option 类,jbuilder里写的,无须解释*/ package jmail;
import java.awt.*; import javax.swing.*; import com.borland.jbcl.layout.*; import java.awt.event.*;
public class Option extends JDialog { JPanel panel1 = new JPanel(); JLabel jLabel1 = new JLabel(); XYLayout xYLayout1 = new XYLayout(); JButton jButton1 = new JButton(); JButton jButton2 = new JButton(); JPasswordField jPasswordField1 = new JPasswordField(); JLabel jLabel2 = new JLabel(); JLabel jLabel3 = new JLabel(); Icon forget=new ImageIcon(".\images\forget.gif"); boolean ok=false; JLabel jLabel4 = new JLabel(); JLabel jLabel5 = new JLabel();
public Option(Frame frame, String title, boolean modal) { super(frame, title, modal); try { jbInit(); pack(); } catch(Exception ex) { ex.printStackTrace(); } }
public Option() { this(null, "", false); } private void jbInit() throws Exception { panel1.setLayout(xYLayout1); jLabel1.setFont(new java.awt.Font("Dialog", 0, 12)); jLabel1.setText("密码:"); jButton1.setFont(new java.awt.Font("Dialog", 0, 12)); jButton1.setDoubleBuffered(false); jButton1.setText("确定"); jButton1.addActionListener(new Option_jButton1_actionAdapter(this)); jButton2.setFont(new java.awt.Font("Dialog", 0, 12)); jButton2.setText("取消"); jButton2.addActionListener(new Option_jButton2_actionAdapter(this)); jLabel2.setFont(new java.awt.Font("Dialog", 0, 12)); jLabel2.setHorizontalTextPosition(SwingConstants.TRAILING); jLabel2.setIcon(forget); jLabel2.setText(""); jLabel3.setFont(new java.awt.Font("Dialog", 0, 12)); jLabel3.setText("服务器需要身份认证, 请输入密码"); panel1.setToolTipText(""); jLabel4.setText(" "); jLabel5.setText(" "); getContentPane().add(panel1, BorderLayout.CENTER); panel1.add(jLabel4, new XYConstraints(189, 61, -1, -1)); panel1.add(jLabel2, new XYConstraints(15, 1, 67, 19)); panel1.add(jLabel3, new XYConstraints(15, 22, -1, -1)); panel1.add(jPasswordField1, new XYConstraints(48, 46, 140, -1)); |