一個發郵件的類,帶驗證功能,可以發html內容,可以添加附件,並解決附件亂碼問題。

//文件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;
    }

    public InputStream getInputStream() 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[]格式,然後使用該方法添加到郵件的附件中,進行發送
       InputStream inputStream=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);
    }
  }
}


本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/cngkqy/archive/2006/05/23/750934.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章