javamail的一些总结

文章出处:http://www.gzu521.com/campus/article/program/200410/1231.htm

本文章对:  
发送普通邮件,接受普通邮件  
发送带有附件的邮件,接收带有附件的邮件  
发送html形式的邮件,接受html形式的邮件  
发送带有图片的邮件等做了一个总结。  
------------------------------------------------------------  
/*注意点:  
1。开发环境:jbuilder5,jdk1.2.2,Javamail  and  javabeans  activation  framework.  
task  1:download  the  latest  version  of  the  javamail  api  implementation  from  SUN.  
task  2:download  the  latest  version  of  the  javabeans  activation  framework  from  sun.  
task  3:unzip  the  downloaded  packages.  you  get  a  zip  file  for  all  platforms  for  both  packages.you  can  use  the  jar  tool  to  unzip  the  packages.  
task  4:add  the  mail.jar  file  from  the  javamail  1.2  download  and  the  activation.jar  file  from  the  javabeans  activation  framework  download  to  your  classpath.copy  the  files  to  your  extension  library  directory.  for  microsoft  windows,  and  using  the  default  installation  copy,  the  command  might  look  like  the  following:  
cd  javamail-1.2  
copy  mail.jar  jdk1.3jrelibext  
cd  jaf-1.0.1  
copy  activation.jar  jdk1.3jrelibext  
if  you  don’t  like  copying  the  files  to  the  exention  library  directory,  detailed  instructions  are  available  from  sun  for  setting  your  classpath  on  windows  nt.  
task  5:go  into  the  demo  directory  that  comes  with  the  javamail  api  implementation  and  compile  the  msgsend  program  to  send  a  test  message.  
task  6:execute  the  program  passing  in  a  from  address  with  the  -o  option,  your  smtp  server  with  the  -m  option,  and  the  to  address  (with  no  option).  you’ll  then  enter  the  subject,  the  text  of  your  message,  and  the  end-of-file  character  (ctrl-z)  to  signal  the  end  of  the  message  input.  
be  sure  to  replace  the  from  address,  smtp  server,  and  to  address.java  msgsend  -o  from@address  -m  smtp.server  to@address  
if  you  are  not  sure  of  your  smtp  server,  contact  your  system  adminstrator  or  check  with  your  internet  service  provider.  
task  7:check  to  make  sure  you  received  the  message  with  your  normal  mail  reader  (eudora,  outlook  express,  pine,  ...).  
*/  
 
package  mail_send_rec_byjm;  
 
import  java.awt.*;  
import  java.awt.event.*;  
import  javax.swing.*;  
import  com.borland.jbcl.layout.*;  
import  javax.mail.*;  
import  java.util.*;  
import  javax.mail.internet.*;  
import  java.io.*;  
import  javax.activation.*;  
 
 
   public      string  host="smtp.163.com";  
   public      string  username="abcdefg";  
   public      string  password="abcdefg";  
   public      string  mail_head_name="this  is  head  of  this  mail";  
   public      string  mail_head_value="this  is  head  of  this  mail";  
   public      string  mail_to="xyz@163.com";  
   public      string  mail_from="abcdefg@163.com";  
   public      string  mail_subject="this  is  the  subject  of  this  test  mail";  
   public      string  mail_body="this  is  the  mail_body  of  this  test  mail";  
   void  jbutton1_actionperformed(actionevent  e)  {  
             try  
                 {//此段代码用来发送普通电子邮件  
                       properties  props  =  new  properties();//获取系统环境  
                       authenticator  auth  =  new  email_autherticator();//进行邮件服务器用户认证  
 
                       props.put("mail.smtp.host",host);  
                       props.put("mail.smtp.auth","true");  
                       session  session  =  session.getdefaultinstance(props,auth);  
                     //设置session,和邮件服务器进行通讯。  
                       mimemessage  message  =  new  mimemessage(session);  
                       message.setcontent("hello","text/plain");//设置邮件格式  
                       message.setsubject(mail_subject);//设置邮件主题  
                       message.settext(mail_body);//设置邮件正文  
                       message.setheader(mail_head_name,mail_head_value);//设置邮件标题  
                       message.setsentdate(new  date());//设置邮件发送日期  
 
                       address  address  =  new  internetaddress(mail_from,"sunxiaoming");  
                       message.setfrom(address);  //设置邮件发送者的地址  
 
                 //如果要对邮件发送者进行多个参数的设置,可以用以下语句  
                 //  address  address[]  =  {new  internetaddress("sunxm@oaklet.co.jp","sunxmatoaklet"),new  internetaddress("firstsxm@hotmail.com","sunxmathotmail")};  
               //    message.addfrom(address);  
 
                       address  toaddress  =  new  internetaddress(mail_to);//设置邮件接收方的地址  
                       message.addrecipient(message.recipienttype.to,toaddress);  
               //    address  ccaddress  =  new  internetaddress("firstsxm@hotmail.com");//设置邮件抄送者的地址  
             //      message.addrecipient(message.recipienttype.cc,ccaddress);  
 
 
                       transport.send(message);//发送邮件  
         /*        //  to  get  a  specific  instance  from  the  session  for  your  protocol.pass  along  the  username  and  password  
                 //  (blank  if  unnecessary).send  the  message,and  close  the  connection;  
                       message.savechanges();  
                       transport  transport  =  session.gettransport("smtp");  
                       transport.connect(host,username,password);  
                       transport.sendmessage(message,message.getallrecipients());  
                       transport.close();  
*/  
                       system.out.println("send  ok!");  
                 }  
             catch(exception  ex)  
                 {  
                       system.out.println("faild"+ex);  
                 }  
   }


public  class  email_autherticator  extends  authenticator  
   {//此段代码用来进行服务器对用户的认证  
             public  email_autherticator()  
                 {  
                       super();  
                 }  
             public  passwordauthentication  getpasswordauthentication()  
                 {  
                         return  new  passwordauthentication(username,password);  
                 }  
   }  
 
   void  jbutton2_actionperformed(actionevent  e)  {  
       try  
         {//该程序为接收邮件  
             properties  props  =  system.getproperties();  //获取系统变量  
             authenticator  auth  =  new  email_autherticator();      
             props.put("mail.smtp.host",host);  
             props.put("mail.smtp.auth","true");  
             session  session  =  session.getdefaultinstance(props,auth);  //建立session  
             store  store  =  session.getstore("pop3");  
             store.connect(host,username,password);  
 
       //after  connecting  to  the  store,you  can  get  a  folder,which  must  be  opened  before  you  can  read  messages  from  it:  
             folder  folder  =  store.getfolder("inbox");//连接到store后,取得一个文件夹,一般默认的是index  
             folder.open(folder.read_write);//read_only为打开方式  
             message  message[]  =  folder.getmessages();//从文件夹获取邮件信息  
 
       //可以用两种方式去获得邮件信息,getcontent()用来获得邮件的主体信息。而writeto()可以用来获得邮件的全部信息,包括头部信息  
       //      system.out.println(((mimemessage)message).getcontent());  
             for  (int  i=0,n=message.length;i                  {  
                         
                       string  out_from_person  =  ((internetaddress)message.getfrom()[0]).getpersonal();  
                       string  out_from_address  =  ((internetaddress)message.getfrom()[0]).getaddress();  
                       system.out.println("from:"+out_from_person+" ");  
                       system.out.println("address:"+out_from_address+" ");  
 
                       string  out_subject  =  message.getsubject();  
                       system.out.println("subject:"+out_subject+" ");  
 
                       //以下代码用来获得邮件的正文信息  
                       part  messagepart  =  message;  
                       object  out_content  =  messagepart.getcontent();  
                       if  (out_content  instanceof  multipart)  
                           {  
                                 messagepart  =  ((multipart)out_content).getbodypart(0);  
                                 system.out.println("[  multipart  message  ]");  
                           }  
                       string  out_content_type  =  messagepart.getcontenttype();  
                       system.out.println("content:"+out_content_type);  
 
                       if  (out_content_type.startswith("text/plain")    |  |  out_content_type.startswith("text/html"))  
                           {  
                                   inputstream  ipstm  =  messagepart.getinputstream();  
                                   bufferedreader  bufreader  =  new  bufferedreader(new  inputstreamreader(ipstm));  
                                   string  thisline  =  bufreader.readline();  
                                   while  (thisline  !=  null)  
                                       {  
                                               system.out.println("thisline:  "+thisline);  
                                               thisline  =  bufreader.readline();  
                                       }  
                           }  
                       system.out.println("------------------------------------------------------------");  
                       message.setflag(flags.flag.deleted,true);//最后删除服务器端的邮件  
                 }  
                           //deleted,answered,draft,flagged,recent,seen,user  
             folder.close(true);//true的话,彻底删除已经标记为delete的邮件,如果为false的话,就不删除  
             store.close();//关闭  
         }  
       catch(exception  ej2)  
         {  
               system.out.println(ej2);  
         }  
   }  
 
   void  jbutton4_actionperformed(actionevent  e)  {  
       try  
         {//该程序为回复邮件  
             properties  props  =  system.getproperties();  //获取系统变量  
             authenticator  auth  =  new  email_autherticator();    //取得?ufffd衿魅现?  
             props.put("mail.smtp.host",host);  
             props.put("mail.smtp.auth","true");  
             session  session  =  session.getdefaultinstance(props,auth);  //建立session  
             store  store  =  session.getstore("pop3");  
             store.connect(host,username,password);  
 
             folder  folder  =  store.getfolder("inbox");  
             folder.open(folder.read_write);  
             message  message[]  =  folder.getmessages();  
 
             for  (int  i=0,n=message.length;i                  {  
   //                string  out_from_person  =  ((internetaddress)message.getfrom()[0]).getpersonal();//获取邮件发信人的署名  
     
                       string  out_from_address  =  ((internetaddress)message.getfrom()[0]).getaddress();  
                       system.out.println(out_from_address);  
 
                       message  forward  =  new  mimemessage(session);  
                       forward.setsubject("fwd:"+message.getsubject());  
                       forward.setfrom(new  internetaddress(mail_to));  
                       forward.addrecipient(message.recipienttype.to,new  internetaddress(out_from_address));  
 
                       bodypart  messagebodypart  =  new  mimebodypart();  
                       messagebodypart.settext("here  you  go  with  the  original  message:

");  
 
                       multipart  multipart  =  new  mimemultipart();  
                       multipart.addbodypart(messagebodypart);  
 
                       messagebodypart  =  new  mimebodypart();  
                       messagebodypart.setdatahandler(message.getdatahandler());  
 
                       multipart.addbodypart(messagebodypart);  
                       forward.setcontent(multipart);  
 
                       transport.send(forward);  
                       message.setflag(flags.flag.deleted,true);//deleted,answered,draft,flagged,recent,seen,user  
                 }  
             folder.close(true);  
             store.close();//关闭  
         }  
       catch(exception  ej2)  
         {  
               system.out.println(ej2);  
         }  
 
   }
void  jbutton5_actionperformed(actionevent  e)  {  
             try  
                 {//此段代码用来发送带有附件的邮件  
                       properties  props  =  new  properties();  
                       authenticator  auth  =  new  email_autherticator();  
 
                       props.put("mail.smtp.host",host);  
                       props.put("mail.smtp.auth","true");  
                       session  session  =  session.getdefaultinstance(props,auth);  
                       mimemessage  message  =  new  mimemessage(session);  
                       message.setcontent("hello","text/plain");  
                       message.setsubject(mail_subject);  
                       message.settext(mail_body);  
                       message.setheader(mail_head_name,mail_head_value);  
                       message.setsentdate(new  date());  
                       message.setfrom(new  internetaddress(mail_from,"sunxiaoming"));  //to  signal  man  
//原理:可以将邮件看成有多个部分组成的,如正文是一个部分,附件也是一个部分,所以用bodypart来设置邮件的格式  
                       message.addrecipient(message.recipienttype.to,new  internetaddress(mail_to));  
                       bodypart  messagebodypart  =  new  mimebodypart();  
                       messagebodypart.settext("pardon  ideas");  
                       multipart  multipart  =  new  mimemultipart();  
                       multipart.addbodypart(messagebodypart);  
 
                       messagebodypart  =  new  mimebodypart();  
                       datasource  source  =  new  filedatasource("./20020423/test.zip");//此处设置邮件的附件  
                       messagebodypart.setdatahandler(new  datahandler(source));  
                       messagebodypart.setfilename("test.zip");  
                       multipart.addbodypart(messagebodypart);  
                       message.setcontent(multipart);  
                       transport.send(message);  
                       system.out.println("send  ok!");  
                 }  
             catch(exception  ex)  
                 {  
                       system.out.println("faild"+ex);  
                 }  
 
   }  
 
   void  jbutton6_actionperformed(actionevent  e)  {  
       try  
         {//该程序为接受带有附件的邮件的代码  
             properties  props  =  system.getproperties();    
             authenticator  auth  =  new  email_autherticator();      
             props.put("mail.smtp.host",host);  
             props.put("mail.smtp.auth","true");  
             session  session  =  session.getdefaultinstance(props,auth);  //建立session  
             store  store  =  session.getstore("pop3");  
             store.connect(host,username,password);  
 
       //after  connecting  to  the  store,you  can  get  a  folder,which  must  be  opened  before  you  can  read  messages  from  it:  
             folder  folder  =  store.getfolder("inbox");  
             folder.open(folder.read_write);  
             message  message[]  =  folder.getmessages();  
 
             for  (int  i=0,n=message.length;i                  {  
                       //获得邮件的部分信息,如头部信息,送信人的署名,送信人的邮件地址  
                       string  out_from_person  =  ((internetaddress)message.getfrom()[0]).getpersonal();  
                       string  out_from_address  =  ((internetaddress)message.getfrom()[0]).getaddress();  
                       system.out.println("from:"+out_from_person+" ");  
                       system.out.println("address:"+out_from_address+" ");  
                       string  out_subject  =  message.getsubject();  
                       system.out.println("subject:"+out_subject+" ");  
 
                       //以下代码用来获取邮件的主体信息  
                       part  messagepart  =  message;  
                       object  out_content  =  messagepart.getcontent();  
                       if  (out_content  instanceof  multipart)  
                           {  
                                 messagepart  =  ((multipart)out_content).getbodypart(0);  
                                 system.out.println("[  multipart  message  ]");  
                           }  
                       string  out_content_type  =  messagepart.getcontenttype();  
                       system.out.println("content:"+out_content_type);  
 
                       if  (out_content_type.startswith("text/plain")    |  |  out_content_type.startswith("text/html"))  
                           {  
                                   inputstream  ipstm  =  messagepart.getinputstream();  
                                   bufferedreader  bufreader  =  new  bufferedreader(new  inputstreamreader(ipstm));  
                                   string  thisline  =  bufreader.readline();  
                                   while  (thisline  !=  null)  
                                       {  
                                               system.out.println("thisline:  "+thisline);  
                                               thisline  =  bufreader.readline();  
                                       }  
                           }  
                       //获取附件  
                       multipart  mp  =  (multipart)message.getcontent();  
                       for  (int  j=0,m=mp.getcount();j                            {  
                                 system.out.println("***"+m+"***");  
                                 part  part  =  mp.getbodypart(j);  
                                 string  disposition  =  part.getdisposition();  
                                 if  ((disposition  !=  null)  &&  ((disposition.equals(part.attachment))    |  |  (disposition.equals(part.inline))))  
                                     {  
 
                                     //以下代码将获得的附件保存到当前目录下,以part.getfilename()为文件名,也既是附件的名称。  
                                             file  filename  =  new  file(part.getfilename());  
                                             for  (int  k=0;filename.exists();k++)  
                                                 {  
                                                           filename  =  new  file(part.getfilename()+k);  
                                                 }  
                                             fileoutputstream  myfileoutputstream  =  new  fileoutputstream(filename);  
                                             int  chunk  =  part.getsize();//获得附件的大小,不一定很准确。  
 
                                             byte  []  buffer  =  new  byte[chunk];  
                                             inputstream  instream  =  part.getinputstream();  
                                             instream.read(buffer,0,chunk);  
                                             myfileoutputstream.write(buffer,0,chunk);  
                                             instream.close();  
                                             myfileoutputstream.close();  
                                     }  
                           }  
                       system.out.println("------------------------------------------------------------");  
                       message.setflag(flags.flag.deleted,true);  
                 }  
             folder.close(true);  
             store.close();//关闭  
         }  
       catch(exception  ej2)  
         {  
               system.out.println(ej2);  
         }  
   }  
void  jbutton8_actionperformed(actionevent  e)  {  
             try  
                 {//此段代码用来发送带有html信息的邮件  
                       properties  props  =  new  properties();  
                       authenticator  auth  =  new  email_autherticator();  
                       props.put("mail.smtp.host",host);  
                       props.put("mail.smtp.auth","true");  
                       session  session  =  session.getdefaultinstance(props,auth);  
                       mimemessage  message  =  new  mimemessage(session);  
                   //设置邮件正文  
                       string  htmltext="
hello
"+"http://www.sina.com.cn";  target="_blank">click  me  please!";  
                       message.setcontent(htmltext,"text/html");//text/plain设置邮件的格式因为是带有html文档的,所以用text/html格式  
 
                       message.setsubject(mail_subject);  
                 //      message.settext(mail_body);在使用message.setcontent()时候,好象不能用message.settext()  
                       message.setheader(mail_head_name,mail_head_value);  
                       message.setsentdate(new  date());  
                       address  address  =  new  internetaddress(mail_from,"sunxiaoming");  
                       message.setfrom(address);    
                       address  toaddress  =  new  internetaddress(mail_to);  
                       message.addrecipient(message.recipienttype.to,toaddress);  
                       transport.send(message);  
                       system.out.println("send  ok!");  
                 }  
             catch(exception  ex)  
                 {  
                       system.out.println("faild"+ex);  
                 }  
 
   }  
 
   void  jbutton9_actionperformed(actionevent  e)  {  
             try  
                 {//此段代码用来发送带有图片的邮件  
                       string  file  =  "./20020423/test.gif";  
                       properties  props  =  new  properties();  
                       authenticator  auth  =  new  email_autherticator();  
 
                       props.put("mail.smtp.host",host);  
                       props.put("mail.smtp.auth","true");  
                       session  session  =  session.getdefaultinstance(props,auth);  
                       mimemessage  message  =  new  mimemessage(session);  
 
                       message.setsubject("embedded  image");  
                       address  address  =  new  internetaddress(mail_from,"sunxiaoming");  
                       message.setfrom(address);    
                       address  toaddress  =  new  internetaddress(mail_to);  
                       message.addrecipient(message.recipienttype.to,toaddress);  
                       message.setheader(mail_head_name,mail_head_value);  
                       message.setsentdate(new  date());  
 
                       bodypart  messagebodypart  =  new  mimebodypart();  
                       string  htmltext  =  "
"+"";//加入图片  
                       messagebodypart.setcontent(htmltext,"text/html");  
                 //原理同发送附件一样,将邮件看成有多个部分组成的,先设置每一个部分,然后再全部将它们合起来即可。  
                       //create  a  related  multi-part  to  combine  the  parts  
                       mimemultipart  multipart  =  new  mimemultipart("related");  
                       multipart.addbodypart(messagebodypart);  
 
                       //create  part  for  the  image  
                       messagebodypart  =  new  mimebodypart();  
 
                       //fetch  the  image  and  associate  to  part  
                       datasource  fds  =  new  filedatasource(file);  
                       messagebodypart.setdatahandler(new  datahandler(fds));  
                       messagebodypart.setheader("content-id","memememe");  
 
                       //add  part  to  multi-part  
                       multipart.addbodypart(messagebodypart);  
 
                       //associate  multi-part  with  message  
                       message.setcontent(multipart);  
 
                       transport.send(message);  
                       system.out.println("send  ok!");  
                 }  
             catch(exception  ex)  
                 {  
                       system.out.println("faild"+ex);  
                 }  
 
   }  
 void  jbutton7_actionperformed(actionevent  e)  {  
       try  
         {//该程序用来接受带有html信息的邮件  
             properties  props  =  system.getproperties();    
             authenticator  auth  =  new  email_autherticator();  
             props.put("mail.smtp.host",host);  
             props.put("mail.smtp.auth","true");  
             session  session  =  session.getdefaultinstance(props,auth);  
             store  store  =  session.getstore("pop3");  
             store.connect(host,username,password);  
 
       //after  connecting  to  the  store,you  can  get  a  folder,which  must  be  opened  before  you  can  read  messages  from  it:  
             folder  folder  =  store.getfolder("inbox");  
             folder.open(folder.read_write);  
             message  message[]  =  folder.getmessages();  
 
             for  (int  i=0,n=message.length;i //                  for  (int  i=0,n=1;i                  {  
                       string  out_from_person  =  ((internetaddress)message.getfrom()[0]).getpersonal();  
                       string  out_from_address  =  ((internetaddress)message.getfrom()[0]).getaddress();  
                       system.out.println("from:"+out_from_person+" ");  
                       system.out.println("address:"+out_from_address+" ");  
 
                       string  out_subject  =  message.getsubject();  
                       system.out.println("subject:"+out_subject+" ");  
 
                       //获取邮件的信息,并且对其每一部分进行操作  
                       part  messagepart  =  message;  
                       object  out_content  =  messagepart.getcontent();  
                       if  (out_content  instanceof  multipart)  
                           {  
                                 messagepart  =  ((multipart)out_content).getbodypart(0);  
                                 system.out.println("[  multipart  message  ]");  
                           }  
                       string  out_content_type  =  messagepart.getcontenttype();  
                       system.out.println("content:"+out_content_type);  
 
                       jeditorpane1.settext("");//将其显示在jeditorpanel上  
                       jeditorpane1.setcontenttype("text/html");  
                       jeditorpane1.settext((string)out_content);  
                       jeditorpane1.seteditable(false);  
 
/*  
                       if  (out_content_type.startswith("text/plain")    |  |  out_content_type.startswith("text/html"))  
                           {  
                                   inputstream  ipstm  =  messagepart.getinputstream();  
                                   bufferedreader  bufreader  =  new  bufferedreader(new  inputstreamreader(ipstm));  
                                   string  thisline  =  bufreader.readline();  
                                   while  (thisline  !=  null)  
                                       {  
                                               system.out.println("thisline:  "+thisline);  
                                               thisline  =  bufreader.readline();  
                                       }  
                           }  
*/  
                       system.out.println("------------------------------------------------------------");  
                       message.setflag(flags.flag.deleted,true);  
                 }  
             folder.close(true);  
             store.close();  
         }  
       catch(exception  ej2)  
         {  
               system.out.println(ej2);  
         }  
 
   }
本文来自学习网(www.gzu521.com),原文地址:http://www.gzu521.com/campus/article/program/200410/1231.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值