当前位置: 代码迷 >> 综合 >> java 邮件系统
  详细解决方案

java 邮件系统

热度:34   发布时间:2023-12-17 09:17:19.0

1.发送邮件的方法

public class MailTemplateHelper {

    /** 短信模板分类ID */
    private static final String ID = "FSYJ";

    /** 短信模板文件存放路径 */
    private static final String PATH =  File.separator + "template" + File.separator + "mail" + File.separator;

    /** 模板文件扩展名 */
    private static final String EXT = "ftl";

    /** 模板接口类 */
    private static final ITemplate tempalte = new TemplateImpl();

    public static boolean sendMail(String key, Map<?, ?> root, String[] emails, String mailSubject) {
        // 短信参数
        String mailTemplateNo = getData(key, root);
        // 判断是否发送成功
        boolean isSuccess = true;
        // 发送短信
        if (emails != null && emails.length > 0) {
            for (String s : emails) {
                if (s != null && !s.equals("")) {
                    MailInfo mail = new MailInfo();
                    mail.addTo(s);
                    mail.setSubject(mailSubject);
                    mail.setBody(mailTemplateNo);
                    isSuccess = MailSenderHelper.asynSend(mail);
                }
            }
        } else {
            isSuccess = false;
        }
        return isSuccess;
    }

    // 根据路径取到邮件模板

    public static String getData(String key, Map<?, ?> root) {
        String templateName = ID + "_" + key + "." + EXT;
        return tempalte.getData(PATH, templateName, root);
    }

}

 

public class TemplateImpl implements ITemplate {

    /**
     * 根据模板全路径取得模板,并转换其中的变量为实际的数据
     *
     * @param path
     *            模板文件路径
     * @param templateName
     *            模板文件名
     * @param root
     *            数据源map
     */
    public String getData(String path, String templateName, Map<?, ?> root) {
        try {
            // 初使化FreeMarker配置           
            Configuration config = new Configuration();
            // 设置包装器,并将对象包装为数据模型
            config.setClassForTemplateLoading(TemplateImpl.class, path);
            config.setObjectWrapper(new DefaultObjectWrapper());
            Template template = config.getTemplate(templateName, "UTF-8");
            // 合并数据模型与模板
            StringWriter writer = new StringWriter();
            template.process(root, writer);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

 

/**
 * <p>电子邮件工具类</p>
 * <ol>[提供机能]
 * <li>通过这个工具可以完成异步或者同步发送邮件。
 * </ol>
 */
public class MailSenderHelper {

    /** 邮件访问地址 */
    private static final String URL = Resources.getData("MAIL_SEND_URL");

    /**
     * <p>异步发送邮件</p>
     * @param info 邮件信息对象
     * @return 结果 true:成功;false:失败
     */
    public static boolean asynSend(MailInfo info) {

        MailHttpClient client = new MailHttpClient(URL);
        return client.asynSend(info);
    }
}

/**
 * 电子邮件HTTP远程调用工具类。
 * @author huyunlin
 */
public class MailHttpClient {

    /** 远程连接地址 */
    private String url;

    /**
     * 构造函数
     * @param url 远程连接地址
     */
    public MailHttpClient(String url) {
        this.url = url;
    }

    /**
     * <p>异步发送邮件</p>
     * <ol>[功能概要]
     * <div>系统首先保存邮件,然后系统自动发送已经保存的电子邮件.</div>
     * <div>必填项:主题,收件人(*),内容
     * (*)多个收件人以逗号隔开,即可以使用集合变量付值(to),也可以采用字符串付值(toStr)
     * </div>
     * <div>可填项:发件人</div>
     * <div>可填项:预定发送时间</div>
     * <div>可填项:是否重复发送</div>
     * </ol>
     * @param info 邮件信息对象
     * @return 结果 true:成功;false:失败
     */
    public boolean asynSend(MailInfo info) {

        Map<String, String> map = new HashMap<String, String>();

        // 主题
        if (info.getSubject() != null && info.getSubject().length() > 0) {
            map.put("subject", info.getSubject());
        }
        // 收件人(以逗号隔开)
        if (info.getToStr() != null && info.getToStr().length() > 0) {
            map.put("to", info.getToStr());
        } else {
            List<String> list = info.getTo();
            String toStr = null;
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (i == 0) {
                        toStr = list.get(i);
                    } else {
                        toStr += "," + list.get(i);
                    }
                }
                if (toStr != null) {
                    map.put("to", toStr);
                }
            }
        }
        // 内容
        if (info.getBody() != null && info.getBody().length() > 0) {
            map.put("body", info.getBody());
        }

        // 发件人
        if (info.getFrom() != null && info.getFrom().length() > 0) {
            map.put("sender", info.getFrom());
        }
        // 发送时间(YYYYMMDDHHMMSS)
        if (info.getSendDate() != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            map.put("time", format.format(info.getSendDate()));
        }
        // 是否重复发送
        if (info.getReFlg() != null && info.getReFlg().length() > 0) {
            map.put("re", info.getReFlg());
        }

        String result = URLTools.post(url, map);
        try {
            int resultInt = Integer.parseInt(result);
            if (resultInt >= 0) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

    }

}

/*
 * HTTP远程调用工具类  URLTools
 *
 */

package cn.com.onezero.util.client.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import cn.com.onezero.util.client.express.ExpressConstant;

/**
 * HTTP远程调用工具类,目前提供GET和POST两种请求方式。
 */
public class URLTools {

    /**
     * 以HTTP协议的GET请求方式获取返回值
     * @param urlvalue 调用地址
     * @return 请求结果
     */
    public static String get(String urlvalue) {

        String inputLine = "";

        try {
            URL url = new URL(urlvalue);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

            inputLine = in.readLine().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return inputLine;
    }

    /**
     * 以HTTP协议的POST请求方式获取返回值
     * @param url 调用地址
     * @param map 参数
     * @return 请求结果
     */
    public static String post(String url, Map<String, String> map) {

        String inputLine = null;

        // 连接对象
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
        } catch (Exception e) {
            e.printStackTrace();
            return inputLine;
        }

        // 构造参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = map.keySet();
        Iterator<String> ite = keySet.iterator();
        while (ite.hasNext()) {
            String key = ite.next();
            nvps.add(new BasicNameValuePair(key, map.get(key)));
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            // 成功返回
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity); // 释放

        } catch (Exception e) {
            e.printStackTrace();
            return inputLine;
        } finally {
            httpPost.releaseConnection();
        }

        return inputLine;
    }

    /**
     * 以HTTP协议的POST请求方式获取二进制返回值
     * @param url 调用地址
     * @param map 参数
     * @return 对象数组,第一个元素为图片数据,第二元素为会话ID
     */
    public static Object[] postValicode(String url, Map<String, String> map) {

        // 连接对象
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 构造参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = map.keySet();
        Iterator<String> ite = keySet.iterator();
        while (ite.hasNext()) {
            String key = ite.next();
            nvps.add(new BasicNameValuePair(key, map.get(key)));
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            // 从cookie中获取SessionID
            String sessionId = null;
            CookieStore cookieStore = httpclient.getCookieStore();
            List<Cookie> cookieList = cookieStore.getCookies();
            if (cookieList != null && !cookieList.isEmpty()) {
                for (int i = 0; i < cookieList.size(); i++) {
                    Cookie cookie = cookieList.get(i);
                    if (ExpressConstant.EXPRESS_SESSION_KEY.equals(cookie.getName())) {
                        sessionId = cookie.getValue();
                    }
                }
            }

            // 成功返回
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return new Object[]{EntityUtils.toByteArray(entity), sessionId};
            }
            EntityUtils.consume(entity); // 释放

            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            httpPost.releaseConnection();
        }
    }
}

 

/*
 * 接收邮件Servlet类
 */

/**
 * <p>接收邮件Servlet类</p>
 */
public class MailReceiveServlet extends HttpServlet {

    /** 日志 */
    private static final transient Logger LOG = Logger.getLogger(MailReceiveServlet.class);

    /**
     * GET方式接收消息
     * @param req 请求对象
     * @param res 响应对象
     */
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        doPost(req, res);
    }

    /**
     * POST方式接收消息
     * @param req 请求对象
     * @param res 响应对象
     */
    public void doPost(HttpServletRequest req, HttpServletResponse res) {

        try {

            res.reset();
            res.setContentType("text/plain;charset=" + MailConstant.DEFAULT_ENCODE);
            req.setCharacterEncoding("UTF-8");
            PrintWriter out = res.getWriter();

            MailInfo info = new MailInfo();
            // 主题
            String subject = req.getParameter("subject");
            if (!Validator.isNullEmpty(subject)) {
                subject = subject.trim();
            }
            info.setSubject(subject);
            // 收件人(以逗号隔开)
            String to = req.getParameter("to");
            if (!Validator.isNullEmpty(to)) {
                to = to.trim();
                if (to.indexOf(MailConstant.MAIL_SEPRATE_TO) == -1) {
                    info.addTo(to);
                } else {
                    info.addTo(to.split(MailConstant.MAIL_SEPRATE_TO));
                }
            }

            // 内容
            String body = req.getParameter("body");
            if (!Validator.isNullEmpty(body)) {
                body = body.trim();
            }
            info.setBody(body);
            // 发件人
            String sender = req.getParameter("sender");
            if (!Validator.isNullEmpty(sender)) {
                sender = sender.trim();
            }
            info.setMailSender(sender);

            // 是否重复发送
            String re = req.getParameter("re");
            if (!Validator.isNullEmpty(re)) {
                re = re.trim();
            }
            info.setReFlg(re);

            // 发送时间(YYYYMMDDHHMMSS)
            String sendDate = req.getParameter("time");
            if (!Validator.isNullEmpty(sendDate)) {
                sendDate = sendDate.trim();
                try {
                    info.setSendDate(DateUtil.dateToTimestamp(DateUtil.parseDateTimeL(sendDate)));
                } catch (ParseException e) {
                    // 邮件内容不正确
                    out.println(MailConstant.MAIL_NEW_STATUS_INCORRECT);
                    out.flush();
                    out.close();
                    return;
                }
            }

            if (checkMailInfo(info)) {
                WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(req
                    .getSession().getServletContext());
                EmailManager manager = (EmailManager) ctx.getBean("emailManager");
                out.print(manager.addEmailInfo(info));
            } else {
                // 邮件内容不正确
                out.println(MailConstant.MAIL_NEW_STATUS_INCORRECT);
            }

            out.flush();
            out.close();

        } catch (Exception e) {
            // 发生异常
            LOG.error("接收邮件信息时发生异常", e);
        }
    }

    /**
     * <p>检查邮件内容是否正确</p>
     * @param info 邮件信息对象
     * @return true:成功;false:失败
     */
    private boolean checkMailInfo(MailInfo info) {

        // 收件人
        if (info.getTo() == null || info.getTo().isEmpty()) {
            // log.info("收信人邮件地址不能为空");
            return false;
        }

        Iterator<String> ite = info.getTo().iterator();
        List<String> bak = new ArrayList();
        while (ite.hasNext()) {
            String mail = ite.next();
            if (Validator.isNullEmpty(mail) || !Validator.isEmail(mail)) {
                // log.info("收信人邮件地址不正确");
                return false;
            }

            if (bak.contains(mail)) {
                ite.remove();
            } else {
                bak.add(mail);
            }
        }

        // 主题
        if (!Validator.isNullEmpty(info.getSubject()) && info.getSubject().length() > 40) {
            // log.info("主题内容超过40个字符");
            return false;
        }

        // 内容
        if (Validator.isNullEmpty(info.getBody())
            || Validator.getWordCount(info.getBody()) > 64 * 1024) {
            // log.info("邮件内容为空或者超过64K字节");
            return false;
        }

        // 发件用户ID
        if (Validator.isNullEmpty(info.getMailSender())) {
            info.setMailSender(MailConstant.MAIL_SUBMITER_DEFAULT);
        }

        return true;
    }
}

 

  相关解决方案