利用jakarta Commons组件收发邮件

发邮件:

Telnet to port 25 of a SMTP server, and you will see the server respond with a numeric code (220). SMTPReply.isPositiveCompletion( ) returns true if the response code of the previously executed command is between 200 and 299; the value of the initial response code, 220, is equal to the public static variable SMTPReply.SERVICE_READY. The following example uses getReplyCode( ) and SMTPReply.isPositiveCompletion() to test the connection to the SMTP server:

import org.apache.commons.net.smtp.SMTP;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
SMTPClient client = new SMTPClient( );
client.connect("www.discursive.com");
int response = client.getReplyCode( );
if( SMTPReply.isPositiveCompletion( response ) ) {
// Set the sender and the recipients
client.setSender( "tobrien@discursive.com" );
client.addRecipient( "president@whitehouse.gov" );
client.addRecipient( "vicepresident@whitehouse.gov" );
// Supply the message via a Writer
Writer message = client.sendMessageData( );
message.write( "Spend more money on energy research.  Thanks." );
message.close( );
// Send the message and print a confirmation
boolean success = client.completePendingCommand( );
if( success ) {
System.out.println( "Message sent" );
}
} else {
System.out.println( "Error communicating with SMTP server" );
}
client.disconnect( );

Instead of sendSimpleMessage( ), the previous example sets a sender address and two recipient addresses using setSender( ) and addRecipient(). The message body is then written to a Writer returned by sendMessageData(). When the Writer is closed, the message is sent by calling completePendingCommand(). completePendingCommand( ) returns true if the message has been queued for delivery.

收邮件:

Use Commons Net POP3Client to check a POP3 mailbox for incoming mail. The following example connects to the POP3 server www.discursive.com, logs in as tobrien@discursive.com, and prints each message in the mailbox:

import org.apache.commons.io.CopyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
POP3Client client = new POP3Client( );
client.connect("www.discursive.com");
client.login("tobrien@discursive.com", "secretpassword");
POP3MessageInfo[] messages = client.listMessages( );
for (int i = 0; i < messages.length; i++) {
int messageNum = messages[i].number;
System.out.println( "************* Message number: " + messageNum );
Reader reader = client.retrieveMessage( messageNum );
System.out.println( "Message:\n" + IOUtils.toString( reader ) );
IOUtils.closeQuietly( reader );
}
client.logout( );
client.disconnect( );

posted on 2007-11-23 10:13 刘铮 阅读(744) 评论(0)  编辑  收藏 所属分类: JAVA General


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论