SendCommonPostMail.java 9.59 KB
package com.reyun.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.reyun.context.AppUtils;
import com.reyun.model.Email;
import com.reyun.repository.ConfigParamRepository;
import com.reyun.simulationlogin.SouHu;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class SendCommonPostMail {

    protected static Logger logger = LoggerFactory.getLogger(SendCommonPostMail.class);
    public static final String CONTENT_TYPE = Constant.mailContentType;
    public static final String FROM_EMAIL_ADDRESS = Constant.mailUsername;
    public static final String EMAIL_ADDESS = "logo_res_email_addess";
    public static final String EMAIL_USERNAME = "logo_res_email_username";
    public static final String EMAIL_PASSWORD = "logo_res_email_password";
    public static final String EMAIL_HOST = "logo_res_email_host";
    static String url = "http://api.sendcloud.net/apiv2/mail/send";
    static String apiUser = "TrackingIO_mail_service";
    static String apiKey = "I9OlVXux7qwPpgge";

    public static void main(String[] args) throws IOException {
        List<String> email = new ArrayList<String>();
        email.add("68333201@qq.com");
        String subject = "test";
        String content = "test";

        String contents = "<!doctype html><html><head></head><body> " +
                "Larry:</br>" +
                "在或至Office查看详情 </br>" +
                "<a href=\"http://www.baidu.com\">http://www.baidu.com</a>" +
                "</body></html>";
        try {
            boolean b = SendCommonPostMail.sendMailReuse(email, subject, contents, null, null, new HashMap<>());
            System.out.println(b);
        }catch (Exception e){
            System.out.println("捕捉到了异常");
        }

    }

    /**
     * 功能描述:复合邮件发送
     * @param ccList 可空-抄送地址.
     * @param bccList 可空-密送地址.
     * @param content 必填-邮件的内容. 邮件格式为 text/html
     * @param subject 必填-标题
     * @param userEmailAddress 必填-收件人地址.
     *
     *
     * @author liyin
     * @date 2019/7/1
     */
    public static boolean sendMailReuse(List<String> userEmailAddress, String subject, String content,List<String>  ccList,List<String> bccList) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httPost = new HttpPost(url);
//        String toEmail = userEmailAddress == null ? "kangxiaoshan@reyun.com;wangpeiyang@reyun.com" : StringUtils.collectionToDelimitedString(userEmailAddress, ";");
//        String bcc = bccList == null ? null : StringUtils.collectionToDelimitedString(bccList, ";");
//        String cc = ccList == null ? null : StringUtils.collectionToDelimitedString(ccList, ";");

        String toEmail ;
        String bcc = null;
        String cc = null;

        List<String> testUsersEamil = fillNotProEmail();
        if (testUsersEamil != null) {
            //测试环境  使用默认收件人
            toEmail =  StringUtils.collectionToDelimitedString(testUsersEamil, ";");
        }else{
            //线上环境
            toEmail = userEmailAddress == null ? null : StringUtils.collectionToDelimitedString(userEmailAddress, ";");
            bcc = bccList == null ? null : StringUtils.collectionToDelimitedString(bccList, ";");
            cc = ccList == null ? null : StringUtils.collectionToDelimitedString(ccList, ";");
        }

        List params = new ArrayList();
        // 您需要登录SendCloud创建API_USER,使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("from", "trackingio@service.reyun.com"));
        params.add(new BasicNameValuePair("fromName", "TrackingIO"));
        params.add(new BasicNameValuePair("to", toEmail));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", content));
        if(cc!=null&&!"".equals(cc)){
            params.add(new BasicNameValuePair("cc", cc));
        }
        if(bcc!=null&&!"".equals(bcc)){
            params.add(new BasicNameValuePair("bcc", bcc));
        }
        boolean success = false;

            httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            // 请求
            HttpResponse response = httpclient.execute(httPost);
            // 处理响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                // 读取xml文档
                String result = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(result);
                String result1 = jsonObject.getString("result");
                success = Boolean.valueOf(result1);
                if(!success){
                    logger.error(result);
                    throw new Exception(result);
                }
            } else {
                logger.error("邮件发送状态异常:" + toEmail);
                throw new Exception("邮件发送状态异常:" + toEmail);
            }
            httPost.releaseConnection();

        return success;
    }
/**
 * 功能描述:多两个参数,from发件人邮箱;发件人名字
 * @author liyin
 * @date 2019/7/2
 */
    public static boolean sendMailReuse(List<String> userEmailAddress, String subject, String content, List<String>  ccList, List<String> bccList,Map<String,String> mailConfig) throws Exception  {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httPost = new HttpPost(url);

        String toEmail;
        String bcc = null;
        String cc = null;

        List<String> testUsersEamil = fillNotProEmail();
        if (testUsersEamil != null) {
            //测试环境  使用默认收件人
            toEmail =  StringUtils.collectionToDelimitedString(testUsersEamil, ";");
        }else{
            //线上环境
            toEmail = userEmailAddress == null ? null : StringUtils.collectionToDelimitedString(userEmailAddress, ";");
            bcc = bccList == null ? null : StringUtils.collectionToDelimitedString(bccList, ";");
            cc = ccList == null ? null : StringUtils.collectionToDelimitedString(ccList, ";");
        }


        String from;
        String fromName;
        if(mailConfig!=null){
            from = mailConfig.get(SendCommonPostMail.EMAIL_USERNAME) == null?FROM_EMAIL_ADDRESS:mailConfig.get(SendCommonPostMail.EMAIL_USERNAME);
            fromName = from;
        }else{
            from=FROM_EMAIL_ADDRESS;
            fromName=FROM_EMAIL_ADDRESS;
        }
        List params = new ArrayList();
        // 您需要登录SendCloud创建API_USER,使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("from", from));
        params.add(new BasicNameValuePair("fromName", fromName));
        params.add(new BasicNameValuePair("to", toEmail));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", content));
        if(cc!=null&&!"".equals(cc)){
            params.add(new BasicNameValuePair("cc", cc));
        }
        if(bcc!=null&&!"".equals(bcc)){
            params.add(new BasicNameValuePair("bcc", bcc));
        }
        boolean success = false;
            httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            // 请求
            HttpResponse response = httpclient.execute(httPost);
            // 处理响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                // 读取xml文档
                String result = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(result);
                String result1 = jsonObject.getString("result");
                success = Boolean.valueOf(result1);
                if(!success){
                    logger.error(result);
                    throw new Exception(result);
                }
            } else {
                logger.error("邮件发送状态异常:" + toEmail);
                throw new Exception("邮件发送状态异常:" + toEmail);
            }
            httPost.releaseConnection();
        return success;
    }


    private static List<String> fillNotProEmail(){

        // 测试环境设置为默认的收件人

        if("true".equals(Constant.mailProd)){
            return null;
        }

        ConfigParamRepository configParamRepository = AppUtils.getApplicationContext().getBean(ConfigParamRepository.class);

        String testEmails = configParamRepository.findParamsByKey("not_pro_user_email");

        if(StringUtils.isEmpty(testEmails)){
            testEmails = "kangxiaoshan@reyun.com";
        }

        List<String> emails =new ArrayList<>();

        if(!org.apache.commons.lang.StringUtils.isEmpty(testEmails)){
            emails.addAll(Arrays.asList(testEmails.split(",")));
        }

        // 非线上环境收件人
        return emails;

    }

}