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

求大神解答

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

 

时间: 2024-11-05 18:46:11

利用Javamail接收QQ邮箱和Gmail邮箱(转)的相关文章

Gmail邮箱怎么注册

  Gmail邮箱怎么注册?谷歌邮箱又名Gmail邮箱,谷歌地图.谷歌Chrome浏览器等它们的服务都会用到Gmail邮箱.那么,怎么注册谷歌邮箱呢?须知,国内正常情况下是打不开谷歌Gmail邮箱注册入口而注册. 谷歌邮箱Gmail怎么注册 1.打开谷歌Gmail邮箱注册入口 2.界面都是中文的,相信对于大家来说应该不难.填写姓名(姓.名字),然后输入你喜欢的邮箱名,设置密码.生日.性别,填写验证手机号等. 3."您当前的电子邮件地址"可填一个你最常用的邮箱,比如QQ邮箱.网易邮箱等,

我的qq邮箱和网易邮箱接收不到验证码

问题描述 我的qq邮箱和网易邮箱接收不到验证码 我的网易邮箱跟QQ邮箱均接收不到好多网站的邮箱验证信息,试过各种方法,还是不行.请大神们指教 解决方案 你的邮箱是新申请的吗.要用经常用的邮箱才可以的,可能你的邮箱权限还不够. 解决方案二: 可能是浏览器的因素.换换浏览器试试. qq邮箱和网易邮箱往往在HTML5开始的浏览器里出现这种问题 解决方案三: 有可能是发送验证码的邮箱发送不到,总之原因很多,也可能是你的邮箱设置了转发(在设置里面),你可以看下是不是已经设置了转发. 解决方案四: 你说的好

imap接收qq邮箱未读的邮件

问题描述 C#中怎么用imap协议接收qq邮箱中未读的邮件? 解决方案

用Foxmail把Gmail邮箱变网盘

现在邮件服务商提供的邮箱容量是越来越大,就以Gmail来说吧,完全可以作为网盘来用.不过大多数朋友都是采用Web方式来收发邮件,这样就需要打开浏览器,输入网址,然后再输入邮箱账号密码登录,最后再上传附件.其实利用邮件客户端来收发邮件就更简单直接了,而且还能快速地上传文件到邮箱中.例如利用Foxmail,就可以把Gmail当做网盘,快速上传文件. 第一步.设置邮件客户端为IMAP访问 要想在Foxmail中直接向Gmail邮箱中同步文档,那么需要在Foxmail中设置邮件接收访问方式为IMAP.在

暴力枚举Gmail邮箱地址的新姿势

本文讲的是暴力枚举Gmail邮箱地址的新姿势, 本文将介绍一种比较经典的枚举用户Gmail邮箱地址的新思路,这种思路可以检索成千上万个Gmail邮箱地址. 我偶然发现一个小故障,允许我大量猜测现有的且可能是未知的Google帐户地址. 免责声明:本文介绍的方法可能只是一个没有进行合理限制的接口,没有什么太花哨的姿势,所以如果你正在寻找一些比较6的0day,请绕道.  小故障 https://mail.google.com/mail/gxlu这个网址没有对请求次数做任何限制.另外,我注意到,提供不

gmail邮箱登陆不了怎么办?

  方法一:使用foxmail邮件客户端 1.下载并打开foxmial. 2.点击右上角的设置按钮,选择"账号管理". 3.点击"新建"按钮,然后分别输入你的Gmail账号和密码,最后点击"创建"按钮. 3.等待软件与gmail服务器验证账号信息,验证成功后会显示"设置成功",点击完成就OK了. 4.小编亲自测试,收发Gmail邮件都没有问题.有图有真相,决不复制粘贴! 方法二:使用国内邮箱代收 有些时候不方便安装本地的邮件客

Gmail邮箱如何接受其他邮箱的邮件?

  在浏览器中打开"Gmail",在Gmail中点击右上角的"齿轮",展开列表选择"设置". 点击打开"设置"界面之后,点击顶部选择"账户和导入".在账户和导入中,用户可以看到一个"检查来自其他账户的邮件",在该选项中点击"添加一个您拥有的pop3邮件账户". 点击之后,用户填写需要接收的电子邮件地址.然后点击"下一步". 点击下一步之后,就可以对

Gmail打不开怎么办?Gmail邮箱打不开问题解决方法

Gmail打不开可以使用手机QQ来代收了,具体的设置方法如下所示. 在手机中需要先安装一个"手机QQ邮箱客户端"之后我们打开手机QQ邮箱客户端点击添加账户中选择Gmail 然后会打开一个 Google的授权信息,登陆谷歌账户 细节如下图所示 然后我们申请授权访问Google,如下图所示同,这样就设置好了. 设置好了QQ邮箱接受Gmail邮件与直接打开Gmail是没有区别的哦, 好了你会发现你的手机是可以接受gmail邮箱的邮件的哦,大家有需要的朋友可以去试一下吧.

andoid打包短信发送到gmail邮箱实现代码_Android

andriod短信整合备份发送到gmail邮箱,需要在andoid手机配置好gmail邮箱 github代码 https://github.com/zhwj184/smsbackup 查看效果:  可以把几天的短信打包发送到自己的gmail邮箱,可以定时备份下短信. 主要代码: 复制代码 代码如下: package org.smsautobackup; import java.text.DateFormat; import java.text.SimpleDateFormat; import j