码迷,mamicode.com
首页 > 编程语言 > 详细

利用Javamail接收QQ邮箱和Gmail邮箱(转)

时间:2016-04-03 01:44:16      阅读:829      评论:0      收藏:0      [点我收藏+]

标签:

求大神解答

Java代码:

 public class SendMailController {

    //@Autowired
    private JavaMailSenderImpl mailSender;

    @RequestMapping(value ="/sendMail", method = RequestMethod.GET) 
    public void sendMail(HttpServletRequest request) throws MessagingException {
        mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.qq.com");  //设置邮件服务器
        mailSender.setUsername("XXXX@qq.com");
        mailSender.setPassword("**********");

        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper msgHelper = new MimeMessageHelper(msg, true, "utf-8");

        msgHelper.setTo("YYYYYYYYY@qq.com");
        msgHelper.setFrom("XXXXXXX@qq.com");
        msgHelper.setSubject("测试发送带附件的邮件");
        msgHelper.setText("测试邮件");

        FileSystemResource file = new FileSystemResource(new File("D:/test.png"));
        msgHelper.addAttachment("test.png", file); //添加附件

        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "25000"); 
        mailSender.setJavaMailProperties(prop);

        mailSender.send(msg);

        System.out.println("邮件发送成功!");
    }
}

错误:
type Exception report

message Request processing failed; nested exception is org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn‘t connect to host, port: smtp.qq.com, 25; timeout -1;

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn‘t connect to host, port: smtp.qq.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn‘t connect to host, port: smtp.qq.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect; message exceptions (1) are:
Failed message 1: com.sun.mail.util.MailConnectException: Couldn‘t connect to host, port: smtp.qq.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

http://ask.csdn.net/questions/180211

java默认会优先使用ipv6,但是你检查一下你的电脑,是不是ipv6那里没有获得ip?只有ipv4那里是有的。

2种办法:
1.运行你的程序的时候,跟上-Djava.net.preferIPv4Stack=true
2.在你电脑上禁用ipv6,就是在网络连接状态-属性里去掉勾选。

 

Java Mail接收邮件连接超时异常

通过命令行telnet可以成功实现邮件的接收,但JavaMaik总是报连接超时的异常,代码如下:

 @Controller
public class ReceiveMailController {

    @RequestMapping(value ="/receiveMail", method = RequestMethod.GET) 
    public void receiveMail(HttpServletRequest request) throws MessagingException, IOException {
        String host = "pop3.sina.com";
        String port = "110";
        String userName = "******@sina.com";
        String password = "******";

        Properties p = System.getProperties();
        p.put("mail.store.protocol", "pop3");
        p.put("mail.pop3.host", host);
        p.put("mail.pop3.port", port);
        p.put("mail.pop3.auth", "true");//需要邮件服务器认证

        MailAuthenticator auth = new MailAuthenticator(userName, password);
        Session session = Session.getDefaultInstance(p, auth);

        try{
            Store store = session.getStore("pop3");
            store.connect(host, userName, password);

            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);

            Message msg[] = folder.getMessages();

            //Integer msgCount = msg.length;
            for(int i = 0, msgCount = msg.length; i < msgCount; i++){
                System.out.println("第"+i+"封邮件主题:"+msg[i].getSubject());
            }

            folder.close(true);
            store.close();

            System.out.println("Email received successfully!");
        }catch(MessagingException e){
            e.printStackTrace();
        }
    }
}

异常:
com.sun.mail.util.MailConnectException: Couldn‘t connect to host, port: pop3.sina.com, 110; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:211)
at javax.mail.Service.connect(Service.java:364)
at javax.mail.Service.connect(Service.java:245)

http://ask.csdn.net/questions/181815

 

package com.mail;

import com.sun.mail.imap.IMAPMessage;
import org.junit.Test;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.security.Security;
import java.util.Enumeration;
import java.util.Properties;


public class EmailClient {

    private static final String IMAP = "imap";

    @Test
    public void testReceive() throws Exception {
        receiveQQEmail(System.getProperty("email"), System.getProperty("password"));
    }

    public void receiveQQEmail(String username, String password) throws Exception {
        String host = "imap.qq.com";
        String port = "143";

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

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

        Properties props = System.getProperties();
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
//  props.setProperty("mail.imap.socketFactory.fallback", "false");  
//     props.setProperty("mail.imap.port", port);  
        props.setProperty("mail.imap.socketFactory.port", port);


        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", host);
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.auth.login.disable", "true");
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(false);
        Store store = session.getStore(IMAP);
        store.connect(host, username, password);
        Folder inbox = null;
        try {

            inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_ONLY);
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);
            Message[] messages = inbox.getMessages();
            inbox.fetch(messages, profile);
            System.out.println("收件箱的邮件数:" + messages.length);

            IMAPMessage msg;
            for (Message message : messages) {
                msg = (IMAPMessage) message;
                String from = decodeText(msg.getFrom()[0].toString());
                InternetAddress ia = new InternetAddress(from);
                System.out.println("FROM:" + ia.getPersonal() + ‘(‘ + ia.getAddress() + ‘)‘);
                System.out.println("TITLE:" + msg.getSubject());
                System.out.println("SIZE:" + msg.getSize());
                System.out.println("DATE:" + msg.getSentDate());
                Enumeration headers = msg.getAllHeaders();
                System.out.println("----------------------allHeaders-----------------------------");
                while (headers.hasMoreElements()) {
                    Header header = (Header) headers.nextElement();
                    System.out.println(header.getName() + " ======= " + header.getValue());
                }
                parseMultipart((Multipart) msg.getContent());
            }

        } finally {
            try {
                if (inbox != null) {
                    inbox.close(false);
                }
            } catch (Exception ignored) {
            }
            try {
                store.close();
            } catch (Exception ignored) {
            }
        }
    }

    protected String decodeText(String text) throws UnsupportedEncodingException {
        if (text == null)
            return null;
        if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
        else
            text = new String(text.getBytes("ISO8859_1"));
        return text;
    }


    /**
     * 对复杂邮件的解析
     *
     * @param multipart
     * @throws MessagingException
     * @throws IOException
     */
    public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {
        int count = multipart.getCount();
        System.out.println("couont =  " + count);
        for (int idx = 0; idx < count; idx++) {
            BodyPart bodyPart = multipart.getBodyPart(idx);
            System.out.println(bodyPart.getContentType());
            if (bodyPart.isMimeType("text/plain")) {
                System.out.println("plain................." + bodyPart.getContent());
            } else if (bodyPart.isMimeType("text/html")) {
                System.out.println("html..................." + bodyPart.getContent());
            } else if (bodyPart.isMimeType("multipart/*")) {
                Multipart mpart = (Multipart) bodyPart.getContent();
                parseMultipart(mpart);

            } else if (bodyPart.isMimeType("application/octet-stream")) {
                String disposition = bodyPart.getDisposition();
                System.out.println(disposition);
                if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
                    String fileName = bodyPart.getFileName();
                    InputStream is = bodyPart.getInputStream();
                    copy(is, new FileOutputStream("D:\\" + fileName));
                }
            }
        }
    }

    /**
     * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载
     *
     * @param is
     * @param os
     * @throws IOException
     */
    public static void copy(InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }
        if (os != null)
            os.close();
        is.close();
    }
}
  

http://blog.csdn.net/haigenwong/article/details/7610839

 

利用Javamail接收QQ邮箱和Gmail邮箱(转)

标签:

原文地址:http://www.cnblogs.com/softidea/p/5348683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!