⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailuserinfobean.java

📁 java的邮件发送源码
💻 JAVA
字号:
/*
 * Created on 2005-8-17
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package cn.ac.ict;


import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import cn.ac.ict.Log4j;
import org.apache.log4j.*;

/**
 * @author zhw
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MailUserInfoBean {
    URLName urlName;
    Session mailSession;
    Store store;
    Folder currentFolder;
    Message currentMsg;
    private Logger logger;
    public MailUserInfoBean(){
		Log4j.ConfigLog_ln(); 

    }
    public static void main(String argc[]) throws MessagingException{
       	MailUserInfoBean mufb = new MailUserInfoBean();
       	int del[] = new int[1];
       	Message msg = null;
       
    	if(mufb.connect("localhost","jmailapp","jmailapp")==JMailUtil.SUCCESS){
    		System.out.print("success");
    		MimeMessage message = new MimeMessage(mufb.getMailSession());
    		message.setFrom(new InternetAddress("localhost"));
    	    message.addRecipient(Message.RecipientType.TO, new InternetAddress("haierreiah@163.com"));
    	    message.setSubject("JMail Test Application");
    	    message.setText("You JMail Application is successful!");

    	    mufb.setCurrentMsg(message);
    	    mufb.deleteFolder("hellotwo");
    	    //mufb.createFolder("hello");
    	    //mufb.renameFolder("hello","hellotwo");
    	    mufb.sendMessage(message);
    	    //mufb.saveMessage(message);
    	    msg = mufb.createMessage("jmailapp@domain.com","","","dajiahao","sdfadf");
    		if(msg==null){
    			System.out.println("create error!");
    		}
    		mufb.sendMessage(msg);
    	    del[0]=1;
           	//del[1]=2;
    	    //mufb.deleteMessage(del,mufb.getStore().getFolder("inbox"));
    	    System.out.print(JMailUtil.getChinese("inbox"));
    		//System.out.print(JMailUtil.AddressToString(mufb.getCurrentMsg().getAllRecipients()));
    	}	
    }
    	public int connect(String host,String user,String pass){
    		  Properties prop=null;
    	      prop = System.getProperties();
    	      prop.put("mail.transport.protocol", "smtp");
    	      prop.put("mail.store.protocol", "imap");
    	      prop.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
    	      prop.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");
    	      prop.put("mail.smtp.host", "localhost");
    	      SmtpAuth  auth = null;
    	      auth = new SmtpAuth();
    	      auth.setUserinfo(user,pass);
    	      Session mail_Session = Session.getDefaultInstance(prop, auth);
    	      mail_Session.setPasswordAuthentication(new URLName(host),auth.getPasswordAuthentication());
    	      this.setMailSession(mail_Session);

    	      try {
				// Get a Store object
				   this.store = this.mailSession.getStore("imap");
				   this.store.connect(host,user,pass);
				   URLName url = new URLName("imap",host, -1, "inbox", user, pass);
				   setURLName(url);
				   Log4j.logger.info("The Store is connected!");
			} catch (NoSuchProviderException e) {
				e.printStackTrace();
				Log4j.logger.debug("Get a Store error!");
				Log4j.logger.debug(e);
				return JMailUtil.FAILED;
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				Log4j.logger.debug("Get a Store error!");
				e.printStackTrace();
				Log4j.logger.debug(e);
				return JMailUtil.FAILED;
			}
			return JMailUtil.SUCCESS;
    	}
    	
    	public URLName getURLName() {
    	return urlName;
        }

        public void setURLName(URLName url){
            urlName=url;
        }

        public Session getMailSession() {
    	return mailSession;
        }

        public void setMailSession(Session s) {
        	mailSession = s;
        }
        public Store getStore() {
        	return store;
        }

        public void setStore(Store s) {
        	store = s;
        }
        public void setCurrentMsg(Message m){
        	this.currentMsg=m;
        }
        public Message getCurrentMsg(){
        	return this.currentMsg;
        }
        public void setCurrentFolder(Folder f){
        	this.currentFolder = f;
        }
        public Folder getCurrentFolder(){
        	return this.currentFolder;
        }
        
        public int deleteFolder(String foldername){
        	
            if(foldername.equalsIgnoreCase("inbox")||
                    foldername.equalsIgnoreCase("trash")||
                    foldername.equalsIgnoreCase("draft")||
                    foldername.equalsIgnoreCase("sendbox")){
            	Log4j.logger.debug("你要删除文件夹是不被允许的");
            	return JMailUtil.REFUSED;
            }
            try {
				Folder folder=store.getFolder(foldername);
				
				if(!folder.exists()){
					
					Log4j.logger.debug("你要删除文件夹不存在!");
					return JMailUtil.FAILED;				
				}
				if(folder.isOpen()){
					folder.close(true);
				}
				folder.delete(true);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				Log4j.logger.debug("删除文件夹失败!");
				e.printStackTrace();
				return JMailUtil.FAILED;
			}
			Log4j.logger.info("文件夹"+foldername+"被删除!");
			return JMailUtil.SUCCESS;
        }
        
        public int createFolder(String foldername){
        	if(foldername.equals("")||foldername==null){
        		return JMailUtil.FAILED;
        	}
        	try {
				Folder folder=store.getFolder(foldername);
				if(folder.exists()){
					Log4j.logger.debug("文件夹"+foldername+"已存在");
					return JMailUtil.FAILED;
				}
				folder.create(Folder.HOLDS_MESSAGES);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return JMailUtil.FAILED;
			}
			Log4j.logger.info("创建了"+foldername+"文件夹");	
        	return JMailUtil.SUCCESS;
        }
        
        public int renameFolder(String oldname,String newname){
        	if(newname==null||newname.equals("")){
        		return JMailUtil.REFUSED;
        	}
        	if(oldname.equalsIgnoreCase("inbox")||
        			oldname.equalsIgnoreCase("trash")||
        			oldname.equalsIgnoreCase("draft")||
        			oldname.equalsIgnoreCase("sendbox")||
        			oldname.equalsIgnoreCase("inbox")||
        			oldname.equalsIgnoreCase("trash")||
        			oldname.equalsIgnoreCase("draft")||
        			oldname.equalsIgnoreCase("sendbox")){
        		Log4j.logger.debug("文件夹"+oldname+"不允许被重命名");
        		return JMailUtil.REFUSED;
        	}
        	try {
				Folder oldFolder = store.getFolder(oldname);
		       	Folder newFolder = store.getFolder(newname);
		       	if(!oldFolder.exists()){
		       		Log4j.logger.debug("文件夹"+oldname+"不存在");
		       		return JMailUtil.FAILED;
		       	}
		       	if(oldFolder.isOpen()){
		       		oldFolder.close(true);
		       	}
		       	oldFolder.renameTo(newFolder);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log4j.logger.debug("重命名文件夹失败!"+e);
				return JMailUtil.FAILED;
			}
			Log4j.logger.info("重命名文件夹成功");
         	return JMailUtil.SUCCESS;
        }
        
        public int deleteMessage(int delArray[],Folder f){
        	try{
        		if(!f.isOpen()){
        			f.open(Folder.READ_WRITE);
        		}
             	for(int i=0;i<delArray.length;i++){
            		if(delArray[i]==0) continue;
            		Message delMsg = f.getMessage(i+1);
            		if(!f.getName().equals("Trash")){
            			Message[] m=new Message[1];
            			m[0] = delMsg;
            			Folder Trash=store.getFolder("Trash");
                        f.copyMessages(m,Trash);
                        delMsg.setFlag(Flags.Flag.DELETED, true);
                        System.out.print("Trash");
            		}else{
            			delMsg.setFlag(Flags.Flag.DELETED, true);
            		}
            	}
        		f.expunge();
        	}catch(Exception e){
        		Log4j.logger.debug("删除邮件失败!"+e);
        		System.out.println("删除邮件失败!");
        		e.printStackTrace();
        		return JMailUtil.FAILED;
        	}
        	Log4j.logger.info("邮件被成功删除!");
        	return JMailUtil.SUCCESS;
        }
        
        public Message createMessage(String to,String cc,String bcc,String subj,String text){
        	Message msg = new MimeMessage(this.mailSession);
        	InternetAddress[] toAddress = null, ccAddress = null, bccAddress=null;
        	if((to!=null)&&(!to.equals(""))){
        		try {
					toAddress = InternetAddress.parse(to,false);
					msg.setRecipients(Message.RecipientType.TO,toAddress);
				} catch (AddressException e) {
					System.out.println("AddressException");
					e.printStackTrace();
					Log4j.logger.debug("新建邮件失败!"+e);
					return null;
				}catch(MessagingException me){
					System.out.println("MessagingException");
					me.printStackTrace();
					Log4j.logger.debug("新建邮件失败!"+me);
					return null;
				}
        		
        	}
        	if((!cc.equals(""))&&(cc!=null)){
        		try {
        	    	ccAddress = InternetAddress.parse(cc, false);
					msg.setRecipients(Message.RecipientType.CC, ccAddress);
				} catch (MessagingException e) {
					e.printStackTrace();
					Log4j.logger.debug("新建邮件失败!"+e);
				}
        	}
        	if((!bcc.equals(""))&&(bcc!=null)){
        		try {
					bccAddress = InternetAddress.parse(bcc, false);
					msg.setRecipients(Message.RecipientType.BCC, bccAddress);
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log4j.logger.debug("新建邮件失败!"+e);
				}
        	}
        	if((!subj.equals(""))&&(subj!=null)){
        		try {
					msg.setSubject(subj);
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log4j.logger.debug("新建邮件失败!"+e);
				}
        	}
        	try {
				msg.setFrom(new InternetAddress(urlName.getUsername()+"@"+urlName.getHost()));
			} catch (AddressException e) {
				System.out.println("urlName"+urlName);
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log4j.logger.debug("新建邮件失败!"+e);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log4j.logger.debug("新建邮件失败!"+e);
			}
			if(text!=null){
				try {
					msg.setText(text);
				} catch (MessagingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					Log4j.logger.debug("新建邮件失败!"+e1);
				}
			}
			return msg;
        }
        
        public int sendMessage(Message msg){
        	try {
				Transport.send(msg);
				//this.getMailSession().getProperties();
				/*
				 * System.out.println(msg.getSubject()+this.getMailSession().getProperty("mail.smtp.host"));
				 Folder f=store.getFolder("SendBox");
				if(!f.isOpen())
					f.open(Folder.READ_WRITE);
				Message m[]=new Message[1];
		        m[0]=msg;		        
		        f.appendMessages(m);
		        */
			} catch (MessagingException e1) {
				System.out.println("发送邮件失败!");
				e1.printStackTrace();
				Log4j.logger.debug("发送邮件失败!"+e1);
			}
			System.out.print("发送邮件成功!");
			Log4j.logger.info("发送邮件成功!");
        	return JMailUtil.SUCCESS;
        }
        
        public int saveMessage(Message msg){
        	 Folder f;
			try {
				f = store.getFolder("Draft");
				if(!f.isOpen())
					f.open(Folder.READ_WRITE);
				Message m[]=new Message[1];
		        m[0]=msg;
		        
		        f.appendMessages(m);
		        //f.expunge();
			} catch (MessagingException e) {
				e.printStackTrace();
				Log4j.logger.debug("保存邮件失败!"+e);
				return JMailUtil.FAILED;
			}
			Log4j.logger.info("成功保存了邮件");
        	return JMailUtil.SUCCESS;
        }
        
        public int moveMessge(String toFolderName){
        	try {
				Folder folderto = store.getFolder(toFolderName);
				if(!folderto.exists()){
					Log4j.logger.debug("");
					return JMailUtil.REFUSED;
				}
				Message[] m=new Message[1];
				m[0] = this.currentMsg;
				this.currentFolder.copyMessages(m,folderto);
				this.currentMsg.setFlag(Flags.Flag.DELETED,true);
				this.currentFolder.expunge();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log4j.logger.debug("移动邮件出现错误"+e);
				return JMailUtil.FAILED;
			}
			Log4j.logger.info("成功移动了邮件");
			return JMailUtil.SUCCESS;
        	
        }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -