一段帶smtp認證的JavaMail代碼。

     Properties props = System.getProperties();
        props.put("mail.smtp.host", host);

        String mailNeedAuth = CatseyeConfig.getConfig("MailNeedAuth");
        String mailUser = CatseyeConfig.getConfig("MailUser");
        String mailPassword = CatseyeConfig.getConfig("MailPassword");

        if (mailNeedAuth.equals("1")) {
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }

        Session session = Session.getDefaultInstance(props, null);

        javax.mail.Message msg = new MimeMessage(session);
        InternetAddress[] toAddrs = null;

        try {
            if (recipients != null) {
                toAddrs = InternetAddress.parse(recipients, false);
                msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddrs);
            } else {
                throw new Exception("No recipient address specified");
            }

            if (sender != null) {
                msg.setFrom(new InternetAddress(sender));
            } else {
                throw new Exception("No sender address specified");
            }

            if (subject != null) {
                msg.setSubject(subject);
            }


            /*
            BodyPart bp=new MimeBodyPart();
            bp.setContent(body, "text/html");
            Multipart mp=new MimeMultipart();
            mp.addBodyPart(bp);
            */

            //msg.setContent(mp);
            msg.setContent(body, "text/html");
            msg.setHeader("X-Mailer", "Catseye SMTP Robot");
            msg.setHeader("Content-Type", "text/html");

            /*
            msg.setDataHandler(new DataHandler(
            new ByteArrayDataSource(body, "text/html")));
            //msg.setText(body);
            */
            Transport trans = session.getTransport("smtp");
            trans.connect(host, mailUser, mailPassword);
            trans.sendMessage(msg,
                              msg.getRecipients(
                                      javax.mail.Message.RecipientType.TO));

  
發佈了25 篇原創文章 · 獲贊 1 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章