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 ...
随机推荐
- windows10如何安装cpu版本tensorflow
1.获取anaconda https://repo.continuum.io/archive/Anaconda3-2018.12-Windows-x86_64.exe (这个版本内置python3.7 ...
- UOJ #164 【清华集训2015】 V
题目链接:V 这道题由于是单点询问,所以异常好写. 注意到每种修改操作都可以用一个标记\((a,b)\)表示.标记\((a,b)\)的意义就是\(x= \max\{x+a,b\}\) 同时这种标记也是 ...
- python 计算字典value值的和
my_dict = {,,} print(sum(my_dict.values()))
- data.table 中的动态作用域
data.table 中最常用的语法就是 data[i, j, by],其中 i.j 和 by 都是在动态作用域中被计算的.换句话说,我们不仅可以直接使用列,也可以提前定义诸如 .N ..I 和 .S ...
- gif&png&jpg&webp
几种图片格式的区别和联系 1.http://www.tuicool.com/articles/AbUvI3A
- git 重写历史
重写最后一次提交的commit git commit --amend 修改多个历史 git rebase -i HEAD~3 命令执行后结果如下: pick f7f3f6d changed my na ...
- HDU 2577 分情况多维DP
How to Type Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total ...
- PHP:第五章——字符串的分割与替换
<?php header("Content-Type:text/html;charset=utf-8"); //字符串的截取与分割 //1.字符串截取类函数 //1)trim ...
- C#读写配置文件Config
应用程序配置文件是标准的XML文件,XML标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序.配置文件的根节点是configuration.我们经 ...
- SGU 139. Help Needed! 逆序数,奇偶性,分析 难度:0
139. Help Needed! time limit per test: 0.25 sec. memory limit per test: 4096 KB Little Johnny likes ...