package com.hengrun.mail;

import java.io.*;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties; import javax.mail.*;
import javax.mail.internet.*; import sun.misc.BASE64Decoder; public class MailReceive { public MailReceive(){ } private Folder inbox = null; private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //获取所有邮件
public String getMails(int page,String username,String pass){
int pageNum = 10;
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", "imap.exmail.qq.com");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.socketFactory.port", "993"); Session session = Session.getDefaultInstance(props,null); URLName urln = new URLName("imap","imap.exmail.qq.com",993,null,
username, pass); Store store = null;
String msg = ""; try {
store = session.getStore(urln);
store.connect();
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); //计算页数
int all = inbox.getMessageCount();
int pages = all/pageNum;
if(all%pageNum>0){
pages++;
}
int begin = all-((page-1)*pageNum); for (int i = begin-1; i > (begin-pageNum)&&i>=0; i--) {
//邮件发送者
String from = decodeText(messages[i].getFrom()[0].toString());
msg += messages[i].getMessageNumber()+"&";
InternetAddress ia = new InternetAddress(from);
msg+=ia.getPersonal()+"&";
msg+=ia.getAddress()+"&";
//邮件标题
msg+=messages[i].getSubject()+"&";
//邮件大小
msg+=messages[i].getSize()+"&";
//邮件发送时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
msg+=format.format(messages[i].getSentDate())+";"; //判断是否由附件
// if(messages[i].isMimeType("multipart/*")){
// Multipart multipart = (Multipart)messages[i].getContent();
// int bodyCounts = multipart.getCount();
// for(int j = 0; j < bodyCounts; j++) {
// BodyPart bodypart = multipart.getBodyPart(j);
// if(bodypart.getFileName() != null){
// String filename = bodypart.getFileName();
// if(filename.startsWith("=?")){
// filename = MimeUtility.decodeText(filename);
// }
// msg+=filename+"<br/>";
// }
// }
// }
}
} catch (MessagingException | IOException e) {
// TODO Auto-generated catch block
msg = "0";
} finally{
try {
inbox.close(false);
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}finally{
return msg;
}
}
} protected static 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;
} //附件下载到服务器
public void getAtth(int msgnum,int bodynum,String filename,String mailpath) throws MessagingException, IOException{
Message message = inbox.getMessage(msgnum);
Multipart multipart = (Multipart)message.getContent();
BodyPart bodypart = multipart.getBodyPart(bodynum);
InputStream input = bodypart.getInputStream();
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close(); File file = new File("D:\\App\\MailFile\\"+mailpath);
if(!file.isDirectory()&&!file.exists()){
file.mkdir();
} FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();
} //获得单个邮件信息
public String getMail(int id,final String username,final String pass) throws MessagingException, IOException{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", "imap.exmail.qq.com");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.socketFactory.port", "993"); Session session = Session.getDefaultInstance(props,null); URLName urln = new URLName("imap","imap.exmail.qq.com",993,null,
username, pass); Store store = session.getStore(urln);
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE); Message message = inbox.getMessage(id); String msg = ""; msg+=message.getMessageNumber()+"&#@";
msg+=message.getSubject()+"&#@";
msg+=new InternetAddress(message.getFrom()[0].toString()).getAddress()+"&#@";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
msg+=format.format(message.getSentDate())+"&#@"; //判断是否由附件
if(message.isMimeType("multipart/*")){
Multipart multipart = (Multipart)message.getContent();
int bodyCounts = multipart.getCount();
for(int j = 0; j < bodyCounts; j++) {
BodyPart bodypart = multipart.getBodyPart(j);
if(bodypart.getContent()!=null){
msg+=bodypart.getContent()+"&#@";
}
}
}else{
msg+=message.getContent().toString()+"&#@";
} if(message.isMimeType("multipart/*")){
Multipart multipart = (Multipart)message.getContent();
int bodyCounts = multipart.getCount();
for(int j = 0; j < bodyCounts; j++) {
BodyPart bodypart = multipart.getBodyPart(j);
if(bodypart.getFileName() != null){
String filename = bodypart.getFileName();
if(filename.startsWith("=?")){
filename = MimeUtility.decodeText(filename);
}
msg+=filename+";";
}
}
} store.close();
return msg;
} //发送邮件
public String sendmail(final String username,final String pass,String from,String to,String subject,String content){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, pass);
}}); Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to,false));
msg.setSubject(subject);
msg.setText(content);
msg.setSentDate(new Date());
Transport.send(msg);
return "1";
} catch (MessagingException e) {
// TODO Auto-generated catch block
return e.getMessage();
}finally{ }
} //Base64
public static String decryptBASE64(String key) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bt = decoder.decodeBuffer(key);
return new String(bt,"GBK");
} //新邮件提醒
public int MailMsg(String username,String pass){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", "imap.exmail.qq.com");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.socketFactory.port", "993"); Session session = Session.getDefaultInstance(props,null); URLName urln = new URLName("imap","imap.exmail.qq.com",993,null,
username, pass); Store store = null;
int num = 0; try {
store = session.getStore(urln);
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE); num = inbox.getMessageCount();
} catch (MessagingException e) {
// TODO Auto-generated catch block
num = 0;
}finally{
try {
inbox.close(false);
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
}finally{
return num;
}
}
}
}
package com.hengrun.mail;

import java.io.IOException;
import java.io.PrintWriter; import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class MailMsg
*/
public class MailMsg extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public MailMsg() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub request.setCharacterEncoding("gbk"); String username = request.getParameter("username");
String pass = request.getParameter("pass"); MailReceive mr = new MailReceive(); int num = 0;
PrintWriter out = null; num = mr.MailMsg(username, pass); response.setCharacterEncoding("gbk");
response.setContentType("text/html; charset=gbk");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache"); out = response.getWriter(); out.println(num); out.flush();
out.close();
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub //设置request编码方式
request.setCharacterEncoding("gbk"); String username = request.getParameter("username");
String pass = request.getParameter("pass"); MailReceive mr = new MailReceive(); int num = 0;
PrintWriter out = null; num = mr.MailMsg(username, pass); response.setCharacterEncoding("gbk");
response.setContentType("text/html; charset=gbk");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache"); out = response.getWriter(); out.println(num); out.flush();
out.close();
} }

带附件发送邮件

//发送邮件
public String sendmail(final String username,final String pass,String from,String to,String subject,String content, String atthid) throws SQLException, ClassNotFoundException, UnsupportedEncodingException{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = System.getProperties();
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, pass);
}}); Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to,false));
msg.setSubject(subject);
//msg.setContent(content, "text/html;charset=gb2312");
msg.setSentDate(new Date()); Multipart mt = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(content, "text/html;charset=gb2312");
mt.addBodyPart(mbp);
if(atthid!=null&&!atthid.equals("")){
List<Map> list = Utility.GetFiles(atthid); if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
MimeBodyPart fbp = new MimeBodyPart();
FileDataSource fds = new FileDataSource(((HashMap)list.get(i)).get("AnnexDirection").toString());
fbp.setDataHandler(new DataHandler(fds));
fbp.setFileName(MimeUtility.encodeText(((HashMap)list.get(i)).get("AnnexName").toString())); mt.addBodyPart(fbp);
}
}
} msg.setContent(mt); Transport.send(msg);
return "1";
} catch (MessagingException e) {
// TODO Auto-generated catch block
return e.getMessage();
}finally{ }
}

最新整理收邮件代码,通过UID收取新邮件及附近,已测试成功

private IMAPFolder inbox = null;

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

    //获取新邮件
public String getMails(String username,String pass,String server,String port,Boolean ssl){
String num = "";
Properties props = System.getProperties();
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", server);
props.setProperty("mail.imap.port", port);
props.setProperty("mail.imap.socketFactory.port", port);
props.setProperty("mail.imap.auth.login.disable", "true");
props.setProperty("mail.imap.auth.plain.disable", "true"); if(ssl){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
} Session session = Session.getDefaultInstance(props,null); URLName urln = new URLName("imap",server,Integer.parseInt(port),null,
username, pass); Store store = null;
String ids = ""; try {
store = session.getStore(urln);
store.connect();
inbox = (IMAPFolder)store.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
//FetchProfile profile = new FetchProfile();
//profile.add(FetchProfile.Item.ENVELOPE);
//Message[] messages = inbox.getMessages();
//inbox.fetch(messages, profile);
Message[] msgs = inbox.getMessages();
for(int i=0;i<msgs.length;i++){
ids+="insert into #tmp (UID) values ("+inbox.getUID(msgs[i])+");";
}
List<Integer> list = Utility.GetUnreads(username, ids);
int res = SaveMail(list, username); if(res<0){
num="";
}else{
num = "ok";
} } catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
num = "";
} finally{
try {
inbox.close(false);
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}finally{
return num;
}
}
} public int SaveMail(List<Integer> list,String username){
int num = 0;
try{
for(int i=0;i<list.size();i++){ Message msg = inbox.getMessageByUID(list.get(i));           Address[] tos = msg.getRecipients(RecipientType.TO);
                String to = "";
                for(int j=0;j<tos.length;j++){
                    to+=getAdds(decodeText(tos[j].toString()));
                }
          
Address[] froms = msg.getFrom();
String from = "";
for(int j=0;j<froms.length;j++){
from += getAdds(decodeText(froms[j].toString()))+";";
} Address[] ccs = msg.getRecipients(RecipientType.CC);
String cc = "";
for(int j=0;ccs!=null&&j<ccs.length;j++){
cc += getAdds(decodeText(ccs[j].toString()))+";";
} Address[] bccs = msg.getRecipients(RecipientType.BCC);
String bcc = "";
for(int j=0;bccs!=null&&j<bccs.length;j++){
bcc += getAdds(decodeText(bccs[j].toString()))+";";
} String content = "";
String atth = "";
if(msg.isMimeType("multipart/*")){
Multipart multipart = (Multipart)msg.getContent();
int bodyCounts = multipart.getCount();
for(int j = 0; j < bodyCounts; j++) {
BodyPart bodypart = multipart.getBodyPart(j);
if(bodypart.getFileName() != null){
String filename = bodypart.getFileName();
if(filename.startsWith("=?")){
filename = MimeUtility.decodeText(filename);
}
String path = SaveFile(bodypart.getInputStream(), filename);
atth+=path+";";
}
if(bodypart.isMimeType("text/html")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("text/plain")){
content = bodypart.getContent().toString();
}
}
}else{
content = msg.getContent().toString();
} int iscc = 0; if(cc.contains(username)){
iscc = 1;
} int isbcc = 0; if(bcc.contains(username)){
isbcc = 1;
} int has = 0; if(!atth.equals("")){
has = 1;
}

          int isread = 0;
                Flag[] flags = msg.getFlags().getSystemFlags();
                for(int j=0;j<flags.length;j++){
                    if(flags[j] == Flag.SEEN){
                        isread = 1;
                    }
                }
Utility.SaveUnread(username, list.get(i), msg.getSentDate(), from, msg.getSubject(), content, cc, bcc, atth,iscc,isbcc,has,to,isread);
}
num=1;
}catch(Exception e){
e.printStackTrace();
num=-1;
}finally{
return num;
}
} public String SaveFile(InputStream stream,String filename){
String path = "";
try{
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String d = sdf.format(date);
File file = new File("D:\\server\\Test\\soaTest\\files\\"+d);
if(!file.exists()){
file.mkdirs();
}
FileOutputStream out = new FileOutputStream("D:\\server\\Test\\soaTest\\files\\"+d+"\\"+filename);
int data;
while((data = stream.read()) != -1) {
out.write(data);
}
stream.close();
out.close();
path = "D:\\server\\Test\\soaTest\\files\\"+d+"\\"+filename;
}catch(Exception ex){
ex.printStackTrace();
}finally{
return path;
}
}

这里要注意,当你先使用一个需要SSL的邮箱接受之后,再使用一个不需要SSL的邮箱接受就会报错,错误提示你无法获取SSL信息。

这时,你需要这样修改

Properties props = System.getProperties();
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.host", server);
props.setProperty("mail.imap.port", port); if(ssl){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
// 这三句从if外面移进来
props.setProperty("mail.imap.socketFactory.port", port);
props.setProperty("mail.imap.auth.login.disable", "true");
props.setProperty("mail.imap.auth.plain.disable", "true");
}

有的时候会收不到邮件正文,因为有多层的Mult。

public String takeMult(Object par,int i,String username) throws Exception{
String content = "";
Multipart multipart = (Multipart)par;
int bodyCounts = multipart.getCount();
for(int j = 0; j < bodyCounts; j++) {
BodyPart bodypart = multipart.getBodyPart(j);
if(bodypart.getFileName() != null){
String filename = bodypart.getFileName();
if(filename.startsWith("=?")){
filename = MimeUtility.decodeText(filename);
}
if(Utility.IsSaved(i,username)==0){
String path = SaveFile(bodypart.getInputStream(), filename);
//atth+=path+";";
}
}
if(bodypart.isMimeType("text/html")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("text/plain")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("message/rfc822")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("multipart/*")){
content = this.takeMult(bodypart.getContent(), i, username);
}
}
return content;
}
if(bodypart.isMimeType("text/html")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("text/plain")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("message/rfc822")){
content = bodypart.getContent().toString();
}
if(bodypart.isMimeType("multipart/*")){
content = this.takeMult(bodypart.getContent(), i, username);
}

Javamail使用代码整理的更多相关文章

  1. Smtp邮件发送系统公用代码整理—总结

    1.前言 a.在软件开发中,我们经常能够遇到给用户或者客户推送邮件,推送邮件也分为很多方式,比如:推送一句话,推送一个网页等等.那么在系统开发中我们一般在什么情况下会使用邮件发送呢?下面我简单总结了一 ...

  2. Chrome应用技巧之代码整理。

    我们有时候在看别人站点代码时往往是经过压缩的,代码都在一行上了,调试非常是困难,今天给大家介绍一种基本Chrome浏览器的代码整理方法.请看图:

  3. NSIS常用代码整理

    原文 NSIS常用代码整理 这是一些常用的NSIS代码,少轻狂特意整理出来,方便大家随时查看使用.不定期更新哦~~~ 1 ;获取操作系统盘符 2 ReadEnvStr $R0 SYSTEMDRIVE ...

  4. material design 的android开源代码整理

    material design 的android开源代码整理 1 android (material design 效果的代码库) 地址请点击:MaterialDesignLibrary 效果: 2 ...

  5. HTTP请求代码整理

    HTTP请求代码整理 类别 代码 注释 1xx – 信息提示 100 继续 101 切换协议 2xx - 成功 200 确定.客户端请求已成功 201 已创建 202 已接受 203 非权威性信息 2 ...

  6. SQL代码整理

    --SQL代码整理: create database mingzi--创建数据库go--连接符(可省略)create table biao--创建表( lieming1 int not null,-- ...

  7. IOS常用代码整理

    常用代码整理: 12.判断邮箱格式是否正确的代码: //利用正则表达式验证 -(BOOL)isValidateEmail:(NSString *)email { NSString *emailRege ...

  8. html Css PC 移动端 公用部分样式代码整理

    css常用公用部分样式代码整理: body, html, div, blockquote, img, label, p, h1, h2, h3, h4, h5, h6, pre, ul, ol, li ...

  9. Photon Server 实现注册与登录(二) --- 服务端代码整理

    一.有的代码前端和后端都会用到.比如一些请求的Code.使用需要新建项目存放公共代码. 新建项目Common存放公共代码: EventCode :存放服务端自动发送信息给客户端的code Operat ...

随机推荐

  1. 【日志过滤】Nginx日志过滤 使用ngx_log_if不记录特定日志

    ngx_log_if是Nginx的一个第三方模块.它在Github上的描述是这样介绍的:ngx_log_if是一个独立的模块,允许您控制不要写的访问日志,类似于Apache的"CustomL ...

  2. [SpringBoot] - 配置文件的多种形式及优先级

              学习两个注解: @PropertySource   @ImportResource  ↓   @ConfigurationProperties  与 @Bean 结合为属性赋值 与 ...

  3. Recover Binary Search Tree,恢复二叉排序树

    问题描述:题意就是二叉树中有两个节点交换了,恢复结构. Two elements of a binary search tree (BST) are swapped by mistake. Recov ...

  4. append 注意事项

    >>> t1 = [, ] >>> t2 = t1.append() >>> t1 [, , ] >>> t2 None

  5. myeclipse6.5使用tomcat7报java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory错

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFact ...

  6. Django rest framework源码分析(一) 认证

    一.基础 最近正好有机会去写一些可视化的东西,就想着前后端分离,想使用django rest framework写一些,顺便复习一下django rest framework的知识,只是顺便哦,好吧. ...

  7. <NET CLR via c# 第4版>笔记 第6章 类型和成员基础

    6.1 类型的各种成员 6.2 类型的可见性 public 全部可见 internal 程序集内可见(如忽略,默认为internal) 可通过设定友元程序集,允许其它程序集访问该程序集中的所有inte ...

  8. L198

    One of the most common birth defects throughout the world is a cleft lip. Babies born with a cleft l ...

  9. js设计模式整理

    单例模式 恶汉式单例 实例化时 懒汉式单例 调用时构造函数模式 1.实现一 function Car(model, year, miles) { this.model = model; this.ye ...

  10. 分析器错误信息: 服务器标记不能包含 <% ... %> 构造

    我的程序如下:<form runat="server"><TABLE><TR><TD>用户名:</TD><TD&g ...