package mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class
MailClient {
protected Session session;
protected Store store;
private String sendHost="localhost";
private String receiveHost="localhost";
private String sendProtocol="smtp";
private String receiveProtocol="imap";
private String username="admin";
private String password="1234";
private String fromAddr="
[email protected]";
private String toAddr="
[email protected]";
public void init() throws Exception{
Properties props=new Properties();
props.put("mail.transport.protocol",sendProtocol);
props.put("mail.store.protocol",receiveProtocol);
props.put("mail.smtp.protocol","com.sun.mail.smtp.SMTPTransport");
props.put("mail.imap.protocol","com.sun.mail.IMAPStore");
props.put("mail.smtp.host",sendHost);
//创建session对象
session=Session.getDefaultInstance(props);
session.setDebug(true); //输出跟踪日记
//创建Store对象
store=session.getStore(receiveProtocol);
//连接到收邮件服务器
store.connect(receiveHost,username,password);
}
public void close()throws Exception{
store.close();
}
public void sendMessage(String fromAddr,String toAddr) throws Exception{
//创建一个邮件
Message msg=createSimpleMessage(fromAddr,toAddr);
//发送邮件
Transport.send(msg);
}
public Message createSimpleMessage(String fromAddr, String toAddr) throws Exception {
// TODO Auto-generated method stub
Message msg=new MimeMessage(session);
InternetAddress[] toAddrs=InternetAddress.parse(toAddr,false);
msg.setRecipients(Message.RecipientType.TO,toAddrs);
msg.setSentDate(new Date());
msg.setSubject("hello");
msg.setFrom(new InternetAddress(fromAddr));
msg.setText("how are you");
return msg;
}
public void receiveMessage() throws Exception{
browseMessageFromFolder("inbox");
}
public void browseMessageFromFolder(String folderName) throws Exception {
// TODO Auto-generated method stub
Folder folder=store.getFolder(folderName);
if(folder==null){
throw new Exception("folderName"+"邮件夹不存在");
}
browerMessageFromFolder(folder);
}
public void browerMessageFromFolder(Folder folder) throws Exception {
// TODO Auto-generated method stub
folder.open(Folder.READ_ONLY);
System.out.println("you have"+folder.getMessageCount()+"message in inbox");
System.out.println("you have"+folder.getUnreadMessageCount()+"unread message in inbox");
//读邮件
Message[] message=folder.getMessages();
System.out.println("测试-----"+message.length);
for(int i=1;i<=message.length;i++){
System.out.println("----第"+i+"封邮件----");
//打印邮件信息
folder.getMessage(i).writeTo(System.out);
System.out.println();
}
folder.close(false);
//关闭邮件夹,但不删除邮件夹中标识为"DELETE"的邮件
}
public static void main(String[] args) throws Exception{
MailClient client=new MailClient();
client.init();
client.sendMessage(client.fromAddr,client.toAddr);
client.receiveMessage();
client.close();
}
}
===============================================================================
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class
MailClientFolder extends MailClient {
/**
* @param args
* @throws Exception
*/
//列出所有的邮件夹
public void listFolders() throws Exception{
Folder rootFolder=store.getDefaultFolder();
Folder[] folders=rootFolder.list();
for(int i=0;i<folders.length;i++){
System.out.println(folders[i]+"邮件夹:"+folders[i].getMessageCount()+"封邮件");
}
}
//删除邮件夹
public void deleteFolder(String folderName) throws Exception{
if(folderName.equalsIgnoreCase("index")||
folderName.equalsIgnoreCase("trash")||
folderName.equalsIgnoreCase("draft")||
folderName.equalsIgnoreCase("sendbox")){
throw new Exception("不允许删除保留文件夹");
}
Folder folder=store.getFolder(folderName);
if(!folder.exists()){
throw new Exception(folderName+"邮件夹不存在");
}
if(folder.isOpen()){
folder.close(true);
}
folder.delete(true);
}
//创建邮件夹
public void createFolder(String folderName) throws Exception{
if(folderName==null||folderName.equals("")){
throw new Exception("必须指定邮件夹的名字");
}
Folder folder=store.getFolder(folderName);
if(folder.exists()){
throw new Exception("邮件夹已经存在了");
}
folder.create(Folder.HOLDS_MESSAGES);
}
//修改邮件夹的名字
public void renameFolder(String fromName,String toName) throws Exception{
if(toName==null||toName.equals("")){
throw new Exception("必须制定邮件夹新名字");
}
if(fromName.equalsIgnoreCase("index")||
fromName.equalsIgnoreCase("trash")||
fromName.equalsIgnoreCase("draft")||
fromName.equalsIgnoreCase("sendbox")||
toName.equalsIgnoreCase("index")||
toName.equalsIgnoreCase("trash")||
toName.equalsIgnoreCase("draft")||
toName.equalsIgnoreCase("sendbox")){
throw new Exception("不允许修改保留的邮件夹的名字");
}
Folder folderFrom=store.getFolder(fromName);
Folder folderTo=store.getFolder(toName);
if(!folderFrom.exists()){
throw new Exception(folderFrom+" 该邮件夹不存在");
}
if(folderFrom.isOpen()){
folderFrom.close(true);
}
folderFrom.renameTo(folderTo);
}
/*
* javamail 没有直接提供删除邮件方法,如果需要删除,先把Message的Flags.Flag.DELETED设为true,
* 然后调用邮件夹Folder的expunge(),该方法删除邮件夹中所有Flags.Flag.DELETED标识为true的邮件
*
* **/
public void deleteMessage(int[] arrayOpt,String folderName) throws Exception{
Folder folder=store.getFolder(folderName);
if(!folder.exists()){
throw new Exception(folderName+" 该邮件夹不存在");
}
if(!folder.isOpen()){
folder.open(Folder.READ_WRITE);
}
for(int i=0;i<arrayOpt.length;i++){
if(arrayOpt[i]==0){
continue;
}
Message msg=folder.getMessage(i+1);
if(!folder.getName().equals("trash")){
Folder Trash=store.getFolder("trash");
folder.copyMessages(new Message[]{msg}, Trash);
msg.setFlag(Flags.Flag.DELETED, true);
}else{
msg.setFlag(Flags.Flag.DELETED, true);
}
}
folder.expunge();
}
//发送邮件
public void sendMessage(Message msg) throws Exception{
Transport.send(msg);
//把邮件保存到sendbox邮件夹
Folder folder=store.getFolder("sendbox");
if(!folder.isOpen()){
folder.open(Folder.READ_WRITE);
folder.appendMessages(new Message[]{msg});
}
}
//创建保留的邮件夹
public void createReservedFolders() throws Exception{
String[] folderNames={"trash","draft","sendbox"};
for(int i=0;i<folderNames.length;i++){
Folder folder=store.getFolder(folderNames[i]);
if(!folder.exists()){
folder.create(Folder.HOLDS_MESSAGES);
}
}
}
//把邮件保存到draft邮件夹
public void saveMessage(Message msg) throws Exception{
saveMessage("draft",msg);
}
//把邮件保存到指定文件夹
public void saveMessage(String folderName,Message msg) throws Exception{
Folder folder=store.getFolder(folderName);
if(!folder.exists()){
throw new Exception("folderName"+" 邮件夹不存在");
}
if(!folder.isOpen()){
folder.open(Folder.READ_WRITE);
}
folder.appendMessages(new Message[]{msg});
}
//把邮件从一个邮件夹移动到另一个邮件夹
public void moveMessage(String fromFolderName,String toFolderName,Message msg) throws Exception{
Folder folderFrom=store.getFolder(fromFolderName);
Folder folderTo=store.getFolder(toFolderName);
if(!folderFrom.exists()){
throw new Exception(fromFolderName+" 邮件夹不存在");
}
if(!folderTo.exists()){
throw new Exception(toFolderName+" 邮件夹不存在");
}
folderFrom.copyMessages(new Message[]{msg}, folderTo);
msg.setFlag(Flags.Flag.DELETED,true);
folderFrom.expunge();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MailClientFolder client=new MailClientFolder();
client.init();
client.createReservedFolders();//创建trash,sendbox和draft邮件夹
client.createFolder("myfolder");//创建myfolder邮件夹
client.renameFolder("myfolder", "qinya");
Message msg=client.createSimpleMessage("
[email protected]", "
[email protected]");
client.sendMessage(msg);
client.saveMessage("qinya", msg);
// client.deleteMessage(new int[]{1}, "qinya");
client.listFolders();
// client.deleteFolder("qinya");
client.close();
}
}
====================================================================================
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class
MailClientForCitiz extends MailClient{
private Authenticator ma;
protected Store store;
protected Session session;
private String sendHost="localhost";
private String receiveHost="localhost";
private String sendProtocol="smtp";
private String receiveProtocol="pop3";
private String username="admin";
private String password="1234";
private String fromAddr="
[email protected]";
private String toAddr="
[email protected]";
public void init() throws Exception{
System.out.println("开始运行");
Properties props=new Properties();
props.put("mail.transport.protocol",sendProtocol);
props.put("mail.store.protocol",receiveProtocol);
props.put("mail.smtp.protocol","com.sun.mail.smtp.SMTPTransport");
props.put("mail.imap.protocol","com.sun.mail.IMAPStore");
props.put("mail.smtp.host",sendHost);
props.put("mail.stmp.auth","true");
System.out.println("第一步");
ma=new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
System.out.println("第2步");
System.out.println("call getPasswordAuthenticatopn");
return new PasswordAuthentication(username,password);
}
};
System.out.println("第3步");
session=Session.getDefaultInstance(props,ma);
//创建store对象
System.out.println("创建store对象");
store=session.getStore(receiveProtocol);
store.connect(receiveHost, username, password);
}
public void close()throws Exception{
store.close();
}
public static void main(String[] args) throws Exception{
MailClientForCitiz client=new MailClientForCitiz();
client.init();
client.sendMessage(client.fromAddr,client.toAddr);
System.out.println("邮件发送完毕");
client.receiveMessage();
}
public void receiveMessage() throws Exception{
System.out.println("开始接受邮件");
browseMessageFromFolder("inbox");
}
public void sendMessage(String fromAddr,String toAddr) throws Exception{
System.out.println("创建一个邮件");
//创建一个邮件
Message msg=createSimpleMessage(fromAddr,toAddr);
//发送邮件
Transport.send(msg);
}
public Message createSimpleMessage(String fromAddr, String toAddr) throws Exception {
// TODO Auto-generated method stub
Message msg=new MimeMessage(session);
System.out.println("创建一个邮件--1");
InternetAddress[] toAddrs=InternetAddress.parse(toAddr,false);
System.out.println("创建一个邮件--2");
msg.setRecipients(Message.RecipientType.TO,toAddrs);
System.out.println("创建一个邮件--3");
msg.setSentDate(new Date());
msg.setSubject("hello");
System.out.println("创建一个邮件--4");
msg.setFrom(new InternetAddress(fromAddr));
msg.setText("how are you");
return msg;
}
public void browseMessageFromFolder(String folderName) throws Exception {
// TODO Auto-generated method stub
System.out.println("文件夹名称"+folderName);
Folder folder=store.getFolder(folderName);
System.out.println("测试连接");
if(folder==null){
throw new Exception("folderName"+"邮件夹不存在");
}
browerMessageFromFolder(folder);
}
public void browerMessageFromFolder(Folder folder) throws Exception {
// TODO Auto-generated method stub
System.out.println("开始从服务器文件夹中获取文件");
folder.open(Folder.READ_ONLY);
System.out.println("you have"+folder.getMessageCount()+"message in inbox");
System.out.println("you have"+folder.getUnreadMessageCount()+"unread message in inbox");
//读邮件
Message[] message=folder.getMessages();
for(int i=1;i<message.length;i++){
System.out.println("----第"+i+"封邮件----");
//打印邮件信息
folder.getMessage(i).writeTo(System.out);
System.out.println();
}
folder.close(false);
//关闭邮件夹,但不删除邮件夹中标识为"DELETE"的邮件
}
}
=======================================================================================
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class
MailClientFullURL extends MailClient{
/**
* @param args
*/
private Folder folder;
public void init() throws Exception{
init(new URLName("imap://admin:1234@localhost/inbox"));
// init(new URLName("pop3://admin:
[email protected]/inbox"));
}
private void init(URLName urlName) throws Exception {
// TODO Auto-generated method stub
Properties props=new Properties();
session=Session.getDefaultInstance(props);
folder=session.getFolder(urlName);
if(folder==null){
System.out.println(urlName.getFile()+"邮件夹不存在");
System.exit(0);
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MailClientFullURL client=new MailClientFullURL();
client.init();
client.browerMessageFromFolder(client.folder);
}
}
====================================================================================
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class
MailClientReadAttach extends MailClientSendAttach {
/**
* @param args
*/
private String fromAddr="
[email protected]";
private String toAddr="
[email protected]";
public void receiveMessage() throws Exception{
Folder folder=store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
System.out.println("you have"+folder.getMessageCount()+"message in inbox");
System.out.println("you have"+folder.getUnreadMessageCount()+"unread message in inbox");
//读邮件
Message[] message=folder.getMessages();
System.out.println("测试-----"+message.length);
for(int i=1;i<=message.length;i++){
System.out.println("----第"+i+"封邮件----");
//打印邮件信息
folder.getMessage(i).writeTo(System.out);
System.out.println();
}
folder.close(false);
//关闭邮件夹,但不删除邮件夹中标识为"DELETE"的邮件
}
public static void processMessage(Message msg) throws Exception{
processMessageHead(msg);
Object body=msg.getContent();//获取邮件头部
if(body instanceof Multipart){
processMultipart((Multipart)body);
}else{
processPart(msg);
}
}
private static void processPart(Message msg) {
// TODO Auto-generated method stub
}
private static void processMultipart(Multipart mp) throws Exception {
// TODO Auto-generated method stub
for(int i=0;i<mp.getCount();i++){
processPart(mp.getBodyPart(i));
}
}
private static void processPart(BodyPart part) throws Exception {
// TODO Auto-generated method stub
String fileName=part.getFileName();
String disposition=part.getDisposition();
String contentType=part.getContentType();
System.out.println("fileName="+fileName);
System.out.println("disposition="+disposition);
System.out.println("contentType="+contentType);
if(contentType.toLowerCase().startsWith("multipart/")){
processMultipart((Multipart)part.getContent());
}else if(fileName==null&&(Part.ATTACHMENT.equalsIgnoreCase(disposition)||!contentType.toLowerCase().startsWith("text/plain"))){
fileName=java.io.File.createTempFile("attachment", "data").getName();
}
//如果不是附件,打印到控制台
if(fileName==null){
part.writeTo(System.out);
System.out.println();
}else{
java.io.File file=new java.io.File(fileName);
//创建一个在文件系统中不存在的文件
for(int i=1;file.exists();i++){
String newName=i+"_"+fileName;
file=new java.io.File(newName);
}
//把附件保存到一个文件中
java.io.OutputStream out=new java.io.BufferedOutputStream(new java.io.FileOutputStream(file));
java.io.InputStream in=new java.io.BufferedInputStream(part.getInputStream());
int b;
while((b=in.read())!=-1){
out.write(b);
}
out.close();
in.close();
}
}
private static void processMessageHead(Message msg) throws Exception {
// TODO Auto-generated method stub
for(Enumeration<Header> e=msg.getAllHeaders();e.hasMoreElements();){
Header header=e.nextElement();
System.out.println(header.getName()+":"+header.getValue());
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MailClientReadAttach client=new MailClientReadAttach();
client.init();
client.sendMessage(client.fromAddr, client.toAddr);
client.receiveMessage();
client.close();
}
}
==============================================================================================
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class
MailClientSendAttach extends MailClientForCitiz{
/**
* @param args
*/
private String fromAddr="
[email protected]";
private String toAddr="
[email protected]";
public void sendMessage(String fromAddr,String toAddr) throws Exception{
//创建一个邮件
Message msg=new MimeMessage(session);
InternetAddress[] toAddrs=InternetAddress.parse(toAddr, false);
msg.setRecipients(Message.RecipientType.TO, toAddrs);
msg.setSubject("qinya");
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(fromAddr));
String attch1="attch1.txt";
String attch2="attch2.rar";
Multipart multipart=new MimeMultipart();
//加入文本内容
MimeBodyPart mineBodyPart1=new MimeBodyPart();
mineBodyPart1.setText("where the angle is");
multipart.addBodyPart(mineBodyPart1);
//加入第一个附件
MimeBodyPart mineBodyPart2=new MimeBodyPart();
FileDataSource fds=new FileDataSource(attch1);//得到数据源
mineBodyPart2.setDataHandler(new DataHandler(fds));
mineBodyPart2.setDescription(Part.ATTACHMENT);
mineBodyPart2.setFileName(fds.getName()); //设置文件名
multipart.addBodyPart(mineBodyPart2);
//
// //加入第二个附件
// MimeBodyPart mineBodyPart3=new MimeBodyPart();
// fds=new FileDataSource(attch2);//得到数据源
// mineBodyPart3.setDataHandler(new DataHandler(fds));
// mineBodyPart3.setDescription(Part.ATTACHMENT);
// mineBodyPart3.setFileName(fds.getName()); //设置文件名
// multipart.addBodyPart(mineBodyPart3);
//设置邮件正文
msg.setContent(multipart);
//发送邮件
Transport.send(msg);
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MailClientSendAttach client=new MailClientSendAttach();
client.init();
client.sendMessage(client.fromAddr, client.toAddr);
client.receiveMessage();
client.close();
}
}
==============================================================================================
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class
MailClientURLName {
protected Session session;
protected Store store;
private String sendHost="localhost";
private String receiveHost;
private String sendProtocol;
private String receiveProtocol;
private String username;
private String password;
private String fromAddr="
[email protected]";
private String toAddr="
[email protected]";
public void init() throws Exception{
init(new URLName("imap://admin:1234@localhost/"));
}
public void init(URLName urlName) throws Exception {
// TODO Auto-generated method stub
receiveProtocol=urlName.getProtocol();
receiveHost=urlName.getHost();
username=urlName.getUsername();
password=urlName.getPassword();
//设置属性
Properties props=new Properties();
props.put("mail.smtp.host",sendHost);
//创建session对象
session=Session.getDefaultInstance(props);
store=session.getStore(receiveProtocol);
store.connect(receiveHost, username, password);
}
public static void main(String[] args) throws Exception{
MailClientURLName client=new MailClientURLName();
client.init();
client.sendMessage(client.fromAddr,client.toAddr);
client.receiveMessage();
client.close();
}
public void sendMessage(String fromAddr,String toAddr) throws Exception{
//创建一个邮件
Message msg=createSimpleMessage(fromAddr,toAddr);
//发送邮件
Transport.send(msg);
}
public Message createSimpleMessage(String fromAddr, String toAddr) throws Exception {
// TODO Auto-generated method stub
Message msg=new MimeMessage(session);
InternetAddress[] toAddrs=InternetAddress.parse(toAddr,false);
msg.setRecipients(Message.RecipientType.TO,toAddrs);
msg.setSentDate(new Date());
msg.setSubject("hello");
msg.setFrom(new InternetAddress(fromAddr));
msg.setText("how are you");
return msg;
}
public void receiveMessage() throws Exception{
browseMessageFromFolder("inbox");
}
public void browseMessageFromFolder(String folderName) throws Exception {
// TODO Auto-generated method stub
Folder folder=store.getFolder(folderName);
if(folder==null){
throw new Exception("folderName"+"邮件夹不存在");
}
browerMessageFromFolder(folder);
}
public void browerMessageFromFolder(Folder folder) throws Exception {
// TODO Auto-generated method stub
folder.open(Folder.READ_ONLY);
System.out.println("you have"+folder.getMessageCount()+"message in inbox");
System.out.println("you have"+folder.getUnreadMessageCount()+"unread message in inbox");
//读邮件
Message[] message=folder.getMessages();
System.out.println("测试-----"+message.length);
for(int i=1;i<=message.length;i++){
System.out.println("----第"+i+"封邮件----");
//打印邮件信息
folder.getMessage(i).writeTo(System.out);
System.out.println();
}
folder.close(false);
//关闭邮件夹,但不删除邮件夹中标识为"DELETE"的邮件
}
public void close()throws Exception{
store.close();
}
}