posts - 18,comments - 26,trackbacks - 0

/*=========================================================
  * @Programing Name: SendMail.java
  * @Author:          Wang weiPing
  * @Program Date:    2004-02-02
  * @E-Mail:          wangwp@mailer.com.cn
  * @MobilePhone:     13810862095
  * @Address:         北京市海淀区知春路23号863软件园903室
  ********************************************
  *include classes: *SendMail.class       *
  *                 *MailAuthenticator.class *
  *                 *MailSendHtml.class      *
  *                 *MailSendText.class      *
  ********************************************
  *=========================================================
  */


package chundiwebmail;

import java.util.Properties;
import java.util.Date;
import java.util.ArrayList;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

abstract class SendMail{
    
    protected BodyPart messageBodyPart = 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 MailAuthenticator authenticator = null;

    protected String mailSubject ="";
    protected Date mailSendDate = null;
    
    public SendMail(String smtpHost,String username,String password){

        mailProperties.put("mail.smtp.host",smtpHost);
        System.out.println("smtpHost="+smtpHost);
       
       
        mailProperties.put("mail.smtp.auth","true"); //设置smtp认证,很关键的一句
        authenticator = new MailAuthenticator(username,password);
        mailSession = Session.getDefaultInstance(mailProperties,authenticator);
        mailMessage = new MimeMessage(mailSession);
        messageBodyPart = new MimeBodyPart();
    }

    //设置邮件主题
    public void setSubject(String mailSubject)throws MessagingException{
        this.mailSubject = mailSubject;
        mailMessage.setSubject(mailSubject);
    }
    //所有子类都需要实现的抽象方法,为了支持不同的邮件类型
    protected abstract void setMailContent(String mailContent)throws MessagingException;
    
    //设置邮件发送日期
    public void setSendDate(Date sendDate)throws MessagingException{
        this.mailSendDate = sendDate;
        mailMessage.setSentDate(sendDate);
    }

    //设置邮件发送附件
    public void setAttachments(String attachmentName)throws MessagingException{
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        int index = attachmentName.lastIndexOf('\\');
        String attachmentRealName = attachmentName.substring(index+1);
        messageBodyPart.setFileName(attachmentRealName);
        multipart.addBodyPart(messageBodyPart);
    }
    
    //设置发件人地址
    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{
        if(mailToAddress == null){
            System.out.println("请你必须你填写收件人地址!");
            System.exit(1);
        }
        else{
            mailMessage.setContent(multipart);
            System.out.println("正在发送邮件,请稍候.......");
            Transport.send(mailMessage);
            System.out.println("恭喜你,邮件已经成功发送!");
        }
    }

}
//现在的大部分的邮件服务器都要求有身份验证,所以需要此类实现验证功能
class MailAuthenticator extends Authenticator{

    private String username = null;
    private String userpasswd = null;

    public MailAuthenticator(){}
    public MailAuthenticator(String username,String userpasswd){
        this.username = username;
        this.userpasswd = userpasswd;
    }
    
    public void setUserName(String username){
        this.username = username;
    }

    public void setPassword(String password){
        this.userpasswd = password;
    }

    public PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(username,userpasswd);
    }
}

//为了使此邮件发送程序能够支持可扩展性,把发送邮件的类型放到子类中来,
//以便支持更多的邮件类型,比如语音邮件,视频邮件等......

//1.发送纯文本文件的的子类MailSendText.class

class MailSendText extends SendMail{

    public MailSendText(String smtpHost,String username,String password){
        super(smtpHost,username,password);
        multipart = new MimeMultipart();
    }

    public void setMailContent(String mailContent)throws MessagingException{
        messageBodyPart.setText(mailContent);
        multipart.addBodyPart(messageBodyPart);
    }
}

//2.发送html格式的子类MailSendHtml.class
class MailSendHtml extends SendMail{
    private ArrayList arrayList1 = new ArrayList();
    private ArrayList arrayList2 = new ArrayList();

    public MailSendHtml(String smtpHost,String username,String password){
        super(smtpHost,username,password);
        multipart = new MimeMultipart("related");
    }

    public void setMailContent(String mailContent)throws MessagingException{
        String htmlContent = getContent("<img src=",mailContent);
        System.out.println(htmlContent);//1
        messageBodyPart.setContent(htmlContent,"text/html");
        multipart.addBodyPart(messageBodyPart);
        //调用处理html文件中的图片方法
        processHtmlImage(mailContent);
    }
    //处理html页面上的图片方法如下:
    private void processHtmlImage(String mailContent)throws MessagingException{
         for(int i=0;i<arrayList1.size();i++){
             messageBodyPart = new MimeBodyPart();
             DataSource source = new FileDataSource((String)arrayList1.get(i));
             messageBodyPart.setDataHandler(new DataHandler(source));
             String contentId = "<"+(String)arrayList2.get(i)+">";
             System.out.println(contentId);
             messageBodyPart.setHeader("Content-ID",contentId);
             messageBodyPart.setFileName((String)arrayList1.get(i));
             multipart.addBodyPart(messageBodyPart);
         }
    }
    //处理要发送的html文件,主要是针对html文件中的图片
    private String getContent(String searchString,String mailContent){
        String afterReplaceStr = "";
        for(int i=0;i<mailContent.length();i++){
            for(int j=i+1;j<mailContent.length();j++){
                String searResult = mailContent.substring(i,j);
                if(searResult.equalsIgnoreCase(searchString)){
                    String subString = mailContent.substring(j);
                    int flagIndex = subString.indexOf('>');
                    String replaceStr = subString.substring(1,flagIndex-1);
                    if(replaceStr.indexOf("http://") != -1){
                        System.out.println(replaceStr);
                        System.out.println("不需要处理图片!");
                    }
                    else{

                        arrayList1.add(replaceStr);
                    }
                }
            }
        }
        //在html文件中用"cid:"+Content-ID来替换原来的图片链接
        for(int m=0;m<arrayList1.size();m++){
            arrayList2.add(createRandomStr());
            String addString = "cid:"+(String)arrayList2.get(m);
            afterReplaceStr = mailContent.replaceAll((String)arrayList1.get(m),addString);
        }
        return afterReplaceStr;
    }
    //产生一个随机字符串,为了给图片设定Content-ID值
    private String createRandomStr(){
        char []randomChar = new char[8];
        for(int i=0;i<8;i++){
            randomChar[i]=(char)(Math.random()*26+'a');
        }
        String replaceStr = new String(randomChar);
        return replaceStr;
    }

}

/*=============================================================================
下面是此电子邮件发送程序的简单测试程序:
 */
//package chundiwebmail;

//import java.util.Date;
public class SendMailTest{

    public static void main(String args[]){
      //  String []toAddress = {"sunmin_cs@yahoo.com.cn"};
        String []toAddress = {"mailtestonly@163.com"};
       // String []toAddress = {"sunmin@sm.swust.edu.cn"};
       // String []toAddress = {"test@tx.swust.edu.cn"};
       
       
       // SendMail sendmail = new MailSendHtml("smtp.163.com","mailtestonly","123456");
      
        SendMail sendmail = new MailSendHtml("sm.swust.edu.cn","lyh","2");
        try{
            sendmail.setSubject("HelloWorld");
            sendmail.setSendDate(new Date());
            //String plainText = "Welcome to use this Mail-Send program!";
            //******************************************************
            //String htmlText = "<H1>HelloWorld</H1>"+
            //       "<img src=\"1.jpg\">"
            //       +"<font size=\"5\">xxx</font>";
            //******************************************************
            String htmlText="<body><img src=\"1.bmp\"><font size=\"5\">xxx</font></body>";
          
           // String htmlText="sdfsdf";
                   
                    //"<img src=\"http://www.yahoo.com.cn/image1.jpg\">";
            //sendmail.setMailContent(plainText);
            sendmail.setMailContent(htmlText);
            //sendmail.setAttachments("D:\\wwpdev\\attach.jsp");
           
           // sendmail.setMailFrom("mailtestonly@163.com");
           
           // sendmail.setMailFrom("sunmin@localhost.com");
            sendmail.setMailFrom("lyh@sm.swust.edu.cn");
            sendmail.setMailTo(toAddress,"to");
           // sendmail.setMailTo(toAddress,"cc");
            sendmail.sendMail();
        }
        catch(Exception ex){ ex.printStackTrace();}
    }
}
//=============================================================================
 //   [/pre]

posted on 2005-06-08 21:50 瘦猴 阅读(332) 评论(0)  编辑  收藏

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


网站导航: