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

📄 sendmail.java

📁 cwbbs 云网论坛源码
💻 JAVA
字号:
package cn.js.fan.mail;import java.io.File;import java.io.IOException;import java.util.*;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.activation.*;import javax.mail.*;import javax.mail.internet.*;import javax.servlet.ServletContext;import javax.servlet.http.*;import org.apache.log4j.Logger;import sun.misc.BASE64Encoder;import com.redmoon.kit.util.FileUpload;import com.redmoon.kit.util.FileInfo;import cn.js.fan.util.StrUtil;public class SendMail {    public String host;    public String mailFooter;    public String mailFooterHTML;    boolean sessionDebug;    Message msg;    Multipart multipart;    Session session;    PopupAuthenticator popAuthenticator;    String username;    String password;    String errinfo;    int port = 25;    String subtype = "related";    String tempAttachFilePath;    Logger logger = Logger.getLogger(SendMail.class.getName());    public SendMail() {        host = "fserver";        mailFooter = "";        mailFooterHTML = "";    }    public void setmailFooter(String s) throws Exception {        mailFooter = s;    }    public void setmailFooterHTML(String s) throws Exception {        mailFooterHTML = s;    }        public boolean send(String smtpServer, int smtpPort, String smtpUser, String smtpPwd, String to, String from, String subject,                        String content) {        clear();        boolean re = false;        try {            initSession(smtpServer, smtpPort, smtpUser, smtpPwd);            initMsg(to, from, subject, content, true);            re = send();        }        catch (Exception e) {            logger.error("send(,,,,):" + e.getMessage());        }        return re;    }    public void initSession(String host, int port, String username,                            String password, String subtype) {        this.port = port;        this.host = host;        this.username = username;        this.password = password;        this.subtype = subtype;        try {            Properties properties = System.getProperties();            properties.put("mail.host", host);            properties.put("mail.transport.protocol", "smtp");            properties.put("mail.smtp.auth", "true");            properties.put("mail.smtp.port", "" + port);            PopupAuthenticator popupauthenticator = new PopupAuthenticator();            popupauthenticator.init(username, password);            session = Session.getInstance(properties, popupauthenticator);            session.setDebug(sessionDebug);            msg = new MimeMessage(session);            msg.setSentDate(new Date());            if (subtype.equals(""))                multipart = new MimeMultipart();            else                multipart = new MimeMultipart(subtype);            msg.setContent(multipart);        } catch (Exception e) {            errinfo += e.getMessage();            logger.error("initSession: " + e.getMessage());        }    }    public void initSession(String host, String username, String password,                            String subtype) {        initSession(host, 25, username, password, subtype);    }    public void initSession(String host, String username, String password) throws            Exception {        initSession(host, 25, username, password, "");    }    public void initSession(String host, int port, String username, String password) throws            Exception {        initSession(host, port, username, password, "");    }    public void initMsg(String to, String from, String subject, String body,                        boolean flag) {        setSendTo(to);        setFrom(from);        setSubject(subject);        setBody(body, flag);    }        public void initMsg(String to[], String from, String subject, String body,                        boolean flag) throws Exception {        setSendTo(to);        setFrom(from);        setSubject(subject);        setBody(body, flag);    }    public void initMsg(String to, String subject, String body, boolean flag) throws            Exception {        setSendTo(to);        setSubject(subject);        setBody(body, flag);    }    public void setFrom(String from) {        try {            msg.setFrom(new InternetAddress(from));        } catch (Exception e) {            errinfo += e.getMessage();            logger.error("setFrom: " + e.getMessage());        }    }    void setSendTo(String to[]) {        for (int i = 0; i < to.length; i++)            setSendTo(to[i]);    }    void setSendTo(String to) {        try {            InternetAddress ainternetaddress[] = {                                                 new InternetAddress(to)            };            msg.setRecipients(javax.mail.Message.RecipientType.TO,                              ainternetaddress);        } catch (Exception e) {            errinfo += e.getMessage();            logger.error("setSendTo: " + e.getMessage());        }    }    void setCopyTo(String to[]) throws Exception {        for (int i = 0; to != null && i > to.length; i++)            setCopyTo(to[i]);    }    void setCopyTo(String to) throws Exception {        InternetAddress ainternetaddress[] = {                                             new InternetAddress(to)        };        msg.setRecipients(javax.mail.Message.RecipientType.CC, ainternetaddress);    }                void setSubject(String subject) {        try {            BASE64Encoder base64encoder = new BASE64Encoder();            msg.setSubject("=?GB2312?B?" +                           base64encoder.encode(subject.getBytes()) +                           "?=");        } catch (Exception e) {            errinfo += e.getMessage();            logger.error("setSubject: " + e.getMessage());        }    }        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");                                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;    }        public void getMailInfo(ServletContext application,                            HttpServletRequest request) {        String realPath = application.getRealPath("/");        if (realPath.lastIndexOf("/")!=realPath.length()-1)            realPath += "/";        tempAttachFilePath = realPath + "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);                         CleanUp cln = null;         HttpSession session = null;        session = request.getSession(false);        if (session == null)            session = request.getSession(true);        String strlc = (String) session.getAttribute("lc");         if (strlc == null)            strlc = "0";        int lc = Integer.parseInt(strlc);                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());            }        }    }        class CleanUp implements HttpSessionBindingListener {        String m_filename = null;         public CleanUp(String filename) {            m_filename = filename;        }        public void valueBound(HttpSessionBindingEvent e) {                                                        }        public void valueUnbound(HttpSessionBindingEvent e) {                        File delFile = new File(m_filename);            if (delFile != null) {                delFile.delete();            }                                }    }        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) + ">";                        messageBodyPart.setHeader("Content-ID", contentId);            messageBodyPart.setFileName((String) arrayList1.get(i));            multipart.addBodyPart(messageBodyPart);        }    }        private String getContent(String mailContent) {        Pattern pattern;        Matcher matcher;        pattern = Pattern.compile("src=([^>]*[^/].(?:jpg|jpeg|bmp|gif))(?:\\\"|\\'|\\s)", Pattern.CASE_INSENSITIVE);                matcher = pattern.matcher(mailContent);        while (matcher.find()) {            String path = matcher.group(1);            if (path.indexOf("http://") != -1) {                                            } else {                if (path.indexOf("\"")==0 || path.indexOf("'")==0)                    path = path.substring(1);                arrayList1.add(path);            }        }        String afterReplaceStr = mailContent;                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);        }                return afterReplaceStr;    }        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();        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 + -