回顾Swing知识第二天,实现了一个简单的邮箱管理系统

技术点:

Swing窗口+MYSQL+Eclipse

主要代码实现:

一、数据库连接类

package Jdbc;

import java.sql.*;

public class connector {
    // JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC";//需要自行设置数据库路由

    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";//数据库用户名
    static final String PASS = "123456";//数据库密码

    //以下是我自己项目里面的涉及到jdbc数据库操作的两个函数,一个是select,一个是insert
    public static String getname(String account, String password) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 打开链接
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT user_name FROM user WHERE user_account='"+account+"' AND user_psd='"+password+"'";
            System.out.println(sql);
            ResultSet rs = stmt.executeQuery(sql);
            if(rs.next()){
                return rs.getString("user_name");
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public static boolean adduser(String account, String password,String username) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 打开链接
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            String sql="insert into user(user_account,user_psd,user_name) values(?,?,?)";//sql语句

            PreparedStatement pstmt=conn.prepareStatement(sql);//获得预置对象
            pstmt.setString(1, account);//设置占位符的值
            pstmt.setString(2, password);
            pstmt.setString(3, username);

            int res=pstmt.executeUpdate();//执行sql语句
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

二、登录窗口

package MailAssistant;

import Jdbc.connector;
import MailAssistant.Entity.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LoginFrame extends JFrame {
    private String mailAccount;
    private String authorizePassword;

    private JPanel contentPane;
    private final JButton LoginButton = new JButton("登陆");
    private final JButton RegisterButton = new JButton("注册");
    private int number;
    private final JTextField AccounttextField = new JTextField();
    private final JTextField PasswordtextField = new JTextField();
    private final JTable table = new JTable();
    int xOld = 0;
    int yOld = 0;
    private final JLabel Accountlabel = new JLabel("用户名:");
    private final JLabel Passwordlabel = new JLabel("密码:");
    private final JScrollPane scrollPane = new JScrollPane();
    //背景图片bgImage
    private ImageIcon bgImage = new ImageIcon("res/Register.png");

    public void uninum() {
        mailAccount = "";
        authorizePassword = "";
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LoginFrame frame = new LoginFrame();
                    frame.setVisible(true);
                    frame.button(frame);
                    frame.RegisterButton(frame);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public JButton getLoginbutton() {
        return LoginButton;
    }

    public void button(LoginFrame a) {
        JButton button = new JButton();
        button = a.getLoginbutton();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String user_name = connector.getname(AccounttextField.getText(),PasswordtextField.getText());
                if (!user_name.equals("")){
                    JOptionPane.showMessageDialog(new JLabel(), "登陆成功,欢迎你 "+user_name, "提示",JOptionPane.WARNING_MESSAGE);
                    User user = User.getSingleInstance(AccounttextField.getText(),PasswordtextField.getText(),user_name);
                    MailFrame frame = new MailFrame(user);
                    frame.button(frame);
                    frame.Inboxbutton(frame);
                    frame.setVisible(true);
                    a.setVisible(false);  //窗体不可见
                }
                else {
                    JOptionPane.showMessageDialog(new JLabel(), "用户名或密码错误", "警告",JOptionPane.WARNING_MESSAGE);
                    AccounttextField.setText("");
                    PasswordtextField.setText("");
                }

            }
        });
    }

    public JButton getRegisterbutton() {
        return RegisterButton;
    }

    public void RegisterButton(LoginFrame a) {
        JButton button = new JButton();
        button = a.getRegisterbutton();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                a.setVisible(false);
                RegisterFrame frame = new RegisterFrame();
                frame.Registerbutton(frame);
                frame.Loginbutton(frame);
                frame.setVisible(true);

            }
        });
    }

    public LoginFrame() {
        uninum();
        getContentPane().setLayout(null);
        this.setLocationRelativeTo(null);
        bgImage.setImageObserver(null);
        this.setSize((bgImage).getIconWidth(), bgImage.getIconHeight());
        //处理拖动事件---去掉默认边框后,不能拖动了,具体实现如下
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xOld = e.getX();//记录鼠标按下时的坐标
                yOld = e.getY();
            }
        });

        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int xOnScreen = e.getXOnScreen();
                int yOnScreen = e.getYOnScreen();
                int xx = xOnScreen - xOld;
                int yy = yOnScreen - yOld;
                LoginFrame.this.setLocation(xx, yy);//设置拖拽后,窗口的位置
            }
        });

        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setSize(bgImage.getIconWidth(), bgImage.getIconHeight());
        getContentPane().add(layeredPane);

        //背景图层Panel,充当容器---最底层
        JPanel bgPanel = new JPanel();
        bgPanel.setLocation(0, 0);
        bgPanel.setSize(bgImage.getIconWidth(), bgImage.getIconHeight());
        layeredPane.add(bgPanel, JLayeredPane.DEFAULT_LAYER);//放在最底层

        //背景图片,添加到背景图层Panel里面
        JLabel bgLabel = new JLabel(bgImage);
        bgPanel.add(bgLabel);

        //主界面,也就是背景上面的一层Panel,可用于添加控件
        contentPane = new JPanel();
        contentPane.setLocation(0, 0);
        contentPane.setSize(700, 450);
        contentPane.setLayout(null);
        contentPane.setOpaque(false);
        layeredPane.add(contentPane, JLayeredPane.MODAL_LAYER);//放在较高一层

        //关闭按钮
        JButton closeButton = new JButton();
        closeButton.setSize(30, 30);
        contentPane.add(closeButton);

        JLabel lblNewLabel = new JLabel("用户登录");
        lblNewLabel.setFont(new Font("楷体", Font.PLAIN, 28));
        lblNewLabel.setForeground(new Color(0, 0, 128));
        lblNewLabel.setBounds(200, 0, 464, 50);
        contentPane.add(lblNewLabel);

        //请输入用户邮箱账号
        Accountlabel.setForeground(new Color(0, 0, 0));
        Accountlabel.setBounds(5, 185, 60, 20);
        contentPane.add(Accountlabel);

        //用户邮箱账号输入框
        AccounttextField.setBounds(65, 185, 120, 20);
        contentPane.add(AccounttextField);

        //请输入用户邮箱授权密码
        Passwordlabel.setForeground(new Color(0, 0, 0));
        Passwordlabel.setBounds(185, 185, 45, 20);
        contentPane.add(Passwordlabel);

        //用户邮箱授权密码输入框
        PasswordtextField.setBounds(230, 185, 120, 20);
        contentPane.add(PasswordtextField);

        //登录
        LoginButton.setBounds(360, 185, 60, 20);
        contentPane.add(LoginButton);

        //注册
        RegisterButton.setBounds(425, 185, 60, 20);
        contentPane.add(RegisterButton);

//        table.setBounds(20, 73, 309, 367);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                int rowIndex = table.getSelectedRow();
                String b = table.getValueAt(rowIndex, 0).toString();
                int id = Integer.parseInt(b);
            }
        });
        scrollPane.setViewportView(table);

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        this.setLayeredPane(layeredPane);
        this.setLocationRelativeTo(null);
        bgImage.setImageObserver(null);
        this.setSize((bgImage).getIconWidth(), bgImage.getIconHeight());
        this.setLocation(bgImage.getIconWidth(), bgImage.getIconHeight());
        this.setUndecorated(true);//去边框

    }
}

三、主窗口

package MailAssistant;

import MailAssistant.Entity.User;

import javax.mail.Message;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;

public class MailFrame extends JFrame {

    private JPanel contentPane;
    private final JButton SendButton = new JButton("发送");
    private final JButton InboxButton = new JButton("收件箱");
    private int number;

    private final JTable table = new JTable();
    int xOld = 0;
    int yOld = 0;
    private final JLabel Receiverlabel = new JLabel("收件人");
    private final JTextField ReceivertextField = new JTextField();
    private final JLabel Subjectlabel = new JLabel("主题");
    private final JTextField SubjecttextField = new JTextField();
    private final JLabel Contentlabel = new JLabel("邮件内容");
    private final JTextArea ContenttextField = new JTextArea();

    private final JScrollPane scrollPane = new JScrollPane();
    private final JLabel lblAbc = new JLabel("");
    private final JLabel lblNewLabel_1 = new JLabel("");
    private final JLabel lblNewLabel_2 = new JLabel("");
    private final JLabel lblNewLabel_3 = new JLabel("");
    private final JLabel lblNewLabel_4 = new JLabel("");
    private final JSplitPane splitPane = new JSplitPane();
    private String mailAccount;
    private String authorizePassword;

    private String ReceiverAccount;
    private String Subject;
    private String Content;

    private User user;


    //背景图片bgImage
    private ImageIcon bgImage = new ImageIcon("res/Mail.jpg");

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MailFrame frame = new MailFrame(null);
                    frame.setVisible(true);
                    //frame.fillTable(frame.table, 2);
                    frame.button(frame);
                    frame.Inboxbutton(frame);
                    frame.setSize(1000, 450);
                    //frame.setLocation(300, 100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public JButton getbutton() {
        return SendButton;
    }

    public JButton getInboxButton() {
        return InboxButton;
    }

    public void button(MailFrame a) {
        JButton button = new JButton();
        button = a.getbutton();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ReceiverAccount = ReceivertextField.getText();
                Subject = SubjecttextField.getText();
                Content = ContenttextField.getText();
                if (ReceiverAccount.equals("") || Content.equals("")) {
                    System.out.println("信息输入不完整!");
                }
                boolean results = SendMail.sendMail(ReceiverAccount, Subject, Content, "");
                if (results){
                    JOptionPane.showMessageDialog(new JLabel(), "邮件发送成功!", "提示",JOptionPane.WARNING_MESSAGE);
                    ReceivertextField.setText("");
                    SubjecttextField.setText("");
                    ContenttextField.setText("");
                }
            }
        });
    }
    public void Inboxbutton(MailFrame a) {
        JButton button = new JButton();
        button = a.getInboxButton();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Message[] messages = ReceiveMail.getAllMails();
                if (messages  !=null){
                    a.setVisible(false);
                    JOptionPane.showMessageDialog(new JLabel(), "所有邮件获取成功", "提示",JOptionPane.WARNING_MESSAGE);
                    ReceivesFrame receivesFrame = new ReceivesFrame(messages);
                    receivesFrame.Inboxbutton(receivesFrame);
                    receivesFrame.setVisible(true);
//                    receivesFrame.Inboxbutton(receivesFrame);
                }
            }
        });
    }

    public void fillTable(JTable table, int num) {

        try {
            String[] column = {"Packet", "版本号", "标识"};
            DefaultTableModel defaultTableModel = new DefaultTableModel(column, 0) {
                public boolean isCellEditable(int row, int column) {
                    return false;//重写isCellEditable类使整个表格不允许被编辑
                }
            };
            int j = 0;
            while (j < num) {
                int id = j + 1;
                String version = "IPv4";
//                int ident = packets[j].getIdent();

//                Object[] str_row = {id, version, ident};
//                defaultTableModel.addRow(str_row);
                j++;
            }
            table.setModel(defaultTableModel);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "加载不成功!");
        }
    }

    public void uninum() {
        mailAccount = "";
        authorizePassword = "";
    }

    public MailFrame(User user) {
        this.user = user;
//        uninum();
        getContentPane().setLayout(null);
        this.setLocationRelativeTo(null);
        bgImage.setImageObserver(null);
        this.setSize((bgImage).getIconWidth(), bgImage.getIconHeight());
        //处理拖动事件---去掉默认边框后,不能拖动了,具体实现如下
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xOld = e.getX();//记录鼠标按下时的坐标
                yOld = e.getY();
            }
        });

        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int xOnScreen = e.getXOnScreen();
                int yOnScreen = e.getYOnScreen();
                int xx = xOnScreen - xOld;
                int yy = yOnScreen - yOld;
                MailFrame.this.setLocation(xx, yy);//设置拖拽后,窗口的位置
            }
        });

        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setSize(bgImage.getIconWidth(), bgImage.getIconHeight());
        getContentPane().add(layeredPane);

        //背景图层Panel,充当容器---最底层
        JPanel bgPanel = new JPanel();
        bgPanel.setLocation(0, 0);
        bgPanel.setSize(bgImage.getIconWidth(), bgImage.getIconHeight());
        layeredPane.add(bgPanel, JLayeredPane.DEFAULT_LAYER);//放在最底层

        //背景图片,添加到背景图层Panel里面
        JLabel bgLabel = new JLabel(bgImage);
        bgPanel.add(bgLabel);

        //主界面,也就是背景上面的一层Panel,可用于添加控件
        contentPane = new JPanel();
        contentPane.setLocation(0, 0);
        contentPane.setSize(700, 450);
        contentPane.setLayout(null);
        contentPane.setOpaque(false);
        layeredPane.add(contentPane, JLayeredPane.MODAL_LAYER);//放在较高一层

        //关闭按钮
        JButton closeButton = new JButton();
        //closeButton.setIcon(new ImageIcon("src/images/closebtn.png"));
        closeButton.setSize(30, 30);
        contentPane.add(closeButton);

        JLabel lblNewLabel = new JLabel("基于SMTP协议的模拟邮件系统");
        lblNewLabel.setFont(new Font("楷体", Font.PLAIN, 26));
        lblNewLabel.setForeground(new Color(0, 0, 128));
        lblNewLabel.setBounds(250, 0, 520, 50);
        contentPane.add(lblNewLabel);

        JLabel userLabel = new JLabel("欢迎你 --" + user.getUser_name());
        userLabel.setFont(new Font("楷体", Font.PLAIN, 20));
        userLabel.setForeground(new Color(0, 0, 128));
        userLabel.setBounds(530, 25, 500, 50);
        contentPane.add(userLabel);

        Receiverlabel.setForeground(new Color(0, 0, 0));
        Receiverlabel.setBounds(270, 60, 70, 20);
        Receiverlabel.setFont(new Font("楷体", Font.PLAIN, 20));
        contentPane.add(Receiverlabel);

        ReceivertextField.setBounds(350, 60, 160, 20);
        contentPane.add(ReceivertextField);

        Subjectlabel.setForeground(new Color(0, 0, 0));
        Subjectlabel.setBounds(280, 100, 60, 20);
        Subjectlabel.setFont(new Font("楷体", Font.PLAIN, 20));
        contentPane.add(Subjectlabel);

        SubjecttextField.setBounds(350, 100, 160, 20);
        contentPane.add(SubjecttextField);

        Contentlabel.setForeground(new Color(0, 0, 0));
        Contentlabel.setBounds(260, 240, 80, 20);
        Contentlabel.setFont(new Font("楷体", Font.PLAIN, 20));
        contentPane.add(Contentlabel);

        ContenttextField.setBounds(350, 140, 160, 200);
        contentPane.add(ContenttextField);

        InboxButton.setBounds(560, 70, 100, 20);
        contentPane.add(InboxButton);

        SendButton.setBounds(560, 100, 100, 20);
        contentPane.add(SendButton);


        table.setBounds(20, 73, 309, 367);
        scrollPane.setViewportView(table);

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        this.setLayeredPane(layeredPane);
        this.setLocationRelativeTo(null);
        bgImage.setImageObserver(null);
        this.setSize((bgImage).getIconWidth(), bgImage.getIconHeight());
        this.setLocation(bgImage.getIconWidth(), bgImage.getIconHeight());
        this.setUndecorated(true);//去边框

    }
}

四、发送邮件

package MailAssistant;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendMail {
    public static boolean sendMail(String account,String subject,String content,String fromUser){
        if (fromUser == null){
            fromUser = "Sayello";
        }
        try {
            String host = "smtp.qq.com";//这是QQ邮箱的smtp服务器地址
            String port = "25"; //端口号
            /*
             *Properties是一个属性对象,用来创建Session对象
             */
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.port", port);
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.ssl.enable", "false");//"true"
            props.setProperty("mail.smtp.connectiontimeout", "5000");
            final String user = "XXXX@qq.com";//邮箱账号
            final String pwd = "xxxxxxx";//smtp/pop3授权密码
            /*
             *Session类定义了一个基本的邮件对话。
             */
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    //登录用户名密码
                    return new PasswordAuthentication(user, pwd);
                }
            });
            session.setDebug(true);
            /*
             *Transport类用来发送邮件。
             *传入参数smtp,transport将自动按照smtp协议发送邮件。
             */
            Transport transport = session.getTransport("smtp");//"smtps"
            transport.connect(host, user, pwd);
            /*
             *Message对象用来储存实际发送的电子邮件信息
             */
            MimeMessage message = new MimeMessage(session);
            message.setSubject(subject);
            //消息发送者接收者设置(发件地址,昵称),收件人看到的昵称是这里设定的
            message.setFrom(new InternetAddress(user, fromUser));
            message.addRecipients(Message.RecipientType.TO, new InternetAddress[]{
            //消息接收者(收件地址,昵称)
            // 不过这个昵称貌似没有看到效果
            new InternetAddress(account, "Sayello"),});
            message.saveChanges();
            //设置邮件内容及编码格式
            // 后一个参数可以不指定编码,如"text/plain",但是将不能显示中文字符
            message.setContent(content, "text/plain;charset=UTF-8");
            //发送
            Transport.send(message);
            transport.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }
}

五、接收邮件

package MailAssistant;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import java.util.Date;
import java.util.Properties;

public class ReceiveMail {
    public static Message[] getAllMails() {
        String protocol = "pop3";//使用pop3协议
        boolean isSSL = true;//使用SSL加密
        String host = "pop.qq.com";//QQ邮箱的pop3服务器
        int port = 995;//端口
        final String username = "XXXX@qq.com";//邮箱账户
        final String password = "xxxxxx";//smtp/pop3授权密码
        /*
         *Properties是一个属性对象,用来创建Session对象
         */
        try{
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            Properties props = new Properties();
            props.put("mail.pop3.auth.plain.disable",true);
            props.put("mail.pop3.ssl.enable",true);

            props.put("mail.pop3.auth", "true"); //这样才能通过验证

            props.put("mail.pop3.ssl.socketFactory", sf);
            props.put("mail.pop3.host", host);
            props.put("mail.pop3.port", port);

            MyAuthenticator myauth = new MyAuthenticator(username, password);

            Session session = Session.getDefaultInstance(props,myauth);
            /*
             * Store类实现特定邮件协议上的读、写、监视、查找等操作。
             * 通过Store类可以访问Folder类。
             * Folder类用于分级组织邮件,并提供照Message格式访问email的能力。
             */
            Store store = null;
            Folder folder = null;
            try {
                store = session.getStore(protocol);
                store.connect(username, password);
                folder = store.getFolder("INBOX");// 获得用户的邮件帐户
                folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限
                Message[] messages = folder.getMessages();
                System.out.println("count="+messages.length);
                int n = folder.getUnreadMessageCount();// 得到未读数量
                int n1 = folder.getMessageCount();// 得到未读数量
                return messages;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("接收完毕!");
        return null;
    }
}

系统的简单页面:

登录注册:

基于Java的邮件收发系统开题报告 邮件管理系统基于java_swing

基于Java的邮件收发系统开题报告 邮件管理系统基于java_swing_02

发送/接收邮件:

基于Java的邮件收发系统开题报告 邮件管理系统基于java_基于Java的邮件收发系统开题报告_03

 

基于Java的邮件收发系统开题报告 邮件管理系统基于java_java_04

 

有些小瑕疵:

背景图片有点low(网上随便找的背景素材)、收件箱的布局没有弄好,内容显示有点挤得慌