首页 » 技术分享 » 模拟21cn邮箱登陆,获取邮件

模拟21cn邮箱登陆,获取邮件

 

模拟21cn邮箱登陆
用抓包工具firebug(本人使用的也可以时别的),找到登陆页面分析出form表单,21cn登陆的页面url是:
http://open.e.189.cn/189mail/account/unifyAccountLogin.do?appId=8013411507&version=v1.0&clientType=1&paras=C753AEA2F4A5B49F4CDB8FAA67B76EC6B7574A025C7762D4B6DF40517C089400A12B34FB306F67961C52F90B185E9D2C7C91EDA1D5B11ECCDCB6EC2E081060E34B9901761CBD9B3AC9654C6BC9A017CC5284E04EBEC9F4DF237F2E2E06E396BA5437FB665FEAE4C766ED22EDBE96383CFF858694C6148A8345A9C00695A3844735E4FF01FF0CC59FC1A62C672F9D3B168FE0AB271811A3EE5ECA0C342123FDF9B37CD271F748B2F33D6E3E28&sign=28E498416D78B2FEBED59826838D59B8EBFA374C&format=redirect
第一步:获得下一步post请求的需要的参数和cookies下面代码
//usename:为自己的用户名
//pwd为自己的邮箱密码

public static void login(String username, String pwd) {
    Map<String, String> cookies3 = null ;
    String str[] = new String[10];
    // 第一次请求
    // 获取链接
    String url = "http://open.e.189.cn/189mail/account/unifyAccountLogin.do?appId=8013411507&version=v1.0&clientType=1&paras=C753AEA2F4A5B49F4CDB8FAA67B76EC6B7574A025C7762D4B6DF40517C089400A12B34FB306F67961C52F90B185E9D2C7C91EDA1D5B11ECCDCB6EC2E081060E34B9901761CBD9B3AC9654C6BC9A017CC5284E04EBEC9F4DF237F2E2E06E396BA5437FB665FEAE4C766ED22EDBE96383CFF858694C6148A8345A9C00695A3844735E4FF01FF0CC59FC1A62C672F9D3B168FE0AB271811A3EE5ECA0C342123FDF9B37CD271F748B2F33D6E3E28&sign=28E498416D78B2FEBED59826838D59B8EBFA374C&format=redirect";

    Connection con = Jsoup.connect(url);
 con.header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0");

    // 配置模拟浏览器)

    // 获取响应
    Response rs;
    try {
        rs = con.execute();
        // System.out.println(rs.body());
        // Document doc=con.get();
        // 转换为dom
        Document dl = Jsoup.parse(rs.body());
        // 获取form表单,
        List<Element> et = dl.select("#loginForm");

        // 获取,cooking的表单属性。下面map存放post的数据
        Map<String, String> map = new HashMap<String, String>();

/* map.put(“userName”, username);
map.put(“password”,pwd);*/
for (Element e : et.get(0).getAllElements()) {
// e.attr(“name”).equals(“userName”)表示name标签的值
if (e.attr(“name”).equals(“userName”)) {
// 设置用户名
e.attr(“value”, username);
}
if (e.attr(“name”).equals(“password”)) {
// 设置用户密码
e.attr(“value”, pwd);
}
// 排除空值表单属性
if (e.attr(“name”).length() > 0) {
map.put(e.attr(“name”), e.attr(“value”));
}
}

int i = 0;
        for (Map.Entry<String, String> ele : map.entrySet()) {
        System.err.println(ele);
            str[i] = ele.getValue();
            i++;
        }

        //获取页面cookie
        Connection con1= Jsoup.connect("https://open.e.189.cn/api/common/loginSubmit.do?accountType="+str[5]+"&appId="+str[6]+"&returnUrl="+str[8]+"&clientType="+str[2]+"&userName="+str[9]+"%4021cn.com&mail="+str[3]+"&password="+str[1]+"&ValidateCode="+str[4]);
            con1.header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0");
                    Response response1 =  con1.ignoreContentType(true).method(Method.POST).data(map).execute();
                    //获取页面cookie
                Map<String, String> cookies = response1.cookies();
        }

第二部获取需要的一个cookie:LSID和下一步需要的url
Document doc=Jsoup.connect(“https://open.e.189.cn/api/common/loginSubmit.do?accountType=“+str[5]+”&appId=”+str[6]+”&returnUrl=”+str[8]+”&clientType=”+str[2]+”&userName=”+str[9]+”%4021cn.com&mail=”+str[3]+”&password=”+str[1]+”&ValidateCode=”+str[4]).get();
//获取请求以后的url
String toUrl1 = doc.baseUri().substring(doc.baseUri().indexOf(“LSID”));
String toUrl2 = toUrl1.replace(“%3D”, “=”);
String toUrl3 = toUrl2.replace(“%26”, “&”);
String LSID = toUrl3.substring((toUrl3.indexOf(“LSID”)+5),(toUrl3.indexOf(“&”)));

                            cookies.put("LSID", LSID);
                    String toUrl  = "http://mail.21cn.com/w2/logon/unifyPlatformLogonReturn.do?"+toUrl3;



                    Connection con2= Jsoup.connect(toUrl);

                con2.header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0");
                    Response response2 = con2.ignoreContentType(true).method(Method.GET).cookies(cookies).execute();
                    Map<String, String> cookies2 = response2.cookies();

                    String [] str1 = new String[2];
                    int j =0;
                    for (Map.Entry<String, String> entry : cookies2.entrySet()) {

                        str1[j] = entry.getValue();
                        j++;
                    }

//第三部:进入主页
Connection con3 =Jsoup.connect(“http://mail.21cn.com/w2/logon/signOn.do“);
con3.header(“User-Agent”, “Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0”);
Response response3 = con3.ignoreContentType(true).method(Method.GET).cookies(cookies2).execute();

                    String str2 = response3.body();
                        //获取cookie
                     cookies3 = response3.cookies();
                        String cookie = "";
                    String cookie1 = "";
                    int count = 1;
                    for (Map.Entry<String, String> entry : cookies3.entrySet()) {
                        if(count <cookies3.size()){
                        cookie1 = entry.getKey() +"="+entry.getValue()+";";
                        }else{
                            cookie1 = entry.getKey() +"="+entry.getValue();
                        }
                        count++;
    cookie = cookie + cookie1;

                    }
if(cookies3.size() > 0){
                        System.out.println("登陆成功");
                        GetEmail.getEmail(cookie);(此方法为获取邮件和附件的方法,下面会有,GetEmail是类getEmail为此类的静态方法)

                    }else{
                        System.out.println("登录失败");
                    }



    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

//获取邮件
/*
* 获取邮件
*/
public class GetEmail {
private static BufferedInputStream in;
private static BufferedInputStream out;

public static void getEmail(String cookies) {
    // http://mail.21cn.com/w2/mail/listMail.do
    String strUrl = "http://mail.21cn.com/w2/mail/listMail.do?labelId=1";

    // 创建URL对象
    URL url;
    try {
        url = new URL(strUrl);
        // 返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

        httpConn.setRequestProperty("Cookie", cookies);
        // 可以通过InputStreamReader将其转换为字符流
        InputStreamReader input = new InputStreamReader(httpConn.getInputStream(), "utf-8");
        // 读取字符流
        BufferedReader bufReader = new BufferedReader(input);
        String line = "";
        // 创建一个可变的字符串
        StringBuilder contenBuf = new StringBuilder();
        while ((line = bufReader.readLine()) != null) {
            // 不为空将数据添加到可变的字符串对象中
            contenBuf.append(line);
        }
        String str = contenBuf.toString();
        // System.out.println(str);
        // 将字符串转换为json
        JSONObject obj = JSONObject.fromObject(str);
        // 取出邮件总数量
        String mailCount = obj.getString("mailCount");
        // 创建一个JSON数组
        JSONArray firstArr = obj.getJSONArray("mailList");
        // 遍历firstArr数组
        String msId = "";
        String msIdList = "";
        String labelId = "";
        String labelIdList = "";
        String mid = "";
        String midList = "";
        // String messageId="";
        int count = 1;
        // List<String> mdList = new ArrayList<String>();
        for (int i = 0; i < firstArr.length(); i++) {
            // 将数组的值转化为JSONObject
            JSONObject object = (JSONObject) firstArr.get(i);
            /*
             * //根据key取出对应的值
             * 
             * //发件人 String sender = object.getString("sender"); //发件主题
             * String subject = object.getString("subject");
             */
            // 获取msid
            msId= object.getString("msId");
            // 获取labelList
            String labelId1 = object.getString("labelIdList");
            // 获取消息id
            mid = object.getString("messageId");

            //
            // mdList.add(mid);
            int mailcount = Integer.parseInt(mailCount);
            if (count < mailcount) {
                msIdList = msIdList + msId + ",";

                labelId = labelId1.substring((labelId1.indexOf("[") + 1), labelId1.indexOf("]"));
                labelIdList = labelIdList + labelId + ",";

                midList = midList + mid + ",";
            } else {
                msIdList = msIdList + msId;

                labelIdList = labelIdList + labelId;

                midList = midList + mid;
            }
            count++;
                }
                    System.out.println("邮件数量" + mailCount);
        for (int i = 0; i < firstArr.length(); i++) {
            // 将数组的值转化为JSONObject
            JSONObject object = (JSONObject) firstArr.get(i);
            // 根据key取出对应的值

            // 发件人
            String sender = object.getString("sender");
            System.out.println("发件人: " + sender);
            // 发件主题
            String subject = object.getString("subject");
            System.out.println("发件主题: " + subject);
            // 发件日期
            String send = object.getString("sendDate");
            // 创建一个日期格式化对象并设定转换格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            // 1.将字符串转换为Long的整数
            // 2.将long着整数转换为date日期格式
            String sendDate = sdf.format(new Date(Long.parseLong(send)));
            System.out.println("发件时间: " + sendDate);
            String mid1 = object.getString("messageId");
            // 邮件内容
            emaiConnect(msIdList, labelIdList, midList, mid1, cookies);
            //判断是否有附件然后爬去附件
             ifEmailFile( labelId,mid1,msId,cookies);


        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

// 获得邮件内容
public static void emaiConnect(String msidList, String labelIdList, String midList, String mid, String cookie) {
    String strUrl = "http://mail.21cn.com/w2/mail/getAbstract.do?msidList=" + msidList + "&labelsList="
            + labelIdList + "&midList=" + midList;
    try {
        URL url = new URL(strUrl);
        // 返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestProperty("Cookie", cookie);
        // 可以通过InputStreamReader将其转换为字符流
        InputStreamReader input = new InputStreamReader(httpConn.getInputStream(), "utf-8");
        // 读取字符流
        BufferedReader bufreader = new BufferedReader(input);
        String line = "";
        // 创建一个可变字符串
        StringBuilder buf = new StringBuilder();
        // 按行读取
        while ((line = bufreader.readLine()) != null) {
            // 不为空将数据添加到可变的字符串对象中
            buf.append(line);
        }

        String str = buf.toString();
        // 将字符串转换为json
        JSONObject obj = JSONObject.fromObject(str);
        // System.out.println(obj.toString());
        JSONObject obj1 = (JSONObject) obj.get("abstractMap");
        JSONObject obj3 = (JSONObject) obj1.get(mid);
        // 获取内容
        String comment = obj3.getString("mailAbstract");
        System.out.println("邮件内容: " + comment + "\n");

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("加载地址有误");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("远程连接失败");
        e.printStackTrace();
    }
}
// 判断是否有附件
public static void ifEmailFile(String labelId, String messageId, String msId, String cookie) {
    String strUrl = "http://mail.21cn.com/w2/mail/readMail.do?labelId+" + labelId + "&messageId=" + messageId
            + "&msId=" + msId;
    try {
        URL url = new URL(strUrl);
        // 返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestProperty("Cookie", cookie);
        // 可以通过InputStreamReader将其转换为字符流
        InputStreamReader input = new InputStreamReader(httpConn.getInputStream(), "utf-8");
        // 读取字符流
        BufferedReader bufreader = new BufferedReader(input);
        String line = "";
        // 创建一个可变字符串
        StringBuilder buf = new StringBuilder();
        // 按行读取
        while ((line = bufreader.readLine()) != null) {
            // 不为空将数据添加到可变的字符串对象中
            buf.append(line);
        }

        String str = buf.toString();
        // 将字符串转换为json
        JSONObject obj = JSONObject.fromObject(str);
        String file = obj.getString("attachmentList");
        String subject = (String) obj.get("subject");
        if (!file.substring((file.indexOf("[") + 1), file.lastIndexOf("]")).equals("")) {
            System.out.println("邮件标题为:" + subject + "    邮件中含有附件\r\n爬去附件");
            JSONArray frr = obj.getJSONArray("attachmentList");
            for (int i = 0; i < frr.length(); i++) {

// System.out.println(“ss”);
JSONObject obj1 = (JSONObject) frr.get(i);
String path = obj1.getString(“name”);
String partid = obj1.getString(“id”);
// System.out.println(partid);
downloadEmailFile(messageId,msId,partid,cookie,path);
}
}
// System.out.println(obj.toString());
// JSONObject obj1 = (JSONObject) obj.get(“attachmentList”);
// JSONObject obj3 = (JSONObject) obj1.get(mid);
// 获取内容
// String comment = obj3.getString(“mailAbstract”);
// System.out.println(“邮件内容: ” + comment + “\n”);

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("加载地址有误");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("远程连接失败");
        e.printStackTrace();
    }
}
//下载附件
    public static void downloadEmailFile(String messageid, String msid, String partid,String cookie,String path) throws IOException {
    String sourceURL = "http://mail.21cn.com/w2/downLoadAttachNormal.do?messageid=" + messageid + "&msid=" + msid
            + "&partid=" + partid;
            +   URL url;
    try {
        url = new URL(sourceURL);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Cookie", cookie);
        java.io.InputStream inputStream = connection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream("/home/ycw/桌面/"+path);
        //"/home/ycw/桌面/"+path这是我的输出地址,可以根据自己的需要修改
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        byte buffer[] = new byte[inputStream.available()];
        in = new BufferedInputStream(inputStream, buffer.length);
        out = new BufferedOutputStream(outputStream, buffer.length);
        int total = 0;
        String str;
        for (int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;) {
            str = new String(buffer);
            System.out.println(str);
            out.write(buffer, 0, bytesRead);
            total += bytesRead;
        }

        System.out.println(total);
        in.close();
        out.close();

    } catch (MalformedURLException e) { // TODO Auto-generated catch block
        System.out.println("地址有误");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("建立远程链接失败"); // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}
希望对你有所帮助

转载自原文链接, 如需删除请联系管理员。

原文链接:模拟21cn邮箱登陆,获取邮件,转载请注明来源!

0