随笔 - 7, 文章 - 12, 评论 - 17, 引用 - 0
数据加载中……

邮件的发送实例

package com.baosight.spes.mail;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
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;

import sun.misc.BASE64Encoder;

import com.baosight.dexpt.DefaultDispatcher;


public class MailSender {
 private Map mailMap = new HashMap();
 
 public void init()throws IOException
 {
  Properties props=new Properties();
  Class clazz=DefaultDispatcher.class;
  ClassLoader clazzLoader=clazz.getClassLoader();
  InputStream is=null;
  try
  {
   is=clazzLoader.getResourceAsStream("mail.properties");
   if(is==null)
   {
    throw new FileNotFoundException("\"classpath:mail.properties\" file not found...or open error...");
   }
   props.load(is);
  }
  finally
  {
   if(is!=null)
    is.close();
  }
  Iterator iter = props.keySet().iterator();
  for (; iter.hasNext();)
  {
   String key = (String) iter.next();
   String value=props.getProperty(key);
   this.mailMap.put(key, value);
  }
 } 
 /***
  *
  * @param to : 目标邮件地址
  * @param title :邮件标题
  * @param content: 邮件内容
  * @return :发送成功返回1,否则返回0
  */
 public int sendMessage(String to,String title,String content)
 {
  return sendMessage(to,title,content,null);
 }
 /***
  *
  * @param to : 目标邮件地址
  * @param title :邮件标题
  * @param content: 邮件内容
  * @param map :key为文件的名字,value为文件流(Inputstream)
  * @return :发送成功返回1,否则返回0
  */
 public int sendMessage(String to,String title,String content,HashMap map)
 {
  String [] tt = {to};
  return sendMessage(tt,null,title,content,map);
 }
 /***
  *
  * @param to : 目标邮件地址
  * @param cc : 抄送邮件地址
  * @param title :邮件标题
  * @param content: 邮件内容
  * @param map :key为文件的名字,value为文件流(Inputstream)
  * @return :发送成功返回1,否则返回0
  */
 public int sendMessage(String to,String cc,String title,String content,HashMap map)
 {
  String [] ttArr = {to};
  String [] ccArr={cc};
  return sendMessage(ttArr,ccArr,title,content,map);
 }
 /***
  *
  * @param to : 目标邮件地址数组
  * @param cc : 抄送邮件地址数组
  * @param title :邮件标题
  * @param content: 邮件内容
  * @param map :key为文件的名字,value为文件流(Inputstream)
  * @return :发送成功返回1,否则返回0
  */
 public int sendMessage(String[] to,String cc[],String title,String content,HashMap map)
 {
  String host = (String)mailMap.get("host");
        String from =  (String)mailMap.get("from");      
        String username = (String)mailMap.get("user");
        String password = (String)mailMap.get("password");       
      
        BASE64Encoder enc = new BASE64Encoder();
        try
        {
         Properties props = new Properties();
         props.put("mail.smtp.host", host);
         props.put("mail.smtp.auth", "true");
         Session session = Session.getDefaultInstance(props);
         session.setDebug(true);
        
         MimeMessage message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         InternetAddress[] sendTo = new InternetAddress[to.length];
         InternetAddress[] sendCc = new InternetAddress[cc.length];
         for (int i = 0; i < to.length; i++)
         {
              sendTo[i] = new InternetAddress(to[i]);
         }
        
         for (int i = 0; i < cc.length; i++)
         {
              sendCc[i] = new InternetAddress(cc[i]);
         }
         message.addRecipients(Message.RecipientType.TO,sendTo);
         message.addRecipients(Message.RecipientType.CC,sendCc);
         message.setSubject(title);

         //attachment
         MimeMultipart multi = new MimeMultipart();
         MimeBodyPart textBodyPart = new MimeBodyPart();
         textBodyPart.setContent(content, "text/html;charset=GBK");
         multi.addBodyPart(textBodyPart);
         Iterator iter = map.keySet().iterator();
         for(;iter.hasNext();)
         {
          String filename = ""+iter.next();
          InputStream is = (InputStream)map.get(filename);
          MimeBodyPart fileBodyPart = new MimeBodyPart();
          DataHandler dh = new DataHandler(new ByteArrayDataSource(is,"application/octet-stream"));
          fileBodyPart.setDataHandler(dh);
          fileBodyPart.setFileName(MimeUtility.encodeText(filename));
          multi.addBodyPart(fileBodyPart);
         }
        
         message.setContent(multi);
         message.saveChanges();
        
         Transport transport = session.getTransport("smtp");
         transport.connect(host, username, password);
         transport.sendMessage(message, message.getAllRecipients());
         transport.close();
        }catch(Exception e)
        {
         e.printStackTrace();
        }
        return 1;
 }
 /**
  * @param args
  */
 public static void main(String[] args)
 {
  MailSender ms = new MailSender();
  String[] to = {"hobby8062@yahoo.com.cn","hobby8052@163.com"};
  String[] cc = {"hobby8052@yahoo.com.cn"};
  String title ="测试";
  
  String content="测试<br><a href='http://www.sohu.com'>aaa</a>";
  //String content="测试";
  try
  {
   ms.init();

   HashMap map = new HashMap();
   
   InputStream is = new BufferedInputStream( new FileInputStream("e:/测试.doc"));
   String tostr = "hobby8052@163.com";
   map.put("测试.doc", is);
   is = new BufferedInputStream( new FileInputStream("e:/测试.rar"));
   map.put("测试.rar", is);
   ms.sendMessage(to, cc, title, content, map);
   //ms.sendMessage(tostr, title, content, map);
  }catch(Exception e)
  {
   e.printStackTrace();
  }
 }
 
}
/*************************对附件流(inputstream)的处理***************************************/
package com.baosight.spes.mail;
//Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
//Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
//Decompiler options: packimports(3) fieldsfirst ansi
//Source File Name:   ByteArrayDataSource.java


import java.io.*;
import javax.activation.DataSource;

public class ByteArrayDataSource
 implements DataSource
{

 private byte data[];
 private String type;

 public ByteArrayDataSource(InputStream inputstream, String s)
 {
     type = s;
     try
     {
         ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
         byte abyte0[] = new byte[4096];
         for(int i = 0; (i = inputstream.read(abyte0)) != -1;)
         {
             bytearrayoutputstream.write(abyte0, 0, i);
         }

         data = bytearrayoutputstream.toByteArray();
     }
     catch(IOException ioexception)
     {
         ioexception.printStackTrace();
     }
 }

 public ByteArrayDataSource(byte abyte0[], String s)
 {
     data = abyte0;
     type = s;
 }

 public ByteArrayDataSource(String s, String s1)
 {
     data = s.getBytes();
     type = s1;
 }

 public InputStream getInputStream()
     throws IOException
 {
     if(data == null)
         throw new IOException("no data");
     else
         return new ByteArrayInputStream(data);
 }

 public OutputStream getOutputStream()
     throws IOException
 {
     throw new IOException("cannot do this");
 }

 public String getContentType()
 {
     return type;
 }

 public String getName()
 {
     return "dummy";
 }
}

 

posted on 2007-07-07 15:38 刘浪 阅读(341) 评论(0)  编辑  收藏 所属分类: code


只有注册用户登录后才能发表评论。


网站导航: