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

📄 sendmail.java

📁 javamail发送源码 javamail发送源码
💻 JAVA
字号:
package quickweb.common;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


/**
 * 服务器端Mail发送组件,需要跟mail.properties配置文件配合使用
 * shanc 创建文件
 * 2007-8-14
 * 
 * shanc 修改文件
 * 2007-8-30
 * 修改:为配置文件设置了缓存
 * 	    增加动态加载配置文件功能(可以在运行时判断配置文件是否被修改,如果被修改则重新加载配置文件)
 * 
 * shanc 修改文件
 * 2007-8-31
 * 修改:重构Class,将可变部分剥离并封装到MailBean中
 * 	   将结构改得更灵活,客户端程序员可以在程序中修改配置文件中所定义的信息
 * 	   在配置文件中增加了一个mail.type属性,用于标识mail正文的格式(纯文本或HTML格式)
 *
 */
public class SendMail {
	
	public static final String HTML_TYPE_VALUE = "html";
	public static final String TEXT_TYPE_VALUE = "text";
	
	static final String MAIL_SMTP_HOST = "mail.smtp.host";
	static final String MAIL_SMTP_TIMEOUT = "mail.smtp.timeout";
	static final String MAIL_FROM = "mail.from";
	static final String MAIL_FROM_NAME = "mail.from.name";
	static final String MAIL_USERNAME = "mail.username";
	static final String MAIL_PASSWORD = "mail.password";
	static final String MAIL_SUBJECT = "mail.subject";
	static final String MAIL_TYPE = "mail.type";
	
	
	static final String TOKENIZER = "?";
	
	private static final String CONFIG_FILE = "config/mail.properties";//配置文件名
	
	private static Properties propsStone = null;//配置文件props
	private static File configFile = null;//配置文件File对象 configFile
	private static long fileLastModified = 0L;//配置文件最后修改时间
	
	private Session session = null; //邮件会话session
	private MimeMessage mimeMsg = null;//Message对象 mimeMsg
	private Multipart mp = null; //邮件内容容器mp
	
	private MailBean mailBean = null;//MailBean对象
	
	
	public SendMail(MailBean mailBean){
		this.mailBean = mailBean;
	}
	
	/**
	 * 重要方法:该静态方法相当于一个工厂方法,用于返回MailBean的一个实例
	 * @param toAddress 收件人邮箱地址
	 * @param toAddressName 收件人别名
	 * @param ccAddress 抄送人邮件地址和抄送人别名
	 * @param bodyContent 邮件正文内容
	 * @throws Exception 
	 */
	public static MailBean createMail(String toAddress,String toAddressName,Map ccAddress,String bodyContent) throws Exception{
		//初始化成员变量
		configInit();
		Properties props = new Properties();
		props.putAll(propsStone);
		return new MailBean(toAddress,toAddressName,ccAddress,bodyContent,props);
	}
	
	/**
	 * 重要方法:重载的工厂方法
	 * @param toAddress
	 * @param ccAddress
	 * @param bodyContent
	 * @throws Exception
	 */
	public static MailBean createMail(String toAddress,Map ccAddress,String bodyContent) throws Exception{
		return createMail(toAddress,null,ccAddress,bodyContent);
	}
	
	/**
	 * 重要方法:重载的工厂方法
	 * @param toAddress
	 * @param toAddressName
	 * @param bodyContent
	 * @throws Exception
	 */
	public static MailBean createMail(String toAddress,String toAddressName,String bodyContent)throws Exception{
		return createMail(toAddress,toAddressName,null,bodyContent);
	}
	
	/**
	 * 重要方法:重载的工厂方法
	 * @param toAddress
	 * @param bodyContent
	 * @throws Exception
	 */
	public static MailBean createMail(String toAddress,String bodyContent)throws Exception{
		return createMail(toAddress,null,null,bodyContent);
	}
	
	/**
	 * 重要方法:发送mail
	 * @throws Exception
	 */
	public void send() throws Exception{
		//初始化session,msg,mp
		Properties props = mailBean.getProps();
		this.session = Session.getInstance(props, null);//获取共享session对象
		this.mimeMsg = new MimeMessage(session);//创建Message
		this.mp = new MimeMultipart();//创建Multipart
		//设置msg属性
		this.setFrom(props);//设置收发件人
		this.setTo(mailBean.getToAddress(), mailBean.getToAddressName());//设置收件人
		this.setCC(mailBean.getCcAddress());//设置抄送人
		
		this.setSubjectAndDate(props);//设置邮件标题和日期
		
		this.setBodyContent(mailBean.getBodyContent(),props);//设置正文内容
		
		//添加附件
		this.addFile();
		
		//融合邮件内容
		mimeMsg.setContent(mp);	
		//发送邮件
		Transport transport = session.getTransport("smtp");//????????
		transport.connect(props.getProperty(MAIL_SMTP_HOST), 
				props.getProperty(MAIL_USERNAME), 
				props.getProperty(MAIL_PASSWORD));
		transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
		transport.close();
	}
	
	/*
	 * 私有方法:用于设置发件人
	 * @throws Exception
	 */
	private void setFrom(Properties props) throws Exception{
		mimeMsg.setFrom(new InternetAddress(props.getProperty(MAIL_FROM),props.getProperty(MAIL_FROM_NAME)));//设置发件人
	}
	
	/*
	 * 私有方法:用于设置收件人
	 * @param toAddress
	 * @param toAddressName
	 * @throws Exception
	 */
	private void setTo(String toAddress,String toAddressName) throws Exception{
		mimeMsg.setRecipient(Message.RecipientType.TO, new InternetAddress (toAddress,toAddressName));//设置收件人
	}
	
	/*
	 * 私有方法:用于设置抄送人
	 * @param ccAddress
	 * @throws Exception
	 */
	private void setCC(Map ccAddress) throws Exception{
		if(ccAddress != null && ccAddress.size() >0){
			mimeMsg.setRecipients(Message.RecipientType.CC, createCcAddress(ccAddress));
		}
	}
	
	/*
	 * 私有方法:用于设置邮件标题和发件日期 
	 * @throws Exception
	 */
	private void setSubjectAndDate(Properties props) throws Exception{
		//需要中文转码
		mimeMsg.setSubject(encode(props.getProperty(MAIL_SUBJECT)));//设置邮件标题
		mimeMsg.setSentDate(new java.util.Date());//设置发件日期
	}
	
	/*
	 * 私有方法:用于设置邮件正文内容
	 * @param bodyContent
	 * @throws Exception
	 */
	private void setBodyContent(String bodyContent,Properties props)throws Exception{
		//设置正文
		BodyPart bp = new MimeBodyPart();
		if(TEXT_TYPE_VALUE.equals(props.get(MAIL_TYPE)))
			bp.setText(bodyContent);
		else
			bp.setContent(bodyContent, "text/html;charset=GBK");//?????
		mp.addBodyPart(bp);
	}
	
	/*
	 * 私有方法:用于对中文进行转码
	 * @param value
	 * @return
	 * @throws Exception
	 */
	private String encode(String value) throws Exception{//?????
		return  MimeUtility.encodeText(
				new String(value.getBytes(),"GB2312"), 
				"GB2312", 
				"B"); 
	}
	
	/*
	 * 私有方法:用于添加附件
	 * @throws Exception
	 */
	private void addFile() throws Exception{
		List fileList = mailBean.getFileList();
		if(!fileList.isEmpty()){
			for(int i = 0 ;i<fileList.size();i++){
				String temp = (String)fileList.get(i);
				String fileRealPath = temp.substring(temp.indexOf(TOKENIZER)+1);
				String newFileName = temp.substring(0,temp.indexOf(TOKENIZER));
				BodyPart body = new MimeBodyPart();  
				FileDataSource fileDataSource = new FileDataSource(fileRealPath); 
				body.setDataHandler(new DataHandler(fileDataSource));        
				if(newFileName == null || "".equals(newFileName)){
					newFileName = fileDataSource.getName();
				}
				//需要对附件文件名称进行转码,不然会出现乱码 
				body.setFileName(encode(newFileName)); //
				mp.addBodyPart(body);
			}
		}
	}
	
	/*
	 * 私有方法:用于将以Map形式传入的抄送人地址,组织成Address[]
	 * @param ccAddress
	 * @return
	 * @throws Exception
	 */
	private Address[] createCcAddress(Map ccAddress) throws Exception{
		Object[] keys = ccAddress.keySet().toArray();
		Address[] result = new InternetAddress[keys.length];
		for(int i = 0;i<keys.length;i++){
			String mailAddress = (String)keys[i];
			String mailName = (String)ccAddress.get(keys[i]);
			result[i] = new InternetAddress(mailAddress,mailName);
		}
		return result;
	}
	
	
	/*
	 * 私有方法:加载mai.properties,初始化configFile
	 * @throws Exception
	 */
	private static void createConfig() throws Exception{
        URL url = ConfigUtil.class.getClassLoader().getResource(CONFIG_FILE);
        configFile = new File(url.getFile());
        propsStone = new Properties();
        load();
    }

	/*
	 * 私有方法:load配置文件,修改fileLastModified
	 * @throws Exception
	 */
    private static void load() throws Exception{
    	propsStone.clear();
    	propsStone.load(new FileInputStream(configFile));
        fileLastModified = configFile.lastModified();
    }

    /*
     * 私有方法:加载配置文件,如果配置文件被更新,则重新加载
     * 该方法在init中被调用
     * @param key
     * @throws Exception
     */
    private static void configInit() throws Exception{
        if ((configFile == null) || (propsStone == null)) {
        	createConfig();
        }else if(configFile.lastModified() > fileLastModified) {
        	load();
        }
    }
}

⌨️ 快捷键说明

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