email

来源:https://blog.csdn.net/xyang81/article/details/7675160     详见此人其它mail 篇

参考2:http://lib.csdn.net/article/java/65792

依赖:"

  <!--  邮件 https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>-b01</version>
        </dependency>
        

1. POP3只可以接受,不可以修改状态, 如该邮件已读,下次不读

package org.yangxin.study.jm;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 使用POP3协议接收邮件
 */
public class POP3ReceiveMailTest {

    public static void main(String[] args) throws Exception {
        receive();
    }

    /**
     * 接收邮件
     */
    public static void receive() throws Exception {
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3");        // 协议
        props.setProperty(");                // 端口
        props.setProperty("mail.pop3.host", "pop3.163.com");    // pop3服务器

        // 创建Session实例对象
        Session session = Session.getInstance(props);
        Store store = session.getStore("pop3");
        store.connect("xyang0917@163.com", "123456abc");

        // 获得收件箱
        Folder folder = store.getFolder("INBOX");
        /* Folder.READ_ONLY:只读权限
         * Folder.READ_WRITE:可读可写(可以修改邮件的状态)
         */
        folder.open(Folder.READ_WRITE);    //打开收件箱

        // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
        System.out.println("未读邮件数: " + folder.getUnreadMessageCount());

        // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
        System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
        System.out.println("新邮件: " + folder.getNewMessageCount());

        // 获得收件箱中的邮件总数
        System.out.println("邮件总数: " + folder.getMessageCount());

        // 得到收件箱中的所有邮件,并解析
        Message[] messages = folder.getMessages();
        parseMessage(messages);

        //释放资源
        folder.close(true);
        store.close();
    }

    /**
     * 解析邮件
     * @param messages 要解析的邮件列表
     */
    public static void parseMessage(Message ...messages) throws MessagingException, IOException {
        )
            throw new MessagingException("未找到要解析的邮件!");

        // 解析所有邮件
        , count = messages.length; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
            System.out.println("主题: " + getSubject(msg));
            System.out.println("发件人: " + getFrom(msg));
            System.out.println("收件人:" + getReceiveAddress(msg, null));
            System.out.println("发送时间:" + getSentDate(msg, null));
            System.out.println("是否已读:" + isSeen(msg));
            System.out.println("邮件优先级:" + getPriority(msg));
            System.out.println("是否需要回执:" + isReplySign(msg));
            System. + "kb");
            boolean isContainerAttachment = isContainAttachment(msg);
            System.out.println("是否包含附件:" + isContainerAttachment);
            if (isContainerAttachment) {
                saveAttachment(msg, "c:\\mailtmp\\"+msg.getSubject() + "_"); //保存附件
            }
            StringBuffer content = );
            getMailTextContent(msg, content);
            System. ? content.substring(,) + "..." : content));
            System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
            System.out.println();
        }
    }

    /**
     * 获得邮件主题
     * @param msg 邮件内容
     * @return 解码后的邮件主题
     */
    public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
        return MimeUtility.decodeText(msg.getSubject());
    }

    /**
     * 获得邮件发件人
     * @param msg 邮件内容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        )
            throw new MessagingException("没有发件人!");

        InternetAddress address = (InternetAddress) froms[];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "";
        }
        from = person + "<" + address.getAddress() + ">";

        return from;
    }

    /**
     * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
     * <p>Message.RecipientType.TO  收件人</p>
     * <p>Message.RecipientType.CC  抄送</p>
     * <p>Message.RecipientType.BCC 密送</p>
     * @param msg 邮件内容
     * @param type 收件人类型
     * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
     * @throws MessagingException
     */
    public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        )
            throw new MessagingException("没有收件人!");
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress)address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }

        receiveAddress.deleteCharAt(receiveAddress.length()-);    //删除最后一个逗号

        return receiveAddress.toString();
    }

    /**
     * 获得邮件发送时间
     * @param msg 邮件内容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy年MM月dd日 E HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 判断邮件中是否包含附件
     * @param msg 邮件内容
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            ; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    ) {
                        flag = true;
                    }  

                    ) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part)part.getContent());
        }
        return flag;
    }

    /**
     * 判断邮件是否已读
     * @param msg 邮件内容
     * @return 如果邮件已读返回true,否则返回false
     * @throws MessagingException
     */
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判断邮件是否需要阅读回执
     * @param msg 邮件内容
     * @return 需要回执返回true,否则返回false
     * @throws MessagingException
     */
    public static boolean isReplySign(MimeMessage msg) throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null)
            replySign = true;
        return replySign;
    }

    /**
     * 获得邮件的优先级
     * @param msg 邮件内容
     * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
     * @throws MessagingException
     */
    public static String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[];
             || headerPriority.indexOf()
                priority = "紧急";
             || headerPriority.indexOf()
                priority = "低";
            else
                priority = "普通";
        }
        return priority;
    } 

    /**
     * 获得邮件文本内容
     * @param part 邮件体
     * @param content 存储邮件文本内容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf(;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part)part.getContent(),content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            ; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart,content);
            }
        }
    }

    /**
     * 保存附件
     * @param part 邮件中多个组合体中的其中一个组合体
     * @param destDir  附件保存目录
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            ; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart,destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                     || contentType.indexOf() {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(),destDir);
        }
    }

    /**
     * 读取输入流中的数据保存至指定目录
     * @param is 输入流
     * @param fileName 文件名
     * @param destDir 文件存储目录
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        ;
        ) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解码
     * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    public static String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }
}

2.imap ---POP3的替代品,可以修改邮件状态  ,推荐使用

package com.icil.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.imap.IMAPMessage;

/**
 * <b>使用IMAP协议接收邮件</b><br/>
 * <p>POP3和IMAP协议的区别:</p>
 * <b>POP3</b>协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作(如移动邮件、标记已读等),不会反馈到服务器上,<br/>
 * 比如通过客户端收取了邮箱中的3封邮件并移动到其它文件夹,邮箱服务器上的这些邮件是没有同时被移动的。<br/>
 * <p><b>IMAP</b>协议提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会同步反应到服务器上,对邮件进行的操作,服务
 * 上的邮件也会做相应的动作。比如在客户端收取了邮箱中的3封邮件,并将其中一封标记为已读,将另外两封标记为删除,这些操作会
 * 即时反馈到服务器上。</p>
 * <p>两种协议相比,IMAP 整体上为用户带来更为便捷和可靠的体验。POP3更易丢失邮件或多次下载相同的邮件,但IMAP通过邮件客户端
 * 与webmail之间的双向同步功能很好地避免了这些问题。</p>
 */
public class MailUtis002 {

    public static void main(String[] args) throws Exception {
        receive();

    }

    public static void receive() throws Exception {
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.163.com");
        props.setProperty(");

        // 创建Session实例对象
        Session session = Session.getInstance(props);

        // 创建IMAP协议的Store对象
        Store store = session.getStore("imap");

        // 连接邮件服务器

        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;
            String subject = MimeUtility.decodeText(msg.getSubject());
//            System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
//            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//            String answer = reader.readLine();
//            if ("yes".equalsIgnoreCase(answer)) {
                parseMessage(msg);    // 解析邮件
                // 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器
//                msg.setFlag(Flag.SEEN, true);    //设置已读标志
//            }
        }

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

    /** ***********************************************************/

    /**
     * 解析邮件
     * @param messages 要解析的邮件列表
     */
    public static void parseMessage(Message ...messages) throws MessagingException, IOException {

        )
            throw new MessagingException("未找到要解析的邮件!");

        // 解析所有邮件
        , count = messages.length; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            if(!isSeen(msg)){
                System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
                System.out.println("主题: " + getSubject(msg));
                System.out.println("发件人: " + getFrom(msg));
                System.out.println("收件人:" + getReceiveAddress(msg, null));
                System.out.println("发送时间:" + getSentDate(msg, null));
                System.out.println("是否已读:" + isSeen(msg));
                System.out.println("邮件优先级:" + getPriority(msg));
                System.out.println("是否需要回执:" + isReplySign(msg));
                System. + "kb");
                boolean isContainerAttachment = isContainAttachment(msg);
                System.out.println("是否包含附件:" + isContainerAttachment);
                if (isContainerAttachment) {
                    saveAttachment(msg, "c:\\mailtmp\\"+msg.getSubject() + "_"); //保存附件
                }
                StringBuffer content = );
                getMailTextContent(msg, content);
                System. ? content.substring(,) + "..." : content));
                System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
                System.out.println();
                msg.setFlag(Flag.SEEN, true);
            }
        }
    }

    /**
     * 获得邮件主题
     * @param msg 邮件内容
     * @return 解码后的邮件主题
     */
    public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
         String subject = msg.getSubject();

        if(subject==null){
            subject="";
        }
        return MimeUtility.decodeText(subject);
    }

    /**
     * 获得邮件发件人
     * @param msg 邮件内容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        )
            throw new MessagingException("没有发件人!");

        InternetAddress address = (InternetAddress) froms[];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "";
        }
        from = person + "<" + address.getAddress() + ">";

        return from;
    }

    /**
     * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
     * <p>Message.RecipientType.TO  收件人</p>
     * <p>Message.RecipientType.CC  抄送</p>
     * <p>Message.RecipientType.BCC 密送</p>
     * @param msg 邮件内容
     * @param type 收件人类型
     * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
     * @throws MessagingException
     */
    public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        )
            throw new MessagingException("没有收件人!");
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress)address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }

        receiveAddress.deleteCharAt(receiveAddress.length()-);    //删除最后一个逗号

        return receiveAddress.toString();
    }

    /**
     * 获得邮件发送时间
     * @param msg 邮件内容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy年MM月dd日 E HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 判断邮件中是否包含附件
     * @param msg 邮件内容
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            ; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    ) {
                        flag = true;
                    }  

                    ) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part)part.getContent());
        }
        return flag;
    }

    /**
     * 判断邮件是否已读
     * @param msg 邮件内容
     * @return 如果邮件已读返回true,否则返回false
     * @throws MessagingException
     */
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判断邮件是否需要阅读回执
     * @param msg 邮件内容
     * @return 需要回执返回true,否则返回false
     * @throws MessagingException
     */
    public static boolean isReplySign(MimeMessage msg) throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null)
            replySign = true;
        return replySign;
    }

    /**
     * 获得邮件的优先级
     * @param msg 邮件内容
     * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
     * @throws MessagingException
     */
    public static String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[];
             || headerPriority.indexOf()
                priority = "紧急";
             || headerPriority.indexOf()
                priority = "低";
            else
                priority = "普通";
        }
        return priority;
    } 

    /**
     * 获得邮件文本内容
     * @param part 邮件体
     * @param content 存储邮件文本内容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
        boolean isContainTextAttach = part.getContentType().indexOf(;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part)part.getContent(),content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            ; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart,content);
            }
        }
    }

    /**
     * 保存附件
     * @param part 邮件中多个组合体中的其中一个组合体
     * @param destDir  附件保存目录
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
            //复杂体邮件包含多个邮件体
            int partCount = multipart.getCount();
            ; i < partCount; i++) {
                //获得复杂体邮件中其中一个邮件体
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一个邮件体也有可能是由多个邮件体组成的复杂体
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart,destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                     || contentType.indexOf() {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(),destDir);
        }
    }

    /**
     * 读取输入流中的数据保存至指定目录
     * @param is 输入流
     * @param fileName 文件名
     * @param destDir 文件存储目录
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        ;
        ) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解码
     * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
     * @return 解码后的文本
     * @throws UnsupportedEncodingException
     */
    public static String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }

}

3.发送邮件

package com.icil.utils;

import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * <p>
 * @Description: 邮件发送工具类
 * </p>
 *
 * @author sea
 * @Date 2018-08-03
 */
public class MailSenderUtils {

    String to = ""; // 收件人邮箱地址
    String from = ""; // 发件人邮箱地址
    String host = ""; // smtp主机
    String username = ""; // 用户名
    String password = ""; // 密码
    String filename = ""; // 附件文件名
    String subject = ""; // 邮件主题
    String content = ""; // 邮件正文
    Vector file = new Vector();// 附件文件集合

    public MailSenderUtils() {
        super();
    }

    public MailSenderUtils(String to, String from, String smtpServer, String username, String password, String subject,
            String content) {
        this.to = to;
        this.from = from;
        this.host = smtpServer;
        this.username = username;
        this.password = password;
        this.subject = subject;
        this.content = content;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPassWord(String pwd) {
        this.password = pwd;
    }

    public void setUserName(String usn) {
        this.username = usn;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @param strText
     * @return
     * @Description: 把主题转为中文 utf-8
     * @Date 2017年6月22日 上午10:37:07
     */
    public String transferChinese(String strText) {
        try {
            strText = MimeUtility.encodeText(new String(strText.getBytes(), "utf-8"), "utf-8", "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strText;
    }

    public void attachfile(String fname) {
        file.addElement(fname);
    }

    /**
     * @return
     * @Description: 发送邮件,发送成功返回true 失败false
     * @author sea
     * @Date 2018年8月3日
     */
    public boolean sendMail() {

        // 构造mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put(

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 构造MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
            subject = transferChinese(subject);
            msg.setSubject(subject);

            // 构造Multipart
            Multipart mp = new MimeMultipart();

            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content, "text/html;charset=utf-8");

            // 向MimeMessage添加(Multipart代表正文)
            mp.addBodyPart(mbpContent);

            // 向Multipart添加附件
            Enumeration efile = file.elements();
            while (efile.hasMoreElements()) {

                MimeBodyPart mbpFile = new MimeBodyPart();
                filename = efile.nextElement().toString();
                FileDataSource fds = new FileDataSource(filename);
                mbpFile.setDataHandler(new DataHandler(fds));
                String filename = new String(fds.getName().getBytes(), "ISO-8859-1");

                mbpFile.setFileName(filename);
                // 向MimeMessage添加(Multipart代表附件)
                mp.addBodyPart(mbpFile);

            }

            file.removeAllElements();
            // 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();

            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean sendMail(String to, String subject, String content) {
        MailSenderUtils sendmail = new MailSenderUtils();
        sendmail.setHost("smtp.163.com");
        sendmail.setUserName("lshan523@163.com");
        sendmail.setPassWord("lshan523");
        sendmail.setTo(to);
        sendmail.setFrom("lshan523@163.com");
        sendmail.setSubject(subject);
        sendmail.setContent(content);
        // 添加附件
        // sendmail.attachfile("d:\\CoolFormat3.4.rar");
        System.out.println(sendmail.sendMail());

        return true;
    }

    /**
     * sea 20180802
     *
     * @param args
     *            参考设置:https://www.west.cn/faq/list.asp?Unid=852
     */
    public static void main(String[] args) {
        MailSenderUtils sendmail = new MailSenderUtils();
        // sendmail.setHost("smtp.exmail.qq.com");
        sendmail.setHost("smtp.163.com");
        sendmail.setUserName("lshan523@163.com");
        sendmail.setPassWord("dsadas");
        sendmail.setTo("sealiu@icil.net");
        sendmail.setFrom("lshan523@163.com");
        sendmail.setSubject("张小米");
        sendmail.setContent("Test 呵呵");
        // 添加附件
        // sendmail.attachfile("d:\\CoolFormat3.4.rar");
        System.out.println(sendmail.sendMail());
    }
}

发邮件已整理:

package com.icil.esolution.utils;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ********************************************
 *
 * @ClassName: MailUtils
 *
 * @Description:
 *
 * @author Sea
 *
 * @date 24 Aug 2018 8:34:09 PM
 *
 ***************************************************
 */
@SuppressWarnings("all")
public class MailUtils {
    private static final Logger logger = LoggerFactory.getLogger(MailUtils.class);

    private Vector file = new Vector();// 附件文件集合

    private final String MAIL_CONFIG_PATH = "/resources/mailconfig.properties";

    public static boolean sendMail(String subject, String content) {
        boolean mails = new MailUtils().sendMails(null, null, subject, content, null);
        return mails;
    }

    public static boolean sendMail(String to, String subject, String content) {
        boolean mails = new MailUtils().sendMails(to, null, subject, content, null);
        return mails;
    }

    public static boolean sendMail(String to, String from, String subject, String content) {
        boolean mails = new MailUtils().sendMails(to, from, subject, content, null);
        return mails;
    }

    /**
     * @return
     * @Description: 发送邮件,发送成功返回true 失败false
     * @author sea
     * @Date 2018年8月3日
     */
    private boolean sendMails(String to1, String from1, String subject, String content, String filename) {

        Properties properties = getProperties(MAIL_CONFIG_PATH);
        String to = (String) properties.get("MAIL_SENDTO");
        String from = (String) properties.get("MAIL_USERNAME");
        String host = (String) properties.get("MAIL_SMTPSERVER");
        String username = (String) properties.get("MAIL_USERNAME");
        String password = (String) properties.get("MAIL_PASSWORD");

        if (to1 != null) {
            to = to1;
        }
        if (from1 != null) {
            from = from1;
        }
        // 构造mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put(

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 构造MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
            subject = transferChinese(subject);
            msg.setSubject(subject);

            // 构造Multipart
            Multipart mp = new MimeMultipart();

            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content, "text/html;charset=utf-8");

            // 向MimeMessage添加(Multipart代表正文)
            mp.addBodyPart(mbpContent);

            // 向Multipart添加附件
            Enumeration efile = file.elements();
            while (efile.hasMoreElements()) {

                MimeBodyPart mbpFile = new MimeBodyPart();
                filename = efile.nextElement().toString();
                FileDataSource fds = new FileDataSource(filename);
                mbpFile.setDataHandler(new DataHandler(fds));
                filename = new String(fds.getName().getBytes(), "ISO-8859-1");

                mbpFile.setFileName(filename);
                // 向MimeMessage添加(Multipart代表附件)
                mp.addBodyPart(mbpFile);

            }

            file.removeAllElements();
            // 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();

            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }

    public Properties getProperties(String path) {

        Properties properties = new Properties();
        try {
            synchronized (properties) {
                properties.load(this.getClass().getResourceAsStream(path));
            }
        } catch (IOException e) {
            return null;
        }

        return properties;
    }

    /**
     * @param strText
     * @return
     * @Description: 把主题转为中文 utf-8
     * @Date 2017年6月22日 上午10:37:07
     */
    public String transferChinese(String strText) {
        try {
            strText = MimeUtility.encodeText(new String(strText.getBytes(), "utf-8"), "utf-8", "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strText;
    }

    public void attachfile(String fname) {
        file.addElement(fname);
    }

    /**
     *
     * @Description:test ok 2018-08-24
     *
     * @author Sea
     *
     * @date 24 Aug 2018 8:34:09 PM
     */
    public static void main(String[] args) {
        boolean mails = new MailUtils().sendMails(null, null, "hello", "I love you", null);
        System.out.println(mails);
    }

}

不需要认证:

package com.icil.milestone.push.common.utils;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ********************************************
 *
 * @ClassName: MailUtils
 *
 * @Description:
 *
 * @author Sea
 *
 * @date 24 Aug 2018 8:34:09 PM
 *
 ***************************************************
 */
@SuppressWarnings("all")
public class MailUtils {
    private static final Logger logger = LoggerFactory.getLogger(MailUtils.class);

    private Vector file = new Vector();// 附件文件集合

    private final String MAIL_CONFIG_PATH = "/resources/properties/mailConfig.properties";

    public static boolean sendMail(String subject, String content) {
        boolean mails = new MailUtils().sendMails(null, null, subject, content, null);
        return mails;
    }

    public static boolean sendMail(String to, String subject, String content) {
        boolean mails = new MailUtils().sendMails(to, null, subject, content, null);
        return mails;
    }

    public static boolean sendMail(String to, String from, String subject, String content) {
        boolean mails = new MailUtils().sendMails(to, from, subject, content, null);
        return mails;
    }

    /**
     * @return
     * @Description: 发送邮件,发送成功返回true 失败false
     * @author sea
     * @Date 2018年8月3日
     */
    private boolean sendMails(String to1, String from1, String subject, String content, String filename) {

        Properties properties = getProperties(MAIL_CONFIG_PATH);
        String to = (String) properties.get("MAIL_SEND_TO");
        String from = (String) properties.get("MAIL_FROM");
        String host = (String) properties.get("MAIL_SMTPSERVER");
//        String username = (String) properties.get("MAIL_USERNAME");
//        String password = (String) properties.get("MAIL_PASSWORD");
        String username = "";
        String password ="";

        if (to1 != null) {
            to = to1;
        }
        if (from1 != null) {
            from = from1;
        }
        // 构造mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
//        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.auth","false");    

//        Session session = Session.getDefaultInstance(props, new Authenticator() {
//            public PasswordAuthentication getPasswordAuthentication() {
//                return new PasswordAuthentication(username, password);
//            }
//        });
        Session session=Session.getDefaultInstance(props);
        try {
            // 构造MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
//            msg.addRecipients(Message.RecipientType.CC, address);
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            subject = transferChinese(subject);
            msg.setSubject(subject);

            // 构造Multipart
            Multipart mp = new MimeMultipart();

            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content, "text/html;charset=utf-8");

            // 向MimeMessage添加(Multipart代表正文)
            mp.addBodyPart(mbpContent);

            // 向Multipart添加附件
            Enumeration efile = file.elements();
            while (efile.hasMoreElements()) {

                MimeBodyPart mbpFile = new MimeBodyPart();
                filename = efile.nextElement().toString();
                FileDataSource fds = new FileDataSource(filename);
                mbpFile.setDataHandler(new DataHandler(fds));
                filename = new String(fds.getName().getBytes(), "ISO-8859-1");

                mbpFile.setFileName(filename);
                // 向MimeMessage添加(Multipart代表附件)
                mp.addBodyPart(mbpFile);

            }

            file.removeAllElements();
            // 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();

            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }

    public Properties getProperties(String path) {

        Properties properties = new Properties();
        try {
            synchronized (properties) {
                properties.load(this.getClass().getResourceAsStream(path));
            }
        } catch (IOException e) {
            return null;
        }

        return properties;
    }

    /**
     * @param strText
     * @return
     * @Description: 把主题转为中文 utf-8
     * @Date 2017年6月22日 上午10:37:07
     */
    public String transferChinese(String strText) {
        try {
            strText = MimeUtility.encodeText(new String(strText.getBytes(), "utf-8"), "utf-8", "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strText;
    }

    public void attachfile(String fname) {
        file.addElement(fname);
    }

    /**
     *
     * @Description:test ok 2018-08-24
     *
     * @author Sea
     *
     * @date 24 Aug 2018 8:34:09 PM
     */
    public static void main(String[] args) {
        boolean mails = ", "hello", "I love you icil", null);
        System.out.println(mails);
    }

}

email 解析 ,发送 邮件的更多相关文章

  1. MVC 4 网页版发送 邮件的配置问题

    有时项目要用到邮箱验证就要发送邮件传统的解决方案: public void SendResetPasswordEmail(string email) { MailAddress from = new ...

  2. 使用django进行发送 邮件

    我们来看一下 django发送 邮件的整个流程 第一步:例先去 网易163注册账号并激活发邮件功能 把授权码进行 开启 来到我们的项目setting中进行 一个配置: # 邮箱的配置信息 EMAIL_ ...

  3. java mail实现Email的发送,完整代码

    java mail实现Email的发送,完整代码 1.对应用程序配置邮件会话 首先, 导入jar <dependencies> <dependency> <groupId ...

  4. Socket与Http方式解析发送xml消息封装中间件jar包

    最近项目代码中太多重复的编写Document,不同的接口需要不同的模板,于是重写提取公共部分打成jar包,方便各个系统统一使用~ 提取结构: Http连接方式: import java.nio.cha ...

  5. 在Salesforce中处理Email的发送

    在Salesforce中可以用自带的 Messaging 的 sendEmail 方法去处理Email的发送 请看如下一段简单代码: public boolean TextFormat {get;se ...

  6. 利用Python imaplib和email模块 读取邮件文本内容及附件内容

    python使用imap接收邮件的过程探索 https://www.cnblogs.com/yhlx/archive/2013/03/22/2975817.html #! encoding:utf8 ...

  7. Python 标准库 —— 邮件(email)与邮件服务器(smtplib)

    你真的懂邮件吗?邮件包括如下四部分内容: 发送人:from_addr 接收人:to_addr 主题:subject 正文:msg(mime text 格式文本) 其中发送者,接收者,又需要两部分的内容 ...

  8. Jenkins Email Extension Plugin 邮件插件

    1:系统管理-管理插件-可选插件  搜索Email 可列出Email Extension Plugin插件 2:选择相应的插件点  下载并安装之后重启,等待 3:安装完后,自己去重启tomcat,先s ...

  9. 利用CodeIgniter中的Email类发邮件

    CodeIgniter拥有功能强大的Email类.以下为利用其发送邮件的代码. 关于CI的Email类的详情请参考:http://codeigniter.org.cn/user_guide/libra ...

随机推荐

  1. wpf中的触发器详解 (转自 乂乂的日志 - 网易博客)

    2010-03-24 16:19:07|  分类: WPF相关 |  标签: |字号大中小 订阅     wpf中的触发器详解 WPF/C# 2009-08-24 11:32:50 7.1.2  简单 ...

  2. Android Studio 中实现高德定位并获取相应信息

    Android开发项目时常常会遇到定位这个功能,所以写了这篇博客,今天主要讲的高德地图的定位并获取相应信息. 首先导入高德的jar包 选中jar包右键点击  Add As Library, 在buil ...

  3. 在请求中使用XML Publisher生成文件报错

    在页面上使用按钮生成该文件不报错,但是使用请求就报错. 错误内容如下 Error : No corresponding LOB data found :SELECT L.FILE_DATA FILE_ ...

  4. IOS-快速集成检查更新

    一直以为Appstore有了检查版本是否更新的机制,我们在APP上做这个更新功能会被拒,但是也有看到一些APP也是做了这个更新功能的.因为在网上没有找到完全正确的方法能获取到iTunes里的数据的,于 ...

  5. myeclipse10修改全局jsp编码格式为gbk

    myeclipse10修改全局jsp编码格式为gbk: window->prefenrence->general->content types->  展开:text->j ...

  6. 关于将vector以及string传递给较老的api的问题

    现在可能STL使用的越来越多,但是一些较老的api并不支持例如vector这样的兑现,但是可以使用一些技巧来使其适应于这些函数. 例如对于使用到int*型的函数来说,传入一个 &vector[ ...

  7. 『转』Bitdefender Internet Security 2013 – 免费1年

    活动中可以选择获取Bitdefender Internet Security 2013+Bitdefender Mobile Security (手机版)各一年激活码申请地址:https://part ...

  8. 201621123006 《Java程序设计》第5周学习总结

    1. 本周学习总结 1.1 写出你认为本周学习中比较重要的知识点关键词. 继承.接口.抽象类.多态.interfac.comparable 1.2 尝试使用思维导图将这些关键词组织起来.注:思维导图一 ...

  9. LNMP架构下Discuz论坛的搭建

    在上一节中,我们对lnmp架构下的mysql.php.nginx进行源码的安装,并设置了相关的安装参数.现在我们将在上一节的基础上,把三者联系起来进行一个论坛的部署. 一.首先进行Discuz(社区论 ...

  10. PHP迭代器的小坑

    使用PHP迭代器的时候,需要主要到很多迭代器是对内部迭代器的封装,当外部迭代器移动的时候,实际上也是在移动内部迭代器. 示例一:命令行 &"C:\wamp64\bin\php\php ...