Javamail使用代码整理
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使用代码整理的更多相关文章
- Smtp邮件发送系统公用代码整理—总结
1.前言 a.在软件开发中,我们经常能够遇到给用户或者客户推送邮件,推送邮件也分为很多方式,比如:推送一句话,推送一个网页等等.那么在系统开发中我们一般在什么情况下会使用邮件发送呢?下面我简单总结了一 ...
- Chrome应用技巧之代码整理。
我们有时候在看别人站点代码时往往是经过压缩的,代码都在一行上了,调试非常是困难,今天给大家介绍一种基本Chrome浏览器的代码整理方法.请看图:
- NSIS常用代码整理
原文 NSIS常用代码整理 这是一些常用的NSIS代码,少轻狂特意整理出来,方便大家随时查看使用.不定期更新哦~~~ 1 ;获取操作系统盘符 2 ReadEnvStr $R0 SYSTEMDRIVE ...
- material design 的android开源代码整理
material design 的android开源代码整理 1 android (material design 效果的代码库) 地址请点击:MaterialDesignLibrary 效果: 2 ...
- HTTP请求代码整理
HTTP请求代码整理 类别 代码 注释 1xx – 信息提示 100 继续 101 切换协议 2xx - 成功 200 确定.客户端请求已成功 201 已创建 202 已接受 203 非权威性信息 2 ...
- SQL代码整理
--SQL代码整理: create database mingzi--创建数据库go--连接符(可省略)create table biao--创建表( lieming1 int not null,-- ...
- IOS常用代码整理
常用代码整理: 12.判断邮箱格式是否正确的代码: //利用正则表达式验证 -(BOOL)isValidateEmail:(NSString *)email { NSString *emailRege ...
- html Css PC 移动端 公用部分样式代码整理
css常用公用部分样式代码整理: body, html, div, blockquote, img, label, p, h1, h2, h3, h4, h5, h6, pre, ul, ol, li ...
- Photon Server 实现注册与登录(二) --- 服务端代码整理
一.有的代码前端和后端都会用到.比如一些请求的Code.使用需要新建项目存放公共代码. 新建项目Common存放公共代码: EventCode :存放服务端自动发送信息给客户端的code Operat ...
随机推荐
- Python3基础 print %d 输出整数
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- CodeForces 450B Jzzhu and Sequences(矩阵快速幂)题解
思路: 之前那篇完全没想清楚,给删了,下午一上班突然想明白了. 讲一下这道题的大概思路,应该就明白矩阵快速幂是怎么回事了. 我们首先可以推导出 学过矩阵的都应该看得懂,我们把它简写成T*A(n-1)= ...
- python assert 断言详细用法格式
使用assert断言是学习python一个非常好的习惯,python assert 断言句语格式及用法很简单.在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行最崩溃,不如在出现错误条件 ...
- mysql explain extended 查看 执行计划
本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 本文以转移至本人的个人博客,请多多关注! 1. explain 可以查看 ...
- 第10章 Pry, 强大的pry-rails和相关的几个好用gem
https://asciinema.org/a/0KtCL9HB1bP08wNHLfIeOMa8K 本章讲了如何定位❌,和排除bug. Pry (5000
- L178 smart meter watchdog
There is "no realistic prospect" of the government meeting its own deadline to install sma ...
- URL 生成带文字二维码
<!DOCTYPE html> <html> <head> <title></title> <meta charset="u ...
- 使用 某款基于Socks5协议的代理软件 一段时间后 被封锁掉IP的一些技术思考
由于关键词比较敏感为了不被删除帖子所以文中某软件(上图所示软件)不用全称表示. 去年9月末在 在某国外网站 上弄了一个vpn,在上面安装了某软件,使用起来还是蛮不错的,平时查查英文论文,看看美剧还是比 ...
- BusyBox ifup udhcpc后台运行
/********************************************************************** * BusyBox ifup udhcpc后台运行 * ...
- 20155223 2016-2017-2 《Java程序设计》第8周学习总结
20155223 2016-2017-2 <Java程序设计>第8周学习总结 教材学习内容总结 第14章 Channel是Java NIO用来衔接数据节点的功能,可定义缓冲区容量.标记内容 ...