正文

Javamail操作指南2006-05-09 16:06:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/sword2008/13781.html

分享到:

Bromon原创 请尊重版权   怎样才算比较完整的Javamail操作指南?我想应该包括绝大多数基本的email操作,能够应付一般的应用。在本指南中打算囊括以下内容:  ● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证  ● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件  我想有了上述功能的介绍,应该可以应付很多email的相关应用了。所以请允许我给本文拟了一个比较狂妄的名字,这样才能保证收视率,。还是那句话,写这个post的原因就是没有在网上看到更全面的,你看过的话记得要告诉我。  下面的所有例子都经过实际测试,你可以说它写得不够OO,不够plugable,但是它的确是可以参考的。自从有了javamail,发垃圾邮件就方便多了。本文代码多说明少,这倒不是我偷懒,而是很多东西都涉及pop3等协议的规范,如果不了解这些规范的话,由的东西我实在不知道怎么跟你解释;如果了解的话,那我基本上就不用再解释。所以本着实用的原则就省略了,由兴趣的话自己去翻翻协议规范。  废话少说,首先需要配置环境。需要的包是mail.jar和activation.jar。高版本的J2SDK EE自带。地址嘛,再java.sun.com上搜索一下,很容易找到。放到classpath中就KO。  一、 邮件的发送  下面了弄个发邮件的Hello World,热热身:  /*************  Name:TextMailSender.java  Author:Bromon  Version:1.0  Date:2004-4-26  Note:发送email到bromon@163.com,需要安装SMTP服务器  *************/  package org.bromon.mail;  import javax.mail.*;  import javax.mail.internet.*;  import java.util.*;  public class TextMailSender  {  public static void main(String args[])  {   try   {    Properties prop=new Properties();    //指定要使用的SMTP服务器为bromon2k    prop.put("mail.smtp.host","bromon2k");    Session mailSession=Session.getDefaultInstance(prop);    //发件人地址    InternetAddress from=new InternetAddress("bromon@bromon2k");    //收件人地址    InternetAddress to=new InternetAddress("bromon@163.com");        MimeMessage msg=new MimeMessage(mailSession);    msg.setFrom(from);    msg.addRecipient(javax.mail.Message.RecipientType.TO,to);    //发信日期    msg.setSentDate(new java.util.Date());    //title    msg.setSubject("你好");    //邮件正文    msg.setText("hello,bromon");    Transport.send(msg);   }catch(Exception e)   {    System.out.println(e);   }  }  }   程序很简单,但是它是不能运行的(倒)。除非你的机器上安装了一个SMTP服务器,而且你的机器还叫做bromon2k。写这么一段不能执行的程序不是为了找打,而是让各位对javamail有个基本印象,我就懒得改了。下面演示的是如何通过163、sohu等email服务商提供的免费邮箱来发邮件,基本操作和上面的一样,只是多一个SMTP验证而已:  /*  * Created on 2004-4-26  */  package org.bromon.mail;  import javax.mail.*;  import java.util.*;  import javax.mail.internet.*;  /**  * @author Bromon  */  public class SenderWithSMTPVer  {  String host="";  String user="";  String password="";  public void setHost(String host)  {   this.host=host;  }  public void setAccount(String user,String password)  {   this.user=user;   this.password=password;  }  public void send(String from,String to,String subject,String content)  {   Properties props = new Properties();   props.put("mail.smtp.host", host);//指定SMTP服务器   props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证   try   {    Session mailSession = Session.getDefaultInstance(props);        mailSession.setDebug(true);//是否在控制台显示debug信息        Message message=new MimeMessage(mailSession);    message.setFrom(new InternetAddress(from));//发件人    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人        message.setSubject(subject);//邮件主题    message.setText(content);//邮件内容    message.saveChanges();        Transport transport = mailSession.getTransport("smtp");    transport.connect(host, user, password);    transport.sendMessage(message, message.getAllRecipients());    transport.close();   }catch(Exception e)   {    System.out.println(e);   }     }  public static void main(String args[])  {   SenderWithSMTPVer sm=new SenderWithSMTPVer();   sm.setHost("smtp.163.com");//指定要使用的邮件服务器   sm.setAccount("abc","123");//指定帐号和密码   /*  * @param String 发件人的地址    * @param String 收件人地址    * @param String 邮件标题    * @param String 邮件正文   */   sm.send("abc@163.com","bromon@163.com","标题","内容");  }  }   这段程序好像也不需要解释了吧,把SMTP地址、帐号、密码等配置信息写到Properties里面,Java里面很多API都需要这么干,比如再程序中加入对代理服务器的支持等。  上面的程序修改一下服务器地址、帐号、密码就可以使用,非常简单。  如何发送一个HTML格式的Email呢?也很简单,再邮件正文中写入HTML代码,然后指定邮件的ContentType就OK,下面只给出关键代码:  ………..  MimeMessage msg=new MimeMessage(mailSession);  msg.setContent(content,"text/html");  msg.setText(“<html><body><h1>下面的,你们好吗?</body></html>”);  ………..  下面是发送带有附件的email,稍微复杂一点,而且和前面的程序有一些不同,请仔细一点,同时需要一点IO的知识。相同的代码就不在列出,只写关键部分,谁都想偷懒不是?  import javax.mail.*;  import javax.mail.internet.*;  import javax.activation.*;  import java.util.*;  ……….  MimeMessage msg=new MimeMessage(mailSession);  msg.setSentDate(new Date());  msg.setSubject("hello");  MimeBodyPart textBodyPart=new MimeBodyPart();  textBodyPart.setText(“邮件正文”);  MimeBodyPart fileBodyPart=new MimeBodyPart();  FileDataSource fds=new FileDataSource("GIS.rar");//要发送的附件  fileBodyPart.setDataHandler(new DataHandler(fds));  fileBodyPart.setFileName(fds.getName());  Multipart container=new MimeMultipart();  container.addBodyPart(textBodyPart);  container.addBodyPart(fileBodyPart);  msg.setContent(container);  Transport.send(msg);  …………   这里的msg由两个MimeBodyPart构成,这个东西解释起来基本上比较难,如果不了解相关的规范就不太好解释,如果了解的话,我就不用解释了,这个这个………唉。 二、 邮件的收取   通常情况下我们都使用pop3协议来收邮件,IMAP嘛现在就不涉及了。收邮件的功能虽然我用了很多时间才基本搞清楚,不过讲起来就so easy了,一个程序就可以基本包括。  邮件大致可以分三种:纯文本邮件、含有其他数据的文本邮件、含有附件的邮件。  CODE    /*  * Created on 2004-4-26  */  package org.bromon.mail;  import javax.mail.*;  import java.util.*;  import java.io.*;  /**  * @author Bromon  */  public class Receiver  {  Folder inbox;  Store store;  //连接邮件服务器,获得所有邮件的列表  public Message[] getMail(String host,String name,String password) throws Exception  {   Properties prop=new Properties();   prop.put("mail.pop3.host",host);   Session session=Session.getDefaultInstance(prop);   store=session.getStore("pop3");   store.connect(host,name,password);      inbox=store.getDefaultFolder().getFolder("INBOX");   inbox.open(Folder.READ_ONLY);      Message[] msg=inbox.getMessages();      FetchProfile profile=new FetchProfile();   profile.add(FetchProfile.Item.ENVELOPE);   inbox.fetch(msg,profile);      return(msg);  }  //处理任何一种邮件都需要的方法  private void handle(Message msg) throws Exception  {   System.out.println("邮件主题:"+msg.getSubject());   System.out.println("邮件作者:"+msg.getFrom()[0].toString());   System.out.println("发送日期:"+msg.getSentDate());  }  //处理文本邮件  public void handleText(Message msg) throws Exception  {   this.handle(msg);   System.out.println("邮件内容:"+msg.getContent());  }  //处理Multipart邮件,包括了保存附件的功能  public void handleMultipart(Message msg) throws Exception  {   String disposition;   BodyPart part;      Multipart mp=(Multipart)msg.getContent();   int mpCount=mp.getCount();//Miltipart的数量,用于除了多个part,比如多个附件   for(int m=0;m<mpCount;m++)   {    this.handle(msg);        part=mp.getBodyPart(m);    disposition=part.getDisposition();    if(disposition!=null && disposition.equals(Part.ATTACHMENT))//判断是否有附件    {     //this.saveAttach(part);//这个方法负责保存附件,注释掉是因为附件可能有病毒,请清理信箱之后再取掉注释    }else{     System.out.println(part.getContent());    }   }  }  private void saveAttach(BodyPart part) throws Exception  {   String temp=part.getFileName();//得到未经处理的附件名字   String s=temp.substring(11,temp.indexOf("?=")-1);//去到header和footer      //文件名一般都经过了base64编码,下面是解码   String fileName=this.base64Decoder(s);   System.out.println("有附件:"+fileName);      InputStream in=part.getInputStream();   FileOutputStream writer=new FileOutputStream(new File(fileName));   byte[] content=new byte[255];   int read=0;   while((read=in.read(content))!=-1)   {    writer.write(content);   }   writer.close();   in.close();  }  //base64解码  private String base64Decoder(String s) throws Exception  {   sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();   byte[] b=decoder.decodeBuffer(s);      return(new String(b));  }  //关闭连接  public void close() throws Exception  {   if(inbox!=null)   {    inbox.close(false);   }      if(store!=null)   {    store.close();   }  }  public static void main(String args[])  {   String host="pop.163.com";   String name="bromon";   String password="My password";      Receiver receiver=new Receiver();      try   {       Message[] msg=receiver.getMail(host,name,password);        for(int i=0;i<msg.length;i++)    {     if(msg[i].isMimeType("text/*"))//判断邮件类型     {      receiver.handleText(msg[i]);     }else{      receiver.handleMultipart(msg[i]);     }     System.out.println("****************************");    }    receiver.close();   }catch(Exception e)   {    System.out.println(e);   }  }  }   没有习惯读java代码的兄弟可能会觉得麻烦了一点,其中有个小问题,下载的附件会再文件名后面加上一个”#”符号,不知道这是javamail的特别处理还是pop3的规范。通过程序更改文件名很简单,就不说了。对于email还有很多其他的操作,可以自己取查看一下javadoc,我就不影响大家探索的乐趣了。在Properties里配置代理服务器,可以让程序通过代理收发邮件,一般的HTTP、socks 4、socks 5都支持。 来源: Sometimes java: http://blog.csdn.net/bromon/cate

阅读(4483) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册