【永恒的瞬间】
☜Give me hapy ☞

//文件Mail.java 该文件内容部分综合网上的资源,自己进行了改进,转载请注明 汪建伟。

package sendmail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.Date;
import java.util.ArrayList;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: Peking University </p>
 * @author 汪建伟
 * @version 1.0
 */

public  class Mail{
   
    protected ArrayList bodypartArrayList=null;
    protected Multipart multipart = null;
    protected MimeMessage mailMessage = null;
    protected Session mailSession = null;
    protected Properties mailProperties = System.getProperties();
    protected InternetAddress mailFromAddress = null;
    protected InternetAddress mailToAddress = null;
    protected String mailSubject ="";
    protected Date mailSendDate = null;
    private String smtpserver="";
    private String name="";
    private String password="";
   
    public Mail(String smtpHost,String username,String password){
     smtpserver=smtpHost;
     name=username;
     this.password=password;
        mailProperties.put("mail.smtp.host",smtpHost);
        mailProperties.put("mail.smtp.auth","true"); //设置smtp认证,很关键的一句
        mailSession = Session.getDefaultInstance(mailProperties);
        //mailSession.setDebug(true);
       
        mailMessage = new MimeMessage(mailSession);
        multipart = new MimeMultipart();
        bodypartArrayList=new ArrayList();//用来存放BodyPart,可以有多个BodyPart!
    }
    //设置邮件主题
    public void setSubject(String mailSubject)throws MessagingException{
        this.mailSubject = mailSubject;
        mailMessage.setSubject(mailSubject);
    }
    //设置邮件发送日期
    public void setSendDate(Date sendDate)throws MessagingException{
        this.mailSendDate = sendDate;
        mailMessage.setSentDate(sendDate);
    }
    //发送纯文本
    public void addTextContext(String textcontent)throws MessagingException{
     BodyPart bodypart=new MimeBodyPart();
     bodypart.setContent(textcontent,"text/plain;charset=GB2312");
     bodypartArrayList.add(bodypart);
    }
    //发送Html邮件
    public void addHtmlContext(String htmlcontent)throws MessagingException{
     BodyPart bodypart=new MimeBodyPart();
     bodypart.setContent(htmlcontent,"text/html;charset=GB2312");
     bodypartArrayList.add(bodypart);
    }
    //将文件添加为附件
    public void addAttachment(String FileName/*附件文件名*/,String DisplayFileName/*在邮件中想要显示的文件名*/)
        throws MessagingException,UnsupportedEncodingException{
     BodyPart bodypart=new MimeBodyPart();
        FileDataSource fds=new FileDataSource(FileName);
       
        DataHandler dh=new DataHandler(fds);
        String displayfilename="";
  displayfilename = MimeUtility.encodeWord(DisplayFileName,"gb2312", null);//对显示名称进行编码,否则会出现乱码!
  
  bodypart.setFileName(displayfilename);//可以和原文件名不一致
        bodypart.setDataHandler(dh);
     bodypartArrayList.add(bodypart);
    }
    //将byte[]作为文件添加为附件
    public void addAttachmentFrombyte(byte[] filebyte/*附件文件的字节数组*/,String DisplayFileName/*在邮件中想要显示的文件名*/)
        throws MessagingException,UnsupportedEncodingException{
     BodyPart bodypart=new MimeBodyPart();
     ByteDataSource fds=new ByteDataSource(filebyte,DisplayFileName);
      
        DataHandler dh=new DataHandler(fds);
        String displayfilename="";
  displayfilename = MimeUtility.encodeWord(DisplayFileName,"gb2312", null);//对显示名称进行编码,否则会出现乱码!
  
  bodypart.setFileName(displayfilename);//可以和原文件名不一致
        bodypart.setDataHandler(dh);
     bodypartArrayList.add(bodypart);
    }

   
    //使用远程文件(使用URL)作为信件的附件
    public void addAttachmentFromUrl(String url/*附件URL地址*/,String DisplayFileName/*在邮件中想要显示的文件名*/)
        throws MessagingException,MalformedURLException,UnsupportedEncodingException{
     BodyPart bodypart=new MimeBodyPart();
        //用远程文件作为信件的附件
        URLDataSource ur= new URLDataSource(new URL(url));
        //注:这里用的参数只能为URL对象,不能为URL字串
  DataHandler dh=new DataHandler(ur);
  String displayfilename="";
        displayfilename=MimeUtility.encodeWord(DisplayFileName,"gb2312", null);
  bodypart.setFileName(displayfilename);//可以和原文件名不一致
  bodypart.setDataHandler(dh);
  bodypartArrayList.add(bodypart);
    }

   
    //设置发件人地址
    public void setMailFrom(String mailFrom)throws MessagingException{
        mailFromAddress = new InternetAddress(mailFrom);
        mailMessage.setFrom(mailFromAddress);
    }
    //设置收件人地址,收件人类型为to,cc,bcc(大小写不限)
    public void setMailTo(String[] mailTo,String mailType)throws Exception{
        for(int i=0;i<mailTo.length;i++){
            mailToAddress = new InternetAddress(mailTo[i]);
            if(mailType.equalsIgnoreCase("to")){
                mailMessage.addRecipient(Message.RecipientType.TO,mailToAddress);
            }
            else if(mailType.equalsIgnoreCase("cc")){
                mailMessage.addRecipient(Message.RecipientType.CC,mailToAddress);
            }
            else if(mailType.equalsIgnoreCase("bcc")){
                mailMessage.addRecipient(Message.RecipientType.BCC,mailToAddress);
            }
            else{
                throw new Exception("Unknown mailType: "+mailType+"!");
            }
        }
    }
    //开始投递邮件
    public void sendMail()throws MessagingException,SendFailedException{
     for (int i=0;i<bodypartArrayList.size();i++) {
      multipart.addBodyPart((BodyPart)bodypartArrayList.get(i)); 
     }
     mailMessage.setContent(multipart);
        mailMessage.saveChanges();
        Transport transport=mailSession.getTransport("smtp");
        transport.connect(smtpserver,name,password);//以smtp方式登录邮箱
        transport.sendMessage(mailMessage,mailMessage.getAllRecipients());
        //发送邮件,其中第二个参数是所有已设好的收件人地址
        transport.close();
    }

}

//文件 ByteDataSource.java 该文件内容由汪建伟原创。转载请注明!

package sendmail;


/**
 * <p>Title: </p>
 * <p>Description: 发邮件</p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: Peking University </p>
 * @author 汪建伟
 * @version 1.0
 */
import javax.activation.DataSource;
import java.io.*;
public class ByteDataSource implements DataSource{
 private byte[] filebyte=null;
    private String filetype="application/octet-stream";
    private String filename="";
    private OutputStream outputstream=null;
    private InputStream  inputstream=null;
    public ByteDataSource() {
    }
    public ByteDataSource(String FileName) {
     File f=new File(FileName);
      filename=f.getName();
     try {
   inputstream = new FileInputStream(f);
   inputstream.read(filebyte);
   
  } catch (Exception e) {
  }
  
    }

    public ByteDataSource(byte[] filebyte,String displayfilename) {
        this.filebyte=filebyte;
        this.filename=displayfilename;
    }
    public String getContentType() {
        return filetype;
    }

    publicInputStreamgetInputStream() throws IOException {
     InputStream input=new ByteArrayInputStream(filebyte);
        return input;
    }

    public String getName() {
        return filename;
    }

    public OutputStream getOutputStream() throws IOException {
     
     outputstream.write(filebyte);
        return outputstream;
    }
}
//newSendMail.java 发邮件示例

  package sendmail;


/**
 * <p>Title: </p>
 * <p>Description: 发邮件示例</p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: Peking University </p>
 * @author 汪建伟
 * @version 1.0
 */

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.*;
public class newSendMail {
  public static void main(String[] args) {
     Mainprogram1 w1= new Mainprogram1();
 
     w1.sendmail() ;
 
  
  }
}

class Mainprogram1{
 
  private  java.util.Date sysdate;
  Mainprogram1(){
      //获取要查询的起止时间
      sysdate = new java.util.Date();
     }

  public void sendmail(){ //创建邮件发送实例,发送邮件
    String smtp = "smtp.163.com";//邮件服务器地址
    String mailname = "";//连接邮件服务器的用户名
    String mailpsw = "";//连连接邮件服务器的用户密码
    String mailto = "";// 接收邮件的地址
    String copyto = "";// 抄送邮件的地址
    String mailfrom = "";// 发送邮件的地址
    String mailtitle = "测试邮件标题";// 邮件的标题
     //请根据实际情况赋值
    Mail mymail= new Mail(smtp,mailname, mailpsw);
    String mto[]={mailto};
    String mcc[]={copyto};
    try{
       mymail.setMailFrom(mailfrom);
       mymail.setSendDate(new Date());
       mymail.setMailTo(mto,"to");
       if (!copyto.matches("")){ //如果抄送不为空,则将信件抄送给copyto
           mymail.setMailTo(mcc,"cc");
       }
       mymail.setSubject(mailtitle);
       mymail.addTextContext("邮件内容");
       mymail.addHtmlContext("html内容");
       mymail.addAttachment("c:\\测试附件.doc","测试附件.doc");
       mymail.addAttachmentFromUrl("http://162.105.109.163/getimg?imgid=148","图片文件.jpg");
       mymail.addAttachmentFromUrl("http://www.pku.edu.cn/","北大主页.htm");
      
       //下面的附件内容来自一个byte[]类型,增加这个方法的意图在于如果在web模式下发邮件,就不用生成临时文件
       //直接将上载的文件保存成byte[]格式,然后使用该方法添加到邮件的附件中,进行发送
       InputStreaminputStream=null;
     try {
     File imageFile = new File("c:\\1.jpg");
         inputStream = new FileInputStream(imageFile);
      } catch(IOException ei){}
  
    try {
     byte[] b=new byte[inputStream.available()];
   
     inputStream.read(b);
     mymail.addAttachmentFrombyte(b,"来自byte的附件.jpg");
    
  
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
      
      
      
       mymail.sendMail() ;
       WriteinfoToFile("邮件发出!");
    }
    catch (Exception ex){ WriteinfoToFile("邮件发送失败!"+ex.toString());}
  }

   //向ini文件中写提示信息
  private void WriteinfoToFile(String info){
    try{
      PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("mailinfo.txt",true)));
      pw.println(sysdate.toString()+" "+info);
      pw.close();
    }
    catch(IOException ei){
      System.out.println(sysdate.toString()+ " 向mailinfo.txt文件中写数据错误:"+ei.toString());
      System.exit(0);
    }
  }
}

posted on 2007-02-02 20:08 ☜♥☞MengChuChen 阅读(1768) 评论(1)  编辑  收藏 所属分类: javamail

FeedBack:
# 你好
2010-11-22 15:54 | 余风好
长须鲸努力掉书袋事故 GUDDSUDUSADSIAUDSFYDIDFSLIFAFSDYIO8YFDOS  回复  更多评论
  

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


网站导航: