自己写的一个mail发送组件,可以直接在程序中调用。

来源:互联网 发布:2016人才缺口it 编辑:程序博客网 时间:2024/05/21 08:04

以下是自己用java mail包写的一个发送邮件的组件,写的比较乱,也没仔细加注释,有任何问题可以联系shanchao@neusoft.com。 

mail.properties:配置文件,配置邮件服务器,发件人等信息

mail.smtp.host=smtp.neusoft.com
mail.smtp.auth=true
mail.smtp.timeout=25000

mail.from=shanchao@neusoft.com
mail.from.name=/u4e4c/u9c81/u6728/u9f50/u52b3/u52a8/u548c/u793e/u4f1a/u4fdd/u969c/u5c40/u7f51/u7ad9/u7ba1/u7406/u5458
mail.username=shanchao
mail.password=****    //密码需要自己写
mail.copyto=guozl@neusoft.com
mail.subject=/u4e4c/u9c81/u6728/u9f50/u52b3/u52a8/u548c/u793e/u4f1a/u4fdd/u969c/u5c40/u7f51/u7ad9/u901a/u77e5

 

SendMail类:mail发送组件,只需要在程序中调用就可以发邮件了。

package com.neusoft.apps;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
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配置文件配合使用
 * @author 单超
 * time:2007-8-14
 *
 */
public class SendMail {
 
 private Properties props = null;//配置文件props
 private Session session = null; //邮件会话session
 private MimeMessage mimeMsg = null;//Message对象 mimeMsg
 private Multipart mp = null; //邮件内容容器mp
 
 /**
  * 重要方法:该构造方法在创建SendMail对象时调用。用于加载必要的参数
  * @param toAddress
  * @param toAddressName
  * @param ccAddress
  * @param bodyContent
  * @throws Exception
  */
 public SendMail(String toAddress,String toAddressName,Map ccAddress,String bodyContent) throws Exception{
  //初始化成员变量
  this.init();
  
  //设置msg属性
  //设置收发件人,抄送人
  mimeMsg.setFrom(new InternetAddress(props.getProperty("mail.from"),props.getProperty("mail.from.name")));//设置发件人
  mimeMsg.setRecipient(Message.RecipientType.TO, new InternetAddress (toAddress,toAddressName));//设置收件人
  //设置抄送人
  if(ccAddress != null && ccAddress.size() >0){
   mimeMsg.setRecipients(Message.RecipientType.CC, createCcAddress(ccAddress));
  }
  
  //设置邮件标题和日期
  //需要中文转码
  mimeMsg.setSubject(encode(props.getProperty("mail.subject")));//设置邮件标题
  mimeMsg.setSentDate(new java.util.Date());//设置发件日期
  
  //设置正文
  BodyPart bp = new MimeBodyPart();
  bp.setContent("" + bodyContent, "text/html;charset=GBK");
  mp.addBodyPart(bp);

 }
 
 /**
  * 重要方法:重载的构造器
  * @param toAddress
  * @param ccAddress
  * @param bodyContent
  * @throws Exception
  */
 public SendMail(String toAddress,Map ccAddress,String bodyContent) throws Exception{
  this(toAddress,null,ccAddress,bodyContent);
 }
 
 /**
  * 重要方法:重载的构造器
  * @param toAddress
  * @param bodyContent
  * @throws Exception
  */
 public SendMail(String toAddress,String bodyContent)throws Exception{
  this(toAddress,null,null,bodyContent);
 }
 
 /**
  * 重要方法:重载的构造器
  * @param toAddress
  * @param toAddressName
  * @param bodyContent
  * @throws Exception
  */
 public SendMail(String toAddress,String toAddressName,String bodyContent)throws Exception{
  this(toAddress,toAddressName,null,bodyContent);
 }
 
 /**
  * 重要方法:该方法用于添加附件,fileRealPath为附件的本地绝对地址,newFileName为附件发送后的文件名
  * @param fileRealPath
  * @param newFileName
  * @throws Exception
  */
 public void addFile(String fileRealPath,String newFileName) throws Exception{
  //设置邮件附件
  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);
 }
 
 /**
  * 重要方法:该方法用于添加附件,fileRealPath为附件的本地绝对地址,附件发送后的文件名默认于原文件名字相同
  * @param fileRealPath
  * @param newFileName
  * @throws Exception
  */
 public void addFile(String fileRealPath) throws Exception{
  this.addFile(fileRealPath,null);
 }
 
 /**
  * 重要方法:发送mail
  * @throws Exception
  */
 public void send() throws Exception{
  //融合邮件内容
  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();
 }
 
 /*
  * 私有方法:用于对中文进行转码
  * @param value
  * @return
  * @throws Exception
  */
 private String encode(String value) throws Exception{
  return  MimeUtility.encodeText(
    new String(value.getBytes(),"GB2312"),
    "GB2312",
    "B");
 }
 
 /*
  * 私有方法:用于初始化props,session,mimeMsg,mp等成员变量
  * @throws Exception
  */
 private void init() throws Exception{
  //初始化props,读取config/mail.properties文件  //需要完善,不能每次都读取配置文件
  this.props  = getProperties("config/mail.properties");//????????????
  
  //初始化session,msg,mp
  this.session = Session.getInstance(props, null);//获取共享session对象
  this.mimeMsg = new MimeMessage(session);//创建Message
  this.mp = new MimeMultipart();//创建Multipart
 }
 
 /*
  * 私有方法:用于读取mail.properties配置文件
  * @param fileName
  * @return
  * @throws Exception
  */
 private Properties getProperties(String fileName) throws Exception{
  URL url = ConfigUtil.class.getClassLoader().getResource(fileName);  
        File configFile = new File(url.getFile());          
        Properties props = new Properties();   
        props.load(new FileInputStream(configFile));
        return props;
 }
 
 /*
  * 私有方法:用于将以Map形式传入的抄送人地址,组织成Address[]
  * @param ccAddress
  * @return
  * @throws Exception
  */
 private static 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;
 }
}

MailTest:测试程序,也同时说明了SendMail的调用方式。

package com.neusoft.apps;

import java.util.HashMap;
import java.util.Map;

 

public class MailTest {

 public static void main(String[] args) throws Exception{
  Map map = new HashMap();
  SendMail mail = new SendMail("shanchao@neusoft.com","***",map,"三版测试");
  mail.addFile("F://设计模式JAVA.pdf");
  mail.send();
 }
}