2010年12月7日 星期二

[ Java 代碼範本 ] JavaMail 使用說明

轉載自 這裡 
前言 : 
In JavaMail you'll find APIs and provider implementations allowing you to develop fully functional email client applications. "Email client applications" invokes thoughts of Microsoft Outlook; and, yes, you could write your own Outlook replacement. But an email client need not reside on a client machine at all. Indeed, it could be a servlet or an EJB running on a remote server, providing end-user access to email via a Web browser. Think of Hotmail (yes, you could write your own version of Hotmail too). Or you could avoid a user interface altogether. 

安裝 : 
If you use Java 2 Platform, Enterprise Edition (J2EE) 1.3, you're in luck: it includes JavaMail, so no additional setup is required. If, however, you're running Java 2 Platform, Standard Edition (J2SE) 1.1.7 and upwards, and you want email capability for your applications, download and install the following link : (For JDK6, the JavaMail default is not in the SDK, than means you have to download the library yourslef too) 
* JavaMail : 

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

To install, simply unzip the downloaded files and add the contained jar files to your classpath. Or use your IDE to be included in the lib list. 
The mailapi.jar file contains the core API classes, while the pop3.jar and smtp.jar files contain the provider implementations for the respective mail protocols. (We won't use the imap.jar file in this article.) Think of the provider implementations as similar to JDBC (Java Database Connectivity) drivers, but for messaging systems rather than databases. As for the mail.jar file, it contains each of the above jar files, so you could restrict your classpath to just themail.jar and activation.jar files. 
The activation.jar file allows you to handle MIME (Multipurpose Internet Mail Extensions) types accessible via binary data streams. Look for the DataHandler class in the Not Just Plain Text section later. 

範例代碼 : Sending email via SMTP 
The first example shows how to send a basic email message via SMTP. Below, you'll find the SimpleSender class, which takes your message's details from the command line and calls a separate method -- send(...) -- to send it : 
- SimpleSender.java (Part 1) :
  1. package com.lotontech.mail;  
  2. import javax.mail.*;  
  3. import javax.mail.internet.*;  
  4. import java.util.*;  
  5. /** 
  6.   * A simple email sender class. 
  7.   */  
  8. public class SimpleSender  
  9. {  
  10.   /** 
  11.     * Main method to send a message given on the command line. 
  12.     */  
  13.   public static void main(String args[])  
  14.   {  
  15.     try  
  16.     {  
  17.       String smtpServer=args[0];  
  18.       String to=args[1];  
  19.       String from=args[2];  
  20.       String subject=args[3];  
  21.       String body=args[4];  
  22.       send(smtpServer, to, from, subject, body);  
  23.     }  
  24.     catch (Exception ex)  
  25.     {  
  26.       System.out.println("Usage: java com.lotontech.mail.SimpleSender"  
  27.        +" smtpServer toAddress fromAddress subjectText bodyText");  
  28.     }  
  29.     System.exit(0);  
  30.   }  

Next, run SimpleSender as below. Replace smtp.myISP.net with your own SMTP server, as derived from your mail settings : 
> java com.lotontech.mail.SimpleSender smtp.myISP.net bill@lotontech.com ben@lotontech.com "Hello" "Just to say Hello." 

And, if it works, at the receiving end you'll see something like what's shown in Figure 2 : 
 
The send(...) method completes the SimpleSender class. I'll show the code first, then detail the theory : 
- SimpleSender.java (Part 2) : Method send()
  1. /** 
  2.     * "send" method to send the message. 
  3.     */  
  4.   public static void send(String smtpServer, String to, String from  
  5.    , String subject, String body)  
  6.   {  
  7.     try  
  8.     {  
  9.       Properties props = System.getProperties();  
  10.       // -- Attaching to default Session, or we could start a new one --  
  11.       props.put("mail.smtp.host", smtpServer);  
  12.       Session session = Session.getDefaultInstance(props, null);  
  13.       // -- Create a new message --  
  14.       Message msg = new MimeMessage(session);  
  15.       // -- Set the FROM and TO fields --  
  16.       msg.setFrom(new InternetAddress(from));  
  17.       msg.setRecipients(Message.RecipientType.TO,  
  18.         InternetAddress.parse(to, false));  
  19.       // -- We could include CC recipients too --  
  20.       // if (cc != null)  
  21.       // msg.setRecipients(Message.RecipientType.CC  
  22.       // ,InternetAddress.parse(cc, false));  
  23.       // -- Set the subject and body text --  
  24.       msg.setSubject(subject);  
  25.       msg.setText(body);  
  26.       // -- Set some other header information --  
  27.       msg.setHeader("X-Mailer""LOTONtechEmail");  
  28.       msg.setSentDate(new Date());  
  29.       // -- Send the message --  
  30.       Transport.send(msg);  
  31.       System.out.println("Message sent OK.");  
  32.     }  
  33.     catch (Exception ex)  
  34.     {  
  35.       ex.printStackTrace();  
  36.     }  
  37.   }  
  38. }  

First, notice that you're obtaining a mail session (java.mail.Session), without which you can do nothing. In this case you're callingSession.getDefaultInstance(...) to get a shared session, which other desktop applications may reuse; you can also set up an entirely new session -- via theSession.getInstance(...) method -- that would be unique to your application. The latter could prove important for email clients not isolated on a per-user basis, such as a Web-based email system implemented with servlets. 
Establishing a session requires you to set certain properties; at minimum, you need the mail.smtp.host property if you're sending messages via SMTP. You'll find other properties described within the API documentation.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...