Upload
biyu
View
2.035
Download
0
Tags:
Embed Size (px)
DESCRIPTION
秃子!邱子东没有理会周秃子,掉头走了。香港六合彩要责问杜元潮:凭什么剥夺了香港六合彩的审批权。路上遇到了副镇长吴同干。老邱你回来了?你去哪儿?邱子东看着吴同干提了两塑料桶油,问。吴同干举了举手中的塑料桶,说:杜书记让我去上头要化肥。你去上头要化肥?邱子东不明白了,油麻地跑外交的是香港六合彩呀!杜书记说,以后,你与香港六合彩一起抓全面,原先由你管的这摊事就都分给我来做了。我怎么行呢?我也不像你那样,外头有那么多关系,香港六合彩又笨。邱子东讥讽地一笑:你怎么就不行呢?你行!香港六合彩看着吴同干手中的两塑料桶油,这油是从哪儿打来的?油坊。我对二扣子说过,没有我的批条,谁也不能从油坊里打油,一滴都不行!吴同干笑了:二扣子已不再负责油坊了,二扣子到三队做队长去了,现在是三队队长林一如管油坊,香港六合彩俩正好倒了个个儿。谁的主意?杜书记提议的。吴同干心里惦记着要化肥计划,就往前走去,但走了几步又回来说,窑厂负责香港六合彩也换了,王家宽去六队做队长,六队队长沈国民做窑厂厂长。说完,提着灌得满满的两桶油,迈着阔步,信心十足地走在油麻地通向外面的路上。最终,香港六合彩没有去找杜元潮。香港六合彩双手插在腰间,站在油麻地的田野上,任由风撩起香港六合彩的衣角、吹乱香港六合彩的头发。香港六合彩的嘴角一直挂着冷冷的微笑。傲慢之后,便是一股抵挡不住的虚弱。审批与外交,是香港六合彩得以在油麻地纵横驰骋的双翼。而如今,这双翼被香港六合彩一向不放在心上的杜元潮剪断了,香港六合彩有一种扑腾在泥灰里的无可奈何的感觉。香港六合彩来到这个世界上,一路高扬,一路风光地生活了这么多年头,第一回刻骨铭心地体味到了剥夺一词的含义。这种感觉犹如一枚冷箭穿透了脊椎。香港六合彩觉得油麻地的田野似乎变得空旷起来。虚弱之后,又是傲慢。二傻子在田野上追逐着一条发情的母牛,在嘴中含糊不清地叫唤着。香港六合彩看到了那条母牛的臀部上方所流出来的亮晶晶的黏液。这黏液的气味刺激了香港六合彩,使香港六合彩不顾一切地向母牛扑去。母牛越过一条水渠,向前奔突着。二傻子在母牛越过水渠时,掉进了水渠,半天,才爬了上来。邱子东想到了戴萍,香港六合彩想要香港六合彩,现在就想要。邱子东拼命地与戴萍做爱。长长地做,狠狠地做,花样翻新地做。一次,香港六合彩将小学校的一张课桌整得瘫痪在了地上。白天,戴萍讲课总打不起精神来,学生做作业时,香港六合彩原来是想看着的,但不一会儿就趴在讲台上睡着了。下一堂课的老师都进教室了,香港六合彩还没醒来。邱子东越来越瘦,也越来越慵懒,常常是睡到快中午了,才起床。但,两香港六合彩也越来越觉得没有味道了,尤其是戴萍。一堆火,正在灰暗中一点一点地矮下去。居然有一回,邱子东让香港六合彩在夜晚于草垛下等着香港六合彩时,香港六合彩说:今天,我不怎么想……与此同时,油麻地小学的男教师林文藻正一步一步地向戴萍靠近。林文藻一副很文弱的样子,十指修长,白嫩光滑,会拉一手好胡琴。《天瓢》【下】[第98节]骚雨/痴雨5(1)在收割早稻的时候,采芹回到了油麻地。香港六合彩和杜元潮有过一次约会。
Citation preview
© 2001 JZ Ventures, Inc. 1
JavaMail API Fundamentals
John Zukowski - [email protected] Ventures, Inc.
© 2001 JZ Ventures, Inc. 2
Agenda Getting Started Core Classes Getting Mail Sending Mail Attachments Searching Q&A
© 2001 JZ Ventures, Inc. 3
Getting Started Without (Pre?) JavaMail With JavaMail
http://java.sun.com/products/javamail/
© 2001 JZ Ventures, Inc. 4
Without JavaMail Read RFC 821 for SMTP
http://www.cis.ohio-state.edu/htbin/rfc/rfc821.html Other RFC describe things like attachments
RFC 822: Text Messages, RFC 2045-7: MIME, RFC 1939: POP3, RFC 2060: IMAP, ...
Open socket connection to port 25HELO sending hostMAIL FROM: sender emailRCPT TO: recipient emailDATA... the email message...... any number of lines ....QUIT
© 2001 JZ Ventures, Inc. 5
SmtpClientimport sun.net.smtp.SmtpClient; import java.io.PrintStream;public class SmtpClientExample { public static void main (String args[]) throws Exception { String host = args[0]; String from = args[1]; String to = args[2]; SmtpClient smtp = new SmtpClient(host); smtp.from(from); smtp.to(to); PrintStream msg = smtp.startMessage(); msg.println("To: " + to); msg.println("Subject: Hello SmtpClient"); msg.println(); // blank line between headers and message
msg.println("This is a test message.");
smtp.closeServer(); }}
© 2001 JZ Ventures, Inc. 6
Without JavaMail Take 3 Just use a URL Open a mailto: URL Write to opened URLConnection Need to set mail.host System
property Be sure to end lines with \r\n
Don’t use println()
© 2001 JZ Ventures, Inc. 7
Mail Through URLimport java.io.*;import java.net.*;public class MailTo { public static void main(String args[]) throws Exception { System.getProperties().put("mail.host", args[0]); URL url = new URL("mailto:[email protected]"); URLConnection conn = url.openConnection(); PrintStream out = new PrintStream(conn.getOutputStream(), true); out.print("From: [email protected]"+"\r\n"); out.print("Subject: Works Great!"+"\r\n"); out.print("Thanks!"+"\r\n"); out.close(); System.out.println("Message Sent"); }}
© 2001 JZ Ventures, Inc. 8
With JavaMail API Latest Version 1.2
December 5, 2000 release Sun includes IMAP, POP, and SMTP service
providers Version 1.1.3 (2/22/2000) most popular one used
Need to get JavaBeans Activation Framework http://java.sun.com/beans/glasgow/jaf.html
See demo directory for many examples
© 2001 JZ Ventures, Inc. 9
JavaMail Setup Add JAR files
to CLASSPATH, to jre/lib/ext Applets can use: javax.*
Won’t work in Netscape though without Plug-in Will work in Internet Explorer / HotJava
JavaMail mail.jar (280K) Separate JAR files available if only using parts
Activation Framework activation.jar (45K)
© 2001 JZ Ventures, Inc. 10
JDK Requirements Works with JDK 1.1.6+ Works with Java 2 platform,
Standard Edition, versions 1.2 / 1.3 Included with Java 2 platform,
Enterprise Edition
© 2001 JZ Ventures, Inc. 11
Core Classes Session Message / MimeMessage InternetAddress Authenticator Transport
© 2001 JZ Ventures, Inc. 12
Session Represents a mail session Uses Properties to get things like mail host
mail.host mail.smtp.host
Get session - no constructor Session session = Session.getInstance(props,
null); // null for Authenticator Session session =
Session.getDefaultInstance(props, null);
© 2001 JZ Ventures, Inc. 13
Message / MimeMessage Represents a mail message
Message abstract class implements Part MimeMessage is MIME style email message implements MimePart
Get message from session MimeMessage message = new
MimeMessage(session); Set parts
message.setContent() / mimeMessage.setText()
© 2001 JZ Ventures, Inc. 14
InternetAddress RFC822 Address Create:
new InternetAddress("[email protected]"); new InternetAddress("[email protected] ", "John
Zukowski"); For To, From, CC, BCC
message.setFrom(address) message.addRecipient(type, address) Types
Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC
© 2001 JZ Ventures, Inc. 15
Authenticator Permit mechanism to prompt for
username and password javax.mail.Authenticator !=
java.net.Authenticator Extend Authenticator Override:
public PasswordAuthentication getPasswordAuthentication() {
String username, password; // Then get them ... return new PasswordAuthentication(username,
password);}
© 2001 JZ Ventures, Inc. 16
Transport Message transport mechanism Get transport for session
Transport transport = session.getTransport("smtp");
Connect transport.connect(host, username, password);
Act - repeat if necessary transport.sendMessage(message,
message.getAllRecipients()); Done
transport.close();
© 2001 JZ Ventures, Inc. 17
Sending Mail Need a working SMTP server
Can be written in Java using JavaMail API, but irrelevant
Need from/to addresses, but don’t need to be valid, unless SMTP server includes some form of verification
To run example: java MailExample smtp.mailserver
© 2001 JZ Ventures, Inc. 18
Hello Worldimport java.util.Properties;import javax.mail.*;import javax.mail.internet.*;
public class MailExample { public static void main (String args[]) throws Exception
{ String host = args[0]; String from = args[1]; String to = args[2];
// Get system properties Properties props = System.getProperties();
// Setup mail server props.put("mail.smtp.host", host);
© 2001 JZ Ventures, Inc. 19
Hello World/2 // Get session Session session = Session.getInstance(props, null);
// Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); message.setText("Welcome to JavaMail");
// Send message Transport.send(message); }}
© 2001 JZ Ventures, Inc. 20
Getting Mail POP3 provider doesn’t provide
local data storage There are mailbox store providers
available Need to get/install POP3 provider
Part of JavaMail 1.2 release NOT part of basic JavaMail 1.1 API
implementation
© 2001 JZ Ventures, Inc. 21
Reading Hello Worldimport java.io.*;import java.util.Properties;import javax.mail.*;import javax.mail.internet.*;public class GetMessageExample { public static void main (String args[]) throws Exception { String host = args[0]; String username = args[1]; String password = args[2];
// Create empty properties Properties props = new Properties();
// Get session Session session = Session.getInstance(props, null);
© 2001 JZ Ventures, Inc. 22
Reading Hello World/2 // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password);
// Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader ( new InputStreamReader(System.in));
// Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; i<n; i++) {
© 2001 JZ Ventures, Inc. 23
Reading Hello World/3 System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); System.out.println("Do you want to read message? [YES
to read/QUIT to end]"); String line = reader.readLine(); if ("YES".equals(line)) { message[i].writeTo(System.out); } else if ("QUIT".equals(line)) { break; } } // Close connection folder.close(false); store.close(); }}
© 2001 JZ Ventures, Inc. 24
Authenticator Usage Put host in properties
Properties props = new Properties();props.put("mail.host", host);
Setup authentication, get sessionAuthenticator auth = new PopupAuthenticator();Session session = Session.getInstance(props,
auth); Get the store
Store store = session.getStore("pop3");store.connect();
© 2001 JZ Ventures, Inc. 25
Saving Messages To save copy locally:
Get/create appropriate provider Knife - http://www.dog.net.uk/knife/
mimeMessage.writeTo(outputStream)
© 2001 JZ Ventures, Inc. 26
Replying Use Message.reply(boolean)
Sets up message with proper headers boolean of true indicates reply to all
vs. reply to sender only Does NOT setup message contents
© 2001 JZ Ventures, Inc. 27
Deleting Messages Set message flag to deleted:
message.setFlag(Flags.Flag.DELETED, true); Be sure folder opened read-write:
folder.open(Folder.READ_WRITE); Deleted when folder closed:
folder.close(true); // true = expunge Expunge / Permanently Deletes
folder.expunge() NOT always implemented
© 2001 JZ Ventures, Inc. 28
Including Attachments Each attachment goes into a
MimeBodyPart DataHandler deals with reading in
contents Provide it with a DataSource Either URLDataSource or
FileDataSource
© 2001 JZ Ventures, Inc. 29
Sending Attachments// create mime message object and set the required
parametersMimeMessage message = createMessage(to, cc, subject); // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart();
//fill messagemessageBodyPart.setText(msg);
Multipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);
// fill the array of files to be attachedFile [] attachments = { .... }
© 2001 JZ Ventures, Inc. 30
Sending Attachments/2 for( int i = 0; i < attachments.length; i++ ) { messageBodyPart = new MimeBodyPart(); FileDataSource fileDataSource =new
FileDataSource(attachments[i]); messageBodyPart.setDataHandler(new
DataHandler(fileDataSource)); messageBodyPart.setFileName(attachments[i].getName()); multipart.addBodyPart(messageBodyPart);}// add the Multipart to the messagemessage.setContent(multipart);
// SEND THE MESSAGETransport.send(message);
© 2001 JZ Ventures, Inc. 31
Sending HTML Attachment Don’t use setText() Use setDataHandler()
String htmlText = "<H1>Hello</H1><H2>World</H2>";
message.setContent(htmlText, "text/html"));
© 2001 JZ Ventures, Inc. 32
Including HTML Images Inline Specify Image source with cid: URL
<IMG SRC=cid:23abc@pc27> Set Content-ID in header of image
attachment part.setHeader("Content-
ID","23abc@pc27"); Complete example:
http://www.jguru.com/jguru/faq/view.jsp?EID=97371
© 2001 JZ Ventures, Inc. 33
Getting Attachments from Client You want to create a web-based email
system Your user wants to include file from
their system as attachment Use an HTML Form Use Servlet to read stream Use MultipartRequest class from
O’Reilly servlets book – www.servlets.com
© 2001 JZ Ventures, Inc. 34
HTML Form<FORM ENCTYPE="multipart/form-
data" method=post action="/myservlet">
<INPUT TYPE="file" NAME="mptest"><INPUT TYPE="submit"
VALUE="upload"></FORM>
© 2001 JZ Ventures, Inc. 35
Getting Attachments For each part of Multipart, process
part Attachments can be inline or not
String disposition = part.getDisposition();
if (disposition.equals(Part.INLINE)) if
(disposition.equals(Part.ATTACHMENT))
© 2001 JZ Ventures, Inc. 36
Save Attachments public static void handleMultipart(Multipart
multipart) throws MessagingException, IOException { for (int i=0, n=multipart.getCount(); i<n; i++) { handlePart(multipart.getBodyPart(i)); } } Following code doesn’t deal with Multipart
in Multipart left as exercise for reader
© 2001 JZ Ventures, Inc. 37
Save Attachments/2 public static void handlePart(Part part) throws MessagingException, IOException { String disposition = part.getDisposition(); String contentType = part.getContentType(); if (disposition == null) { // When just body System.out.println("Null: " + contentType); // Check if plain if ((contentType.length() >= 10) && (contentType.toLowerCase().substring(0,
10).equals("text/plain"))) { part.writeTo(System.out); } else { // Don't think this will happen System.out.println("Other body: " + contentType); part.writeTo(System.out); }
© 2001 JZ Ventures, Inc. 38
Save Attachments/3 } else if (disposition.equals(Part.ATTACHMENT)) { System.out.println("Attachment: " +
part.getFileName() + " : " + contentType); saveFile(part.getFileName(), part.getInputStream()); } else if (disposition.equals(Part.INLINE)) { System.out.println("Inline: " + part.getFileName() + " : " + contentType); saveFile(part.getFileName(), part.getInputStream()); } else { // Should never happen System.out.println("Other: " + disposition); } }
© 2001 JZ Ventures, Inc. 39
Debugging Trace commands sent
session.setDebug(true)
© 2001 JZ Ventures, Inc. 40
New Mail Notification Events Add MessageCountListener to
folder Find out when new messages are
received Sleep then folder.getMessageCount()
to get notification from IMAP server Not POP3 - Does not work when folder
open
© 2001 JZ Ventures, Inc. 41
More Notification Events Transport/Store/
Folder.addConnectionListener() open, closed, disconnected
Folder.addFolderListener() created, deleted, renamed
Folder.addMessageChangeListener changed
Store.addStoreListener notification
Transport.addTransportListener message delivered, not delivered, partially
delivered
© 2001 JZ Ventures, Inc. 42
JavaMail Searching API includes support for searching
for matching messages javax.mail.search package Build a SearchTerm Search:
Message[] msgs = folder.search(st);
© 2001 JZ Ventures, Inc. 43
Building Up SearchTerm AND terms (class AndTerm) OR terms (class OrTerm) NOT terms (class NotTerm) SENT DATE terms (class SentDateTerm) CONTENT terms (class BodyTerm) HEADER terms (FromTerm /
FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..)
© 2001 JZ Ventures, Inc. 44
Using SearchTermFolder folder =
store.getFolder("INBOX");SearchTerm st = new AndTerm(new
SubjectTerm("ADV:"), new BodyTerm("hello");
Message[] msgs = folder.search(st);
© 2001 JZ Ventures, Inc. 45
S/MIME Includes email signing and
encryption support Get a different provider
Phaos S/MIME toolkit http://www.phaos.com/e_security/
prod_smime.html JCSI
http://security.dstc.edu.au/projects/java/release2.html
© 2001 JZ Ventures, Inc. 46
JavaMail with JSP Definitely doable with Java source scriptlets However, should limit amount of Java
source in JSP pages Use JavaBeans that hide/simplify
capabilities for Web designer Create / Get
ImMailBean http://www.imessaging.com/html/immailbean.html
Source Fourge http://sourceforge.net/project/?group_id=1282
© 2001 JZ Ventures, Inc. 47
JavaMail with NNTP You can use JavaMail with NNTP Need to get an NNTP provider
http://www.dog.net.uk/knife/ To read newsgroups
Store store = session.getStore("nntp"); store.connect(host, username, password); Folder folder = store.getFolder(newsgroup); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages();
© 2001 JZ Ventures, Inc. 48
JavaMail is Free Sun’s reference implementation is
completely free Sun’s License:
http://java.sun.com/products/javamail/LICENSE.txt
Includes SMTP, IMAP, and POP3 providers
© 2001 JZ Ventures, Inc. 49
James Java Apache Mail Enterprise Server Pure Java-based mail server Supports Mailets
Like servlets, but for extending mail server
Add capabilities like mailing list support, filtering, translation, etc.
http://java.apache.org/james/index.html
© 2001 JZ Ventures, Inc. 50
Miscellaneous Sun’s JavaMail FAQ
http://java.sun.com/products/javamail/FAQ.html
Mailing List http://archives.java.sun.com/archives/javamail-
interest.html Get the JavaMail Source
1.1.2 source part of J2EE Sun Community Source Licensing
http://www.sun.com/software/communitysource/j2ee/
© 2001 JZ Ventures, Inc. 51
Other Providers knife
http://www.dog.net.uk/knife/ NNTP, POP3, mailbox file provider
Project "POPpers" http://www2s.biglobe.ne.jp/~dat/java/
project/poppers/index_en.html ICEMail
Java-based Email Client http://www.icemail.org/
© 2001 JZ Ventures, Inc. 52
Questions & Answers Questions?
Use the FAQs John Zukowski
http://www.jguru.com http://java.about.com http://www.jguru.com/faq/JavaMail