⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sendmail.java

📁 云网论坛CWBBS 源码,内容丰富,学习,参考,教学的好资料,具体见内说明,
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     * @throws java.lang.Exception
     */
    void setBody(String body, boolean flag) {
        try {
            MimeBodyPart mimebodypart = new MimeBodyPart();
            if (flag) {
                String htmlContent = getContent(body);
                mimebodypart.setContent(StrUtil.GBToUnicode(htmlContent +
                        mailFooterHTML),
                                        "text/html");
                //调用处理html文件中的图片方法
                processHtmlImage();
            } else
                mimebodypart.setText(body + mailFooter);
            multipart.addBodyPart(mimebodypart);
        } catch (Exception e) {
            errinfo += e.getMessage();
            logger.error("setBody: " + e.getMessage());
        }

    }

    public void setAttachFile(String filepath) throws Exception {
        MimeBodyPart mimebodypart = new MimeBodyPart();
        FileDataSource filedatasource = new FileDataSource(filepath);

        mimebodypart.setDataHandler(new DataHandler(filedatasource));
        mimebodypart.setFileName(StrUtil.UTF8ToUnicode(filedatasource.getName()));
        multipart.addBodyPart(mimebodypart);
    }

    public void setAttachFile(String filepath, String name) throws Exception {
        MimeBodyPart mimebodypart = new MimeBodyPart();
        FileDataSource filedatasource = new FileDataSource(filepath);

        mimebodypart.setDataHandler(new DataHandler(filedatasource));
        mimebodypart.setFileName(StrUtil.UTF8ToUnicode(name));
        multipart.addBodyPart(mimebodypart);
    }

    public void setAttachFile(String attach[]) throws Exception {
        for (int i = 0; i < attach.length; i++)
            setAttachFile(attach[i]);
    }

    public boolean send() throws Exception {
        try {
            Transport.send(msg);
        } catch (SendFailedException e) {
            logger.error("send: " + e.getMessage());
            errinfo = e.getMessage();
            throw new Exception(errinfo);
        }
        return true;
    }

    public String getErrMsg() {
        return errinfo;
    }

    /**
     * 取得上传后的邮件信息,包括附件,将其置于cleanup中,以备session消亡时自动删除
     * @param application
     * @param request
     */
    public void getMailInfo(ServletContext application,
                            HttpServletRequest request) {
        tempAttachFilePath = application.getRealPath("/") + "upfile/Attach/";

        FileUpload mfu = new FileUpload();
        mfu.setSavePath(tempAttachFilePath); //取得目录

        try {
            if (mfu.doUpload(application, request) == -3) {
                logger.error("文件太大,请把文件大小限制在30K以内!</p>");
                return;
            }
        } catch (IOException e) {
            logger.error("getRequestInfo:" + e.getMessage());
        }
        // 取得表单中域的信息
        String to = StrUtil.getNullString(mfu.getFieldValue("to"));
        String subject = StrUtil.getNullString(mfu.getFieldValue("subject"));
        String content = StrUtil.getNullString(mfu.getFieldValue("content"));
        try {
            initMsg(to, subject, content, true);
        } catch (Exception e1) {
            logger.error("SendMail initMsg:" + e1.getMessage());
        }

        // 处理附件
        mfu.writeFile(true); //用随机方式命名文件,如果不这样会使得覆盖别人的文件,或者自己的同名文件,但是恰恰session到期,而被删除
        // Add a listener for when this session becomes invalid.
        // We will want to delete the image file at this time
        CleanUp cln = null; // Clean up the image file
        HttpSession session = null;
        session = request.getSession(false);
        if (session == null)
            session = request.getSession(true);
        String strlc = (String) session.getAttribute("lc"); //listenercount
        if (strlc == null)
            strlc = "0";
        int lc = Integer.parseInt(strlc);
        // The first time through for this user session:
        java.util.Enumeration e = mfu.getFiles().elements();
        while (e.hasMoreElements()) {
            lc++;
            FileInfo fi = (FileInfo) e.nextElement();
            cln = new CleanUp(tempAttachFilePath + fi.diskName);
            session.setAttribute("bindings.listener" + lc, cln);
            try {
                setAttachFile(tempAttachFilePath + fi.diskName, fi.name);
            } catch (Exception e2) {
                logger.error("getMailInfo setAttachFile:" + e2.getMessage());
            }
        }

    }

    /**
     *	This class is used to remove the temporary image file when the
     *	client session expires.
     */
    class CleanUp implements HttpSessionBindingListener {
        String m_filename = null; // Image filename

        public CleanUp(String filename) {
            m_filename = filename;
        }

        public void valueBound(HttpSessionBindingEvent e) {
            // The user's session has begun;	m_filename	indicates
            // the name of the image file that will be used for this user's session.
            //System.out.println("Bound event: " + e.toString()
            //	 + "\n m_filename: " + m_filename);
        }

        public void valueUnbound(HttpSessionBindingEvent e) {
            //	The user's session expired; delete the image file.
            File delFile = new File(m_filename);
            if (delFile != null) {
                delFile.delete();
            }
            //System.out.println("Unbound event: " + e.toString()
            //	+ "\n m_filename: " + m_filename);
        }
    }

    // 处理html页面上的图片方法如下:
    private void processHtmlImage() throws MessagingException {
        for (int i = 0; i < arrayList1.size(); i++) {
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource("d:/zjrj/" + (String) arrayList1.get(i));
            messageBodyPart.setDataHandler(new DataHandler(source));
            String contentId = "<" + (String) arrayList2.get(i) + ">";
            // System.out.println(contentId);
            messageBodyPart.setHeader("Content-ID", contentId);
            messageBodyPart.setFileName((String) arrayList1.get(i));
            multipart.addBodyPart(messageBodyPart);
        }
    }

    //处理要发送的html文件,主要是针对html文件中的图片
    private String getContent(String mailContent) {
        Pattern pattern;
        Matcher matcher;

        pattern = Pattern.compile("src=([^>]*[^/].(?:jpg|jpeg|bmp|gif))(?:\\\"|\\'|\\s)", Pattern.CASE_INSENSITIVE);
        // pattern = Pattern.compile("src=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^'\">\\s]+))", Pattern.CASE_INSENSITIVE);

        matcher = pattern.matcher(mailContent);
        while (matcher.find()) {
            String path = matcher.group(1);
            if (path.indexOf("http://") != -1) {
                // System.out.println(replaceStr);
                // System.out.println("不需要处理图片!");
            } else {
                if (path.indexOf("\"")==0 || path.indexOf("'")==0)
                    path = path.substring(1);
                arrayList1.add(path);
            }
        }

        String afterReplaceStr = mailContent;

        //在html文件中用"cid:"+Content-ID来替换原来的图片链接
        for (int m = 0; m < arrayList1.size(); m++) {
            arrayList2.add(createRandomStr());
            String addString = "cid:" + (String) arrayList2.get(m);
            String str = (String) arrayList1.get(m);
            afterReplaceStr = afterReplaceStr.replaceAll((String) arrayList1.get(m),
                    addString);
        }
        // logger.info(afterReplaceStr);
        return afterReplaceStr;
    }

    //产生一个随机字符串,为了给图片设定Content-ID值
    private String createRandomStr() {
        char[] randomChar = new char[8];
        for (int i = 0; i < 8; i++) {
            randomChar[i] = (char) (Math.random() * 26 + 'a');
        }
        String replaceStr = new String(randomChar);
        return replaceStr;
    }

    private ArrayList arrayList1 = new ArrayList();
    private ArrayList arrayList2 = new ArrayList();
    /**
     * clear
     */
    public void clear() {
        try {
            if (subtype.equals(""))
                multipart = new MimeMultipart();
            else
                multipart = new MimeMultipart(subtype);
            msg.setContent(multipart);
        }
        catch (Exception e) {
            logger.error("clear: " + e.getMessage());
        }
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -