首页(162) xml(5) spring(1) 生活(8) java(70) 代码(10) 英语(4) 数据库(7) c#(14) 成长(10) 软件工程(27)  写新日志
 
 

玻璃杯中的花生壳

  真爱的事业和真正的爱情一生只有一次,都值得我们温柔地相待,因为那种感觉是永远都无法复制的, 这世界真正属于你的东西其实并不多,你不好好珍惜,它便会离你而去,包括机遇,包括爱情,包括生命。
   不要找任何理由,  当幸福在你身边的时候就抓住它,你就一定会很幸福! 
   

时 间 记 忆
«December 2025»
123456
78910111213
14151617181920
21222324252627
28293031

最 新 评 论
回复:xml的Jdom解析过程详解
回复:突然想到的几句话!
 Boyle came out of n
回复:xml的Jdom解析过程详解
回复:配置Spring数据源
回复:使用SAX解析XML
回复:java中写文件操作时FileOu
回复:关联和依赖关系的区分
回复:HttpSessionListen
回复:Spring AOP四种创建通知(

最 新 日 志
Java开发者的十大戒律
配置Spring数据源
java多线程设计模式
java中switch的使用
性格,编码,测试
突然想到的几句话!
理解Spring AOP中的关键概念
Spring AOP四种创建通知(拦截器
xml的四种解析方法 比较 sax,do
xml的Jdom解析过程详解

最 新 留 言
签写新留言

我渴望知识
很好的东东
帖子不错,道声谢
想拜师学艺
我的呼喊

搜 索


用 户 登 录
用户名称:
登陆密码:
密码保存:

友 情 连 接

模板设计:部落窝模板世界

blog名称:玻璃杯中的花生壳
日志总数:162
评论数量:249
留言数量:1
访问次数:835891
建立时间:2004年11月4日
 
 
 
[代码]Javamail操作指南:实例代码解析
[ 2006/9/5 11:44:51 | By: 玻璃杯中的花生壳 ]
 
怎样才算比较完整的Javamail操作指南?我想应该包括绝大多数基本的email操作,能够应付一般的应用。在本指南中主要囊括了以下内容: ● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证 ● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件 我想有了上述功能的介绍,应该可以应付很多email的相关应用了。首先需要配置环境。需要的包是mail.jar和activation.jar。高版本的J2SDK EE自带。 一、 邮件的发送 下面了弄个发邮件的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); ………… 二、 邮件的收取 通常情况下我们都使用pop3协议来收邮件,IMAP现在就不涉及了。用一个程序就可以基本包括了收邮件的功能。邮件大致可以分三种:纯文本邮件、含有其他数据的文本邮件、含有附件的邮件。 /* * 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); } } }
 

阅读全文(1992) | 回复(0) | 编辑 | 精华
 

发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)
 
部落窝Blog模板世界部落窝Blog模板世界
站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.547 second(s), page refreshed 144800762 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号