java程序發email

程序如下:

 

 

package cams.alarm_manage.alarmTool;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import twaver.Alarm;
import twaver.Node;
import twaver.TWaverUtil;
import cams.common.SystemConfigStaticFunction;
import cams.public_class.PublicFunction;
import cams.safe_manage.dao.OperLogDAO;


public class AlarmMail extends JDialog
{

    private JTextArea taContent;
    private JTextField txtSubject;
    private JTextField txtReciver;
   
    private static  String USERNAME = "[email protected]";    // 設定郵箱的用戶名

    public static  String PASSWORD = "";                        //123456qaz 設定郵箱的密碼×××就是你的信箱的密碼

    private static  String TO_EMAIL;                            // 設定收件人的信箱

    public static  String SUBJECT;                                // 設定郵件標題

//    private static  String FROM = SystemConfigStaticFunction.strEmail;        // 設定發件件的人

    private static  String SMTP = "smtp.gmail.com";
//    smtp.126.com
//    smtp.gmail.com
//    smtp.qq.com
   
    private JButton btnSend;
    private JButton btnCancel;
    private JLabel lblSender;
    private JLabel lblReciver;
    private JTextField txtSender;
    public static String content;
    public static MailInfo mail=new MailInfo();
    private String sysName="";
   
    public AlarmMail(final Alarm alarm)
    {
        super();
        getContentPane().setLayout(new BorderLayout());
//        setIconImage(Toolkit.getDefaultToolkit().getImage(AlarmMail.class.getResource("/rinms/images/view/enovell_log_icon.png")));
        setTitle("郵件發送");
        setSize(608, 478);
        final JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        panel.setLayout(null);
        getContentPane().add(panel, BorderLayout.CENTER);

        final JLabel lblSender = new JLabel();
        lblSender.setText("收件人地址 :");
        lblSender.setBounds(20, 76, 91, 18);
        panel.add(lblSender);
        txtReciver = new JTextField();
        txtReciver.setBounds(107, 71, 451, 28);
        txtReciver.grabFocus();
        txtSender = new JTextField();
        txtSender.setEditable(false);
        txtSender.setBounds(107, 20, 451, 28);
        txtSender.setText(USERNAME);
        panel.add(txtSender);
       
       
        panel.add(txtReciver);
        txtReciver.grabFocus();
       
        lblReciver = new JLabel();
        lblReciver.setText("/u53D1/u9001/u4EBA/u5730/u5740 /uFF1A");
        lblReciver.setBounds(20, 25, 91, 18);
        panel.add(lblReciver);
   
       
        final JLabel lblSubject = new JLabel();
        lblSubject.setText("   /u90AE/u4EF6/u4E3B/u9898 /uFF1A");
        lblSubject.setBounds(20, 124, 91, 18);
        panel.add(lblSubject);

        txtSubject = new JTextField();
        txtSubject.setEditable(false);
        txtSubject.setBounds(107, 124, 451, 28);
        panel.add(txtSubject);
       
        txtSubject.setText(alarm.getClientProperty("ALARM_NAME").toString());

        final JLabel lblContent = new JLabel();
        lblContent.setText("   /u90AE/u4EF6/u5185/u5BB9 /uFF1A");
        lblContent.setBounds(20, 162, 91, 18);
        panel.add(lblContent);

        taContent = new JTextArea();
        taContent.setEditable(false);
        taContent.setBorder(new TitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        taContent.setBounds(107, 186, 451, 199);
        taContent.setLineWrap(true);
        panel.add(taContent);
       
       
        switch(Integer.valueOf(alarm.getClientProperty("TYPE_FLAG").toString())){
        case 1:
            sysName="交換網";
            break;
        case 2:
            sysName="數據網";
            break;
        case 3:
            sysName="傳輸網";
            break;
        }
       
        taContent.setText("系統:"+sysName+";/n設備名稱:"+alarm.getClientProperty("DEV_NAME").toString()+";/n告警描述:"+alarm.getClientProperty("ALARM_DESC").toString()+";/n告警發生時間:"+alarm.getClientProperty("FIRST_OCCUR").toString());
       

        btnSend= new JButton();
        btnSend.setText("發送");
        btnSend.addActionListener(new ActionListener()
        {
            public void actionPerformed(final ActionEvent arg0)
            {
                SUBJECT=txtSubject.getText().trim().toString();
                TO_EMAIL=txtReciver.getText().trim().toString();
//                content=taContent.getText().toString();
                content="系統:"+sysName+";/n設備名稱:"+alarm.getClientProperty("DEV_NAME").toString()+";/n告警描述:"+alarm.getClientProperty("ALARM_DESC").toString()+";/n告警發生時間:"+alarm.getClientProperty("FIRST_OCCUR").toString();
                mail.setUserID(SystemConfigStaticFunction.iLogOnUserId.toString());
                mail.setMailSubject(SUBJECT);
                mail.setMailContent(content);
                mail.setReciverEmail(TO_EMAIL);
                mail.setMailDeliveryTime(PublicFunction.FetchCurrentTime());
                try {
                         if(TO_EMAIL.equals(""))
                         {
                             PublicFunction.ShowMessageDialog("請輸入郵件接收者郵箱!", 0);
                         }
                         else
                         {
                             dispose();
                             OperLogDAO.addRoleFunctionInfo("增加", "實時告警監視管理", "告警發送郵件");
                             ValidatePWDDialog dialog=new ValidatePWDDialog();
                             dialog.setVisible(true);
                         }
                    } catch (Exception e) {
                        e.printStackTrace();
                        PublicFunction.ShowMessageDialog("發送失敗,請重新發送!",0);
                    }   
            }
        });
        btnSend.setBounds(223, 391, 74, 28);
        btnCancel=new JButton();
        btnCancel.setText("取消");
        btnCancel.setBounds(313, 391, 64, 28);
        btnCancel.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                dispose();
            }
        });
        panel.add(btnSend);
        panel.add(btnCancel);
       
        TWaverUtil.centerWindow(this);
        PublicFunction.ToWindowsLookAndFeel_dialog(this);
    }
   
    public AlarmMail(final Node node)
    {
        super();
        getContentPane().setLayout(new BorderLayout());
//        setIconImage(Toolkit.getDefaultToolkit().getImage(AddAlarmFilterRule.class.getResource("/rinms/images/resource/enovell_1.png")));
        setTitle("郵件詳細信息");
        setSize(608, 459);
        final JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        panel.setLayout(null);
        getContentPane().add(panel, BorderLayout.CENTER);

        final JLabel lblSender = new JLabel();
        lblSender.setText("收件人地址 :");
        lblSender.setBounds(20, 76, 91, 18);
        panel.add(lblSender);
        txtReciver = new JTextField();
        txtReciver.setText(node.getClientProperty("RECIVER_EMAIL").toString());
        txtReciver.setBounds(107, 71, 451, 28);
       
        txtSender = new JTextField();
        txtSender.setText(node.getClientProperty("SENDER_EMAIL").toString());
        txtSender.setBounds(107, 20, 451, 28);
        txtSender.setText(USERNAME);
        panel.add(txtSender);
       
       
        panel.add(txtReciver);
        txtReciver.grabFocus();
       
        lblReciver = new JLabel();
        lblReciver.setText("/u53D1/u9001/u4EBA/u5730/u5740 /uFF1A");
        lblReciver.setBounds(20, 25, 91, 18);
        panel.add(lblReciver);
   
       
        final JLabel lblSubject = new JLabel();
        lblSubject.setText("   /u90AE/u4EF6/u4E3B/u9898 /uFF1A");
        lblSubject.setBounds(20, 124, 91, 18);
        panel.add(lblSubject);

        txtSubject = new JTextField();
        txtSubject.setText(node.getClientProperty("MAIL_SUBJECT").toString());
        txtSubject.setBounds(107, 124, 451, 28);
        panel.add(txtSubject);
       
       

        final JLabel lblContent = new JLabel();
        lblContent.setText("   /u90AE/u4EF6/u5185/u5BB9 /uFF1A");
        lblContent.setBounds(20, 162, 91, 18);
        panel.add(lblContent);

        taContent = new JTextArea();
        taContent.setBorder(new TitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
        taContent.setBounds(107, 186, 451, 199);
        taContent.setText(node.getClientProperty("MAIL_CONTENT").toString());
        taContent.setLineWrap(true);
        panel.add(taContent);
        TWaverUtil.centerWindow(this);
        PublicFunction.ToWindowsLookAndFeel_dialog(this);
    }
   
    public static void sender(String subject, String content)
    {
          Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
          Properties properties = System.getProperties();
          properties.setProperty("mail.smtp.host", SMTP);
          //gmail端口與其它不一樣,要寫下面一段
          String []str=SMTP.split("[.]");
          if(str[1].equals("gmail"))
          {
              properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
              properties.setProperty("mail.smtp.socketFactory.fallback", "false");
              properties.setProperty("mail.smtp.port", "465");
              properties.setProperty("mail.smtp.socketFactory.port", "465");
          }
         
         //---------------------------------------------------
          properties.put("mail.smtp.auth", "true");

          Session session = Session.getDefaultInstance(properties,new Authenticator()
          {
             protected PasswordAuthentication getPasswordAuthentication()
             {
                 return new PasswordAuthentication(USERNAME, PASSWORD);
             }
          });

          Message msg = new MimeMessage(session);
          InternetAddress[] address = null;
         
          try
          {
              // 設定發郵件的人

              msg.setFrom(new InternetAddress(USERNAME));
              // 設定收信人的信箱
              address = InternetAddress.parse(TO_EMAIL, false);
              msg.setRecipients(Message.RecipientType.TO, address);
   
              // 設定信中的主題
              msg.setSubject(subject);
   
              // 設定送信的時間
              msg.setSentDate(new Date());
   
              Multipart mp = new MimeMultipart();
              MimeBodyPart mbp = new MimeBodyPart();
   
              // 設定郵件內容的類型爲 text/plain 或 text/html
              mbp.setContent(content, "text/html;charset=GB2312");
              mp.addBodyPart(mbp);
              msg.setContent(mp);
              Transport transport = session.getTransport("smtp");
              transport.connect(SMTP, USERNAME, PASSWORD);
              transport.sendMessage(msg, msg.getAllRecipients());
              transport.close();
              PublicFunction.ShowMessageDialog("恭喜你!發送成功!",0);
              //發送成功後。入庫。
//              AlarmBusinessFactory.getAlarmBusiness().addEmailInfo(AlarmMail.mail);
          }
          catch (Exception e)
          {
              PublicFunction.ShowMessageDialog("發送失敗,請檢查郵箱地址及密碼是否輸入正確!",0);
              e.printStackTrace();
          }
         
    }
   
    /*class MyProgressBar implements Runnable
    {
        Timer timer;
        ProgressMonitor pm;
        JFrame poi;
        int i;
        public MyProgressBar()
        {
           
        }
        public void run()
        {
            ActionListener actionListener = new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    pm.setProgress(++i == 100 ? 1 : i);
                }
            };
            timer = new Timer(100, actionListener);
            pm = new ProgressMonitor(poi, "", "正在發送郵件,請稍候...", 1, 100);
            pm.setMillisToDecideToPopup(0);
            pm.setMillisToPopup(0);
            timer.start();
            try
            {
                sender(SUBJECT,taContent.getText().trim().toString());
                //PublicFunction.ShowMessageDialog("恭喜你!發送成功!",0);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }*/
   
    public static void main(String [] args ){

        SystemConfigStaticFunction.iLogOnUserId = 0;
       
        Date nowTime = new Date(System.currentTimeMillis());
       
        Alarm alarm = new Alarm();
        alarm.putClientProperty("ALARM_NAME","測試告警");
        alarm.putClientProperty("TYPE_FLAG","0");
        alarm.putClientProperty("DEV_NAME","測試設備");
        alarm.putClientProperty("ALARM_DESC","測試告警描述");
        alarm.putClientProperty("FIRST_OCCUR",FetchCurrentTime());
       
        AlarmMail alarmMail = new AlarmMail(alarm);

        alarmMail.setSize(500, 600);
        alarmMail.setVisible(true);
       
    }
   
    private static String FetchCurrentTime(){
        String CurrentTime = "";
        try{
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            CurrentTime=sDateFormat.format(nowTime);
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        return CurrentTime;
    }
   

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章