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);
    }

}

最新文章

  1. js学习笔记:webpack基础入门(一)
  2. mapreduce流程中的几个关键点
  3. jQuery简介及语法
  4. python字典中的元素类型
  5. NAND Flash【转】
  6. NSNotificationCenter需要注意的几个问题
  7. lk启动流程详细分析
  8. JAXB - Annotations, Annotations for Enums: XmlEnum, XmlEnumValue
  9. smarty半小时快速上手入门教程
  10. cocos2D(三)---- 第一cocos2d的程序代码分析
  11. Xamarin.Android 入门实例(4)之实现对 SQLLite 进行添加/修改/删除/查询操作
  12. C#,VB.NET 如何将Excel转换为Text
  13. Java打印常见图形
  14. mac 查看某个文件夹下所有隐藏文件(夹)的大小
  15. obj-c编程14:Cocoa和Cocoa Touch简介
  16. Jenkins结合.net平台工具之Nunit
  17. Microsoft.mshtml.dll 添加引用及类型选择错误问题解决办法
  18. 设置table中的td一连串内容自动换行
  19. OpenCV 调用双摄像头
  20. 6 vue-cli mock数据

热门文章

  1. Centos7 firewalld命令行
  2. hashcode()和equals()方法
  3. New Concept English Two 24 64
  4. Robot Framework中使用HttpLibrary教程and中文支持
  5. W: GPG error: http://dl.google.com/linux/chrome/deb stable Release: The following signatures couldn'
  6. PyAlgoTrade Hello World 第一个程序(一)
  7. Centos7 服务 service 设置命令 systemctl 用法 (替代service 和 chkconfig)
  8. 为Python编写一个简单的C语言扩展模块
  9. java 之DelayQueue,TaskDelayed,handlerFactory,dataChange消息配置.收发等.java spring事务处理TransactionTemplate
  10. ajax请求返回Json字符串运用highcharts数据图表展现数据