利用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
利用Javamail接收QQ邮箱和Gmail邮箱(转)的更多相关文章
- SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件
在Spring中提供了非常好用的 JavaMailSender接口实现邮件发送,在SpringBoot的Starter模块中也为此提供了自动化配置. 项目源码已托管在Gitee-SpringBoot_ ...
- 在foxmail和outlook中设置QQ邮箱、gmail邮箱、新浪邮箱、微软邮箱、网易邮箱等的方法
怎么用邮件客户端如outlook和foxmail来设置各种邮箱 很多人平时都是在网页上面收发邮件,这个很简单,不用其他的设置,不过在客户端上设置收发邮件还是很不错的,今天就来讲讲各种邮箱在outloo ...
- C#发送Email邮件(实例:QQ邮箱和Gmail邮箱)
下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用: using System.Net.Mail; using System.Text; using System.Net; ...
- [转]C#发送Email邮件 (实例:QQ邮箱和Gmail邮箱)
下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用:using System.Net.Mail;using System.Text;using System.Net; 程序 ...
- SpringBoot2.x整合JavaMail以qq邮箱发送邮件
本文参考spring官网email接口文档所写. spring-email官方网址:https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-fr ...
- 用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(下)
一.我的需求 我希望做成具有以下功能的软件:1. 间隔一段时间登录我的邮箱查看是否有未读邮件 如果不断的运行查看是否有新邮件确实没多大必要. 另外如果这个客户端登录我的邮箱,那么我可能就不能用浏览器登 ...
- 用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(中)
这篇博客,主要讲解用Python实现邮箱服务的几个需要学习的模块:E-mail Compotion and Decoding(邮件生成和解析).SMTP.POP.IMAP 如上篇博客所讲,我学习过程参 ...
- java邮件发送 qq与163邮箱互发和qq和163邮箱发送其他邮箱实例
研究了近一天的时间,通过查阅相关资料,终于对java发送邮件的机制,原理有了一点点的理解,希望能够帮到大家! 1.首先要向你的项目里导入1个jar包:mail-1.4.4.jar即可(实现qq和163 ...
- 使用Gmail邮箱
由于国内不能直接访问google,所以其相关产品也不能直接使用.因为Gmail简洁,使用方便,国际上用的人很多.最近发现网易邮箱大师可以直接访问Gmail,所以将方法介绍给大家,如果大家只有访问Gma ...
随机推荐
- tomcat7 启动报错(转)
不加载任何自己的项目启动即报错: 严重: Error deploying web application directory D:\tomcat7.0.30\webapps\docs java.l ...
- 11661 - Burger Time?
Burger Time? Everybody knows that along the more important highways there are countless fast food ...
- Spark SQL Catalyst源代码分析之TreeNode Library
/** Spark SQL源代码分析系列文章*/ 前几篇文章介绍了Spark SQL的Catalyst的核心执行流程.SqlParser,和Analyzer,本来打算直接写Optimizer的,可是发 ...
- win2003的IIS無法使用,又一次安裝提示找不到iisadmin.mfl文件
我的系統是win2003 繁體版 sp2,現在iis無法使用,我同事的也是,也不知道是不是跟在網域中有關係,因為我用虛擬機的繁體系統win2003 R2版iis能够正常使用,不過曾经那台電腦也是在網域 ...
- POJ 2112 Optimal Milking【网络流+二分+最短路】
求使所有牛都可以被挤牛奶的条件下牛走的最长距离. Floyd求出两两节点之间的最短路,然后二分距离. 构图: 将每一个milking machine与源点连接,边权为最大值m,每个cow与汇点连接,边 ...
- 从源代码角度分析ViewStub 疑问与原理
一.提出疑问 ViewStub比較简单.之前文章都提及到<Android 性能优化 三 布局优化ViewStub标签的使用>.可是在使用过程中有一个疑惑,究竟是ViewStub上设 ...
- Common Lisp Style Guide - Ariel Networks Labs
Common Lisp Style Guide - Ariel Networks Labs Common Lisp Style Guide
- Android实战技巧: ListView之ContextMenu无法弹出
问题 Activity中使用了ListView作为布局.当每一列表项中含有默认能获取焦点的子View时有可能会对ListView的某些事件有影响: 1. OnItemClick 2. OnItemLo ...
- Android中网络流量控制(防火墙)——Iptables
Iptables简单介绍 iptables是与最新的 2.6.x 版本号 Linux 内核集成的 IP 信息包过滤系统. 假设 Linux 系统连接到因特网或 LAN.server或连接 LAN 和因 ...
- 表达式树动态拼接lambda
动态拼接lambda表达式树 前言 最近在优化同事写的代码(我们的框架用的是dapperLambda),其中有一个这样很普通的场景——界面上提供了一些查询条件框供用户来进行过滤数据.由于dappe ...