使用javax.mail收发邮件

依赖:
 
        
            javax.mail
            mail
            1.5.0-b01
        
1.使用SMTP发送邮件
@ 转自:http://blog.csdn.net/smok56888/article/details/50070453
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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;

public class Email {
    private static String defaultSenderName = "";// 默认的发件人用户名,defaultEntity用得到
    private static String defaultSenderPass = "";// 默认的发件人密码,defaultEntity用得到
    private static String defaultSmtpHost = "";// 默认的邮件服务器地址,defaultEntity用得到

    private String smtpHost; // 邮件服务器地址
    private String sendUserName; // 发件人的用户名
    private String sendUserPass; // 发件人密码

    private MimeMessage mimeMsg; // 邮件对象
    private Session session;
    private Properties props;
    private Multipart mp;// 附件添加的组件
    private List files = new LinkedList();// 存放附件文件

    private void init() {
        if (props == null) {
            props = System.getProperties();
        }
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true"); // 需要身份验证
        session = Session.getDefaultInstance(props, null);
        // 置true可以在控制台(console)上看到发送邮件的过程
        session.setDebug(true);
        // 用session对象来创建并初始化邮件对象
        mimeMsg = new MimeMessage(session);
        // 生成附件组件的实例
        mp = new MimeMultipart();
    }

    private Email(String smtpHost, String sendUserName, String sendUserPass, String to, String cc, String mailSubject, String mailBody,
            List attachments) {
        this.smtpHost = smtpHost;
        this.sendUserName = sendUserName;
        this.sendUserPass = sendUserPass;

        init();
        setFrom(sendUserName);
        setTo(to);
        setCC(cc);
        setBody(mailBody);
        setSubject(mailSubject);
        if (attachments != null) {
            for (String attachment : attachments) {
                addFileAffix(attachment);
            }
        }

    }

    /**
     * 邮件实体
     * 
     * @param smtpHost
     *            邮件服务器地址
     * @param sendUserName
     *            发件邮件地址
     * @param sendUserPass
     *            发件邮箱密码
     * @param to
     *            收件人,多个邮箱地址以半角逗号分隔
     * @param cc
     *            抄送,多个邮箱地址以半角逗号分隔
     * @param mailSubject
     *            邮件主题
     * @param mailBody
     *            邮件正文
     * @param attachmentPath
     *            附件路径
     * @return
     */
    public static Email entity(String smtpHost, String sendUserName, String sendUserPass, String to, String cc, String mailSubject, String mailBody,
            List attachments) {
        return new Email(smtpHost, sendUserName, sendUserPass, to, cc, mailSubject, mailBody, attachments);
    }

    /**
     * 默认邮件实体,用了默认的发送帐号和邮件服务器
     * 
     * @param to
     *            收件人,多个邮箱地址以半角逗号分隔
     * @param cc
     *            抄送,多个邮箱地址以半角逗号分隔
     * @param subject
     *            邮件主题
     * @param body
     *            邮件正文
     * @param attachment
     *            附件全路径
     * @return
     */
    public static Email defaultEntity(String to, String cc, String subject, String body, List attachments) {
        return new Email(defaultSmtpHost, defaultSenderName, defaultSenderPass, to, cc, subject, body, attachments);
    }

    /**
     * 设置邮件主题
     * 
     * @param mailSubject
     * @return
     */
    private boolean setSubject(String mailSubject) {
        try {
            mimeMsg.setSubject(mailSubject);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 设置邮件内容,并设置其为文本格式或HTML文件格式,编码方式为UTF-8
     * 
     * @param mailBody
     * @return
     */
    private boolean setBody(String mailBody) {
        try {
            BodyPart bp = new MimeBodyPart();
            bp.setContent("" + mailBody, "text/html;charset=UTF-8");
            // 在组件上添加邮件文本
            mp.addBodyPart(bp);
        } catch (Exception e) {
            System.err.println("设置邮件正文时发生错误!" + e);
            return false;
        }
        return true;
    }

    /**
     * 添加一个附件
     * 
     * @param filename
     *            邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常
     * @return
     */
    public boolean addFileAffix(String filename) {
        try {
            if (filename != null && filename.length() > 0) {
                BodyPart bp = new MimeBodyPart();
                FileDataSource fileds = new FileDataSource(filename);
                bp.setDataHandler(new DataHandler(fileds));
                bp.setFileName(MimeUtility.encodeText(fileds.getName(), "utf-8", null)); // 解决附件名称乱码
                mp.addBodyPart(bp);// 添加附件
                files.add(fileds);
            }
        } catch (Exception e) {
            System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
            return false;
        }
        return true;
    }

    /**
     * 删除所有附件
     * 
     * @return
     */
    public boolean delFileAffix() {
        try {
            FileDataSource fileds = null;
            for (Iterator it = files.iterator(); it.hasNext();) {
                fileds = it.next();
                if (fileds != null && fileds.getFile() != null) {
                    fileds.getFile().delete();
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 设置发件人地址
     * 
     * @param from
     *            发件人地址
     * @return
     */
    private boolean setFrom(String from) {
        try {
            mimeMsg.setFrom(new InternetAddress(from));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 设置收件人地址
     * 
     * @param to收件人的地址
     * @return
     */
    private boolean setTo(String to) {
        if (to == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 设置抄送
     * 
     * @param cc
     * @return
     */
    private boolean setCC(String cc) {
        if (cc == null) {
            return false;
        }
        try {
            mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 发送邮件
     * 
     * @return
     */
    public boolean send() throws Exception {
        mimeMsg.setContent(mp);
        mimeMsg.saveChanges();
        System.out.println("正在发送邮件....");
        Transport transport = session.getTransport("smtp");
        // 连接邮件服务器并进行身份验证
        transport.connect(smtpHost, sendUserName, sendUserPass);
        // 发送邮件
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
        System.out.println("发送邮件成功!");
        transport.close();
        return true;
    }
}
所需依赖:
      
            javax.mail
            javax.mail-api
            1.5.2
            jar
            compile
        
        
            com.sun.mail
            smtp
            1.5.2
            jar
            compile
        
        
            com.sun.mail
            mailapi
            1.5.2
            jar
            compile
        

        
            junit
            junit
            4.9
            test
        

2.使用POP3接收邮件
import com.google.common.base.Strings;
import com.sun.mail.pop3.POP3SSLStore;
import org.testng.annotations.Test;
import javax.mail.*;
import java.io.*;
import java.util.Date;
import java.util.Properties;

public class EmailInspector {
    public static final String EMAIL_SERVER_URL = "pop3.mxhichina.com";
    public static final String GMAIL_SERVER_URL = "pop.gmail.com";
    public static String email = "";
    public static String password = "";

    public static void initEmailInspector(String email, String password) {
        EmailInspector.email = email;
        EmailInspector.password = password;
    }


    public static void clearInbox() throws Exception {
        // connect to my pop3 inbox
        Store store;
        if(email.contains("@gmail"))
            store = gmailWithSSLConnect();
        else
            store = emailConnect();
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);

        // get the list of inbox messages
        Message[] messages = inbox.getMessages();

        if (messages.length == 0) System.out.println("No messages found.");

        for (int i = 0; i < messages.length; i++) {
            System.out.println("Message " + (i + 1));
            System.out.println("From : " + messages[i].getFrom()[0]);
            System.out.println("Subject : " + messages[i].getSubject());
            System.out.println("Sent Date : " + messages[i].getSentDate());
            System.out.println("Content : " + messages[i].getContent().toString());
            writePart(messages[i]);
            System.out.println();
            messages[i].setFlag(Flags.Flag.DELETED, true);
        }

        inbox.close(true);
        store.close();
    }


    public static Message getLatestEmail() throws Exception {
        Store store;
        Message lastestEmail = null;
        if(email.contains("@gmail"))
            store = gmailWithSSLConnect();

        else
            store = emailConnect();
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);

        // get the list of inbox messages
        Message[] messages = inbox.getMessages();

        if (messages.length == 0) {
            System.out.println("No messages found.");
           return null;
        }

        lastestEmail = messages[messages.length - 1];
        return lastestEmail;
    }


    /**
     * This method checks for content-type
     * based on which, it processes and
     * fetches the content of the message
     */
    private static String writePart(Part p) throws Exception {
        if (p instanceof Message)
            //Call method writeEnvelope
            writeEnvelope((Message) p);

        System.out.println("----------------------------");
        System.out.println("CONTENT-TYPE: " + p.getContentType());

        //check if the content is plain text
        if (p.isMimeType("text/plain")) {
            System.out.println("This is plain text");
            System.out.println("---------------------------");
            System.out.println((String) p.getContent());
        }
        //check if the content has attachment
        else if (p.isMimeType("multipart/*")) {
            System.out.println("This is a Multipart");
            System.out.println("---------------------------");
            Multipart mp = (Multipart) p.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                String str = writePart(mp.getBodyPart(i));
                if (str != null)
                    return str;
            }
        }
        //check if the content is a nested message
        else if (p.isMimeType("message/rfc822")) {
            System.out.println("This is a Nested Message");
            System.out.println("---------------------------");
            writePart((Part) p.getContent());
        }
        //check if the content is an inline image
        else if (p.isMimeType("image/jpeg")) {
            System.out.println("--------> image/jpeg");

        }
        else if (p.getContentType().contains("image/")) {
            System.out.println("content type" + p.getContentType());
            File f = new File("image" + new Date().getTime() + ".jpg");
            DataOutputStream output = new DataOutputStream(
                    new BufferedOutputStream(new FileOutputStream(f)));
            com.sun.mail.util.BASE64DecoderStream test =
                    (com.sun.mail.util.BASE64DecoderStream) p
                            .getContent();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = test.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        }
        else {
            Object o = p.getContent();
            if (o instanceof String) {
                System.out.println("This is a string");
                System.out.println("---------------------------");
                System.out.println((String) o);
                return (String) o;
            }
            else if (o instanceof InputStream) {
                System.out.println("This is just an input stream");
                System.out.println("---------------------------");
                InputStream is = (InputStream) o;
                is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            }
            else {
                System.out.println("This is an unknown type");
                System.out.println("---------------------------");
                System.out.println(o.toString());
            }
        }
        return null;
    }
    /*
    * This method would print FROM,TO and SUBJECT of the message
    */
    public static void writeEnvelope(Message m) throws Exception {
        System.out.println("This is the message envelope");
        System.out.println("---------------------------");
        Address[] a;

        // FROM
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("FROM: " + a[j].toString());
        }

        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("TO: " + a[j].toString());
        }

        // SUBJECT
        if (m.getSubject() != null)
            System.out.println("SUBJECT: " + m.getSubject());
    }

    public static Store gmailWithSSLConnect() throws Exception {

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port",  "995");
        pop3Props.setProperty("mail.pop3.socketFactory.port", "995");

        URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
                email, password);

        Session session = Session.getInstance(pop3Props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(email, password);
            }
        });
        Store store = new POP3SSLStore(session, url);
        store.connect();
        return store;
    }


    public static Store emailConnect() throws Exception {
        Properties properties = System.getProperties();
        Session session = Session.getDefaultInstance(properties);
        Store store = session.getStore("pop3");
        store.connect(EMAIL_SERVER_URL, email, password);
        return store;
    }

    @Test
    public void test() throws Exception {
        initEmailInspector("[email protected]","Test!123");
        System.out.println(getLatestEmail().getSubject());
    }
}

你可能感兴趣的:(使用javax.mail收发邮件)