package org.springblade.utils;


import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.util.BASE64DecoderStream;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

/**
 * @author dylan
 */
public class MailHelp {
    final static String smtp_key = "smtp.126.com";
    final static String sendMail_key = "dhsvs1@126.com";
    final static String password_key = "BOZNMIURCDLOESYX";


    public static void getMail() {
        Transport transport = null;
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.imap.host", "mail.dahengsi.com"); // 设置邮件服务器主机名
            prop.put("mail.store.protocol", "imap"); // 发送邮件协议名称
            prop.put("mail.imap.port", "143");// 发送服务器需要身份验证

            prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            prop.setProperty("mail.imap.socketFactory.fallback", "false");
            prop.setProperty("mail.imap.starttls.enable", "true");
            prop.setProperty("mail.imap.socketFactory.port", "993");

            Session session = Session.getInstance(prop);
            URLName urln = new URLName("imap", "mail.dahengsi.com", 143, null, "swp@dahengsi.com", "Dh@82828800");
            // 建立IMAP协议的Store对象
            Store store = session.getStore(urln);
            store.connect();


            // 获得收件箱
            Folder folder = store.getFolder("INBOX");
            // 以读写模式打开收件箱
            folder.open(Folder.READ_WRITE);

            // 获得收件箱的邮件列表
            Message[] messages = folder.getMessages();

            // 打印不同状态的邮件数量
            System.out.println("收件箱中共" + messages.length + "封邮件!");
            System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
            System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
            System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");

            System.out.println("------------------------开始解析邮件----------------------------------");

            // 解析邮件
            for (Message message : messages) {
                IMAPMessage msg = (IMAPMessage) message;
                if(message.getFlags().contains(Flags.Flag.SEEN)){
                    continue;
                }

                String subject = MimeUtility.decodeText(msg.getSubject());

                Object wrapContent=message.getContent();
                if(wrapContent instanceof Multipart){
                    Multipart outMultipart=(Multipart) wrapContent;
                    int partCount=outMultipart.getCount();
                    for(int i=0;i<partCount;i++){
                        Part nPart=outMultipart.getBodyPart(i);
                        Object nContent=nPart.getContent();
                        if(nContent instanceof Multipart){
                            //对文本HTML块的处理
//                            Multipart nMultipart=(Multipart) nContent;
//                            int nPartCount=nMultipart.getCount();
//                            for(int k=0;k<nPartCount;k++){undefined
//                                Part nnPart=nMultipart.getBodyPart(k);
//                                System.out.println("内容类型: "+nnPart.getContentType());
//                                System.out.println("小包裹内容: "+nnPart.getContent());
//                            }

                        }else if(nContent instanceof BASE64DecoderStream){
//                            //对附件块的处理
//                            String disposition=nPart.getDisposition();
//                            if(disposition!=null){undefined
//                                String fileName=MimeUtility.decodeText(nPart.getFileName());
//                                String contentType=MimeUtility.decodeText(nPart.getContentType());
//
//                                System.out.println("i:"+i+" "+"fileName->"+fileName
//                                        +"\ncontentType->"+contentType);
//
//                                InputStream in=nPart.getInputStream();
//                                FileOutputStream out=new FileOutputStream("D:\\Users\\jxn\\Desktop\\TRANSFILE\\"+fileName);
//
//                                int len;
//                                byte[] readBytes=new byte[1024];
//                                while((len=in.read(readBytes))!=-1){undefined
//                                    out.write(readBytes,0,len);
//                                }
//
//                                out.close();
//                                in.close();
//                                System.out.println("文件下载完成");
//                            }
                        }else{
                            //直接文本块的处理
                            System.out.println("i:"+i+" "+nContent.getClass().getName());
                            System.out.println(nContent);
                        }


                    }
                }

//                System.out.println("[" + subject + "]未读，是否须要阅读此邮件（yes/no）？");
//                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//                String answer = reader.readLine();
//                if ("yes".equalsIgnoreCase(answer)) {
//                    // 第二个参数若是设置为true，则将修改反馈给服务器。false则不反馈给服务器
//                    msg.setFlag(Flags.Flag.SEEN, true);   //设置已读标志
//                }
            }

            // 关闭资源
            folder.close(false);
            store.close();

        } catch (Exception e) {
           e.printStackTrace();
        }
    }


    public static void sendMail(String toMail, String title, String mailText) {
        Transport transport = null;
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.host", smtp_key); // 设置邮件服务器主机名
            prop.put("mail.transport.protocol", "smtp"); // 发送邮件协议名称
            prop.put("mail.smtp.auth", "true");// 发送服务器需要身份验证
            Session session = Session.getDefaultInstance(prop);//设置环境信息
            // 开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
            //session.setDebug(true);
            transport = session.getTransport("smtp");
            transport.connect(smtp_key, sendMail_key, password_key);

            String[] mail_list = toMail.split(",");
            if (null != mail_list && mail_list.length > 0) {
                for (String mailAddre : mail_list) {
                    MimeMessage message = new MimeMessage(session);
                    Multipart multipart = null;
                    BodyPart contentPart = null;
                    message.setFrom(new InternetAddress(sendMail_key, "泰山系统", "UTF-8"));//设置发件人
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailAddre));
                    message.setSubject(title);
                    multipart = new MimeMultipart();//设置附件
                    contentPart = new MimeBodyPart();
                    contentPart.setContent(mailText, "text/html;charset=utf-8");
                    multipart.addBodyPart(contentPart);

                    message.setContent(multipart);
                    message.saveChanges();
                    transport.sendMessage(message, message.getAllRecipients());


                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
}
