In my current project, there is a requirment----having to add a mail function. And the task is assigned to me. At first, I feel a little nervous: I did not do the mail function before, will the function be difficult, can I finish the task on time?  Finally, I worked it out with my workmate. It's so easy, maybe the core part just several line code....

Here, I post some code of it. When you see it, you must have the same feeling as me, so easy. But the condition is: you are not write mail coding before and also don't think how to relealize it before.

Come on, please see the code below
There is another propertity file just used config stempsever information and so on.

import  java.util.ArrayList;
import  java.util.Calendar;
import  java.util.Properties;
import  java.util.ResourceBundle;
import  java.util.Vector;
import  javax.activation.DataHandler;
import  javax.activation.FileDataSource;
import  javax.mail.Address;
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  javax.mail.Authenticator;
import  javax.mail.PasswordAuthentication;
import  org.apache.commons.logging.Log;
import  org.apache.commons.logging.LogFactory;


public   class  PESendMail  {
    
static   final  String IniFile  =   " smtp " ;
    Log log 
=  LogFactory.getLog( " Java Mail " );
    
private  String SendEmail  =   " true " ;
    
private  String Debug  =   " true " ;
    
private  String SmtpServer  =   "" ;
    
private  String SmtpServerAuth  =   " true " ;
    
private  String SmtpUser  =   "" ;
    
private  String SmtpUserPass  =   "" ;
    
private  String DisplayName  =   " Test " ;
    
private  String[] CC;
    
static   private  String StartSite  =   "" ;
    
static  PESendMail instance  =   new  PESendMail();
    
/**  Mail Subject.  */
    
private  String Subject  =   "" ;
    
/**  Mail Content.  */
    
private  String Content  =   "" ;
    
/**  Receiver List.  */
    
private  String[] To;
    
/**  mail priority.  */
    
private  String Priorty  =   " 3 " ;
    
/**  CharSet.  */
    
private  String CharSet  =   "" ;
    
private  String strTypeSet  =   " text/plain;charset=UTF-8 " ;
    
/**  Error Message.  */
    
private  String ErrMessage  =   " Mail sending failed " ;
    
private     String From  =   "" ;
    
private  String _strAttachment  =   "" ;
    
private  String _strFielName  =   "" ;
    
private  String[] _address;
    
    
public  PESendMail() {
        init();
    }

    
public  PESendMail(String strContent,String strSubject,String[] strTo) {
        init();
        
this .Content  =  strContent;
        
this .Subject  =  strSubject;
        
this .To  =  strTo;
    }

    
public  PESendMail(String strContent,String strSubject,String[] strTo, String fromAddresss) {
        init();
        
this .Content  =  strContent;
        
this .Subject  =  strSubject;
        
this .To  =  strTo;
        
this .From  =  fromAddresss;
    }

    
public  PESendMail( String strContent,String strSubject, String strSmtpServer, String[] strTo, String fromAddresss )  {
        init();
        
this .Content  =  strContent;
        
this .Subject  =  strSubject;
        
this .SmtpServer  =  strSmtpServer;
        
this .To  =  strTo;
        
this .From  =  fromAddresss;
    }

    
public  PESendMail( String strContent,String strSubject, String strSmtpServer, String[] strTo,String[] cc, String fromAddresss )  {
        init();
        
this .Content  =  strContent;
        
this .Subject     =  strSubject;
        
this .SmtpServer  =  strSmtpServer;
        
this .To  =  strTo;
        
this .CC  =  cc;
        
this .From  =  fromAddresss;
     }


    
void  init() {
        ResourceBundle bundle 
=  ResourceBundle.getBundle(IniFile);
        SendEmail
= getKeyString(bundle, " SendEmail " );
        Debug
= getKeyString(bundle, " Debug " );
        SmtpServer
= getKeyString(bundle, " SMTPServer " );
        SmtpServerAuth
= getKeyString(bundle, " SMTPAuth " );
        SmtpUser
= getKeyString(bundle, " SMTPUser " );
        SmtpUserPass
= getKeyString(bundle, " UserPass " );
        DisplayName
= getKeyString(bundle, " DisplayName " );
        Vector vctCC
= new  Vector();
        
for ( int  i = 1 ;i <= 10 ;i ++ ) {
            String ccTmp
= " CCAddr " + i;
            String ccAddr
= getKeyString(bundle,ccTmp);
            
if (ccAddr != null   &&  ccAddr.trim().length() > 0 )
                vctCC.add(ccAddr);
        }

        
if (vctCC.size() > 0 ) {
            CC
= new  String[vctCC.size()];
            vctCC.toArray(CC);
        }

        StartSite
= getKeyString(bundle, " StartSite " );
      
if (StartSite.length() == 0 )
            StartSite
= " http://sso01-gecisasia.ge.com/login.fcc " ;
  }

    
    String getKeyString(ResourceBundle bundle,String key)
{
        String ret
= "" ;
        
try {
            ret
= bundle.getString(key);
        }
catch (Exception e) {ret = "" ;}
        
return  ret;
    }

    
   
    
public   boolean  MailSend()  {

        
if (To.length  > 0  )
            log.info(
" Email to  " + To[ 0 + " \r\n subject:  " + Subject);

          
try   {
            Session session 
=   null ;
            Properties props 
=  System.getProperties();
            props.put(
" mail.smtp.host " ,SmtpServer);
            
if (SmtpServerAuth.compareToIgnoreCase( " true " ) == 0 ) {
                props.put(
" mail.smtp.auth " " true " );
                session 
=  Session.getInstance(props, new  SmtpAuthenticator(SmtpUser,SmtpUserPass));
            }

            
else
                session 
=  Session.getInstance(props, null );
            
if (Debug.compareToIgnoreCase( " true " ) == 0 )
                session.setDebug(
true );

            
//  Define message
            MimeMessage message  =   new  MimeMessage(session);
            
// message.setFrom(new InternetAddress(From,"GE StatTax Administrator"));
            message.setFrom( new  InternetAddress(SmtpUser,DisplayName));

            Address[] aToddress 
=   new  Address[To.length];
            
for  ( int  i = 0 ;i < To.length;i ++ )
                aToddress[i] 
=   new  InternetAddress(To[i]);
            
// To Address
            message.addRecipients(Message.RecipientType.TO, aToddress);

            
if (CC != null   &&  CC.length > 0 ) {
                 Address[] CCAddress 
=   new  Address[ CC.length];
                 
for  ( int  i  =   0 ; i  <   CC.length; i ++ {
                     CCAddress[i] 
=   new  InternetAddress( CC[i]);
                 }

                 message.addRecipients(Message.RecipientType.CC, CCAddress);
            }


            message.setSubject(MimeUtility.encodeText(Subject, 
" SHIFT_JIS " " B " ));
            message.setSentDate(
new  java.util.Date());     //
            MimeMultipart multipart  =   new  MimeMultipart();

            
if  ( null != _strAttachment  &&   ! "" .equals(_strAttachment))  {
                MimeBodyPart mbp 
=   new  MimeBodyPart();
                FileDataSource fd 
=   new  FileDataSource(_strAttachment);
                DataHandler dAttach 
=   new  DataHandler(fd);
                
// mbp.setContent(dAttach.getContent(),dAttach.getContentType());
                mbp.setDataHandler(dAttach);
                
// mbp.setFileName(MimeUtility.encodeText(fd.getName(),"iso-2022-jp","B"));
                mbp.setFileName(MimeUtility.encodeText(_strFielName, " iso-8859-1 " , " B " ));
                multipart.addBodyPart(mbp);
            }


            MimeBodyPart mbpContent 
=   new  MimeBodyPart();
            mbpContent.setContent(Content,strTypeSet);
            mbpContent.addHeader(
" X-Priority " ,Priorty);
            multipart.addBodyPart(mbpContent);

            message.setContent(multipart);
            Transport.send(message);

        }
  catch  (Exception e)  {
            ErrMessage 
=   " error " + e.toString();
            System.out.println(
" error occured  " + ErrMessage);
            
return   false ;
        }

        
return   true ;
    }


    
/**
     * set Attachment Path
     *
     * 
@param  strAttachment     Attachment Path
     
*/

    
public   void  setattachmentPath(String strAttachment)  {
        _strAttachment 
=  strAttachment;
    }


    
/**
     * set Attachment Path
     *
     * 
@param  strAttachment     Attachment Path
     
*/

    
public   void  setFileName(String fileName)  {
        _strFielName 
=  fileName;
    }


    
public   void  setCCAddress(String[] address)  {
        _address 
=  address;
    }


    
public   void  setContentType(String type)  {
        strTypeSet 
=  type;
    }

    

    
class  SmtpAuthenticator  extends  Authenticator  {
        String smtpUser;
        String password;
        
public   SmtpAuthenticator(String user,String pass) {
            smtpUser
= user;
            password
= pass;
        }

        
protected  PasswordAuthentication getPasswordAuthentication()  {
            
return   new  PasswordAuthentication(smtpUser,password);
        }

      }

    
public  String getErrMsg()  {
        
return  ErrMessage;
    }

    
     public   static   void  SendToDirectManger(String Appellation, String[] to) throws  Exception {
        
final  String strSubject = " Test For Mail Fuynction " ;
        
final  String strContent = " Dear  "   + Appellation + " ,<br> "
                
+ "Please ignore the mail, it's just used for test"
                
+ " <br><br>  "
                
+ " Regards,<br> "
                
+ "A dministrator<br> "
                
+ " <a href=' " + StartSite + " '> " + StartSite + " </a> " ;
        PESendMail peSendMail  =   new  PESendMail(strContent, strSubject,to);
        peSendMail.setContentType(
" text/html " );
        
if  ( ! peSendMail.MailSend())  {
        }

    }

    
 
public   static   void  main(String[] args)  {
        
//  TODO Auto-generated method stub
         try {
            
// test case for mail function             
             String[]  strToAdd 
=   { testAddress@hotmail.com.com } ;
            SendToDirectManger(
" Allen " " D00001 " " Pearl " " 2006/05/16 " ,strToAdd);
            
        }
catch (Exception e) {
            e.printStackTrace();
        }

        
    }

    
    

}


smpt.properties file :

 

#SMTP Email Send

#effecting email sending
, set false not send email 
SendEmail
=true

#display javamail debug info
Debug
=true

#server parameter 
SMTPServer
=yoursetting
SMTPAuth
=yoursetting

SMTPUser
=yoursetting
UserPass
=yoursetting
DisplayName
=Test

#start sie url
StartSite
=http://test.com

#CC addrs
, for testing 
CCAddr1
=jolly@sohu.com
CCAddr2
=pig@elong.com

.
posted on 2006-05-24 14:24 Pearl And Allen 阅读(214) 评论(0)  编辑  收藏 所属分类: J2EE Technology

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


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问