`

接受email

阅读更多
Technical Articles and Tips

Retrieving Mail with the JavaMail API and Working with the Java Communications API

 
<!----><!----><!----><!----><!----><!---->
 
<!----><!----><!----><!---->

Tech Tips Archive


WELCOME to the Java Developer Connection (JDC) Tech Tips, January 22, 2002. This issue covers:

These tips were developed using Java 2 SDK, Standard Edition, v 1.3.

This issue of the JDC Tech Tips is written by John Zukowski, president of JZ Ventures, Inc. (http://www.jzventures.com).

<!---->
Pixel
<!---->

RETRIEVING MAIL WITH THE JAVAMAIL API

The JavaMail API provides the framework for sending and retrieving electronic messages (email). The JDC Tech Tip "Sending Mail With the JavaMail API" showed you how to send mail via SMTP through the JavaMail API. In this tip, you'll see how to retrieve messages from your POP/IMAP server.

In many ways retrieving messages is similar to sending. For example, sending mail involves using the Session, Message, Address, and Transport classes. Retrieving messages involves the same Session and Message classes, however you also use Folder and Store classes. Once you make a connection to the mail server for message retrieval, the messages are stored in a Folder of the Store.

The first thing you do to retrieve mail is connect to the mail server, just as you do for sending mail. But the mail servers are different. When you send mail, you connect to a server that supports the Simple Mail Transfer Protocol (SMTP). This is a protocol explicitly for sending electronic mail. When you retrieve mail, you connect to a server that supports the Post Office Protocol, Version 3 (POP3) or Internet Message Access Protocol, Version 4 (IMAP4) protocol. These protocols are designed for retrieving electronic mail. POP is a simple protocol. It allows users to retrieve mail, but it doesn't have the sophistication to do things like identify "new" mail. IMAP, by comparison, is more sophisticated.

You can get a mail session with either the getDefaultInstance() or getInstance() methods of Session. Calling the getDefaultInstance() method returns a shared session instance. This means that the same session is returned (and thus shared) by every call to the method. The getInstance() method returns a new session instance each time you call it. New sessions are useful when you don't want other threads to be working simultaneously with the shared session.

When you get the session, you must pass a Properties instance. This contains property settings such as the mail server you're using for the connection. You need to set the "mail.pop3.host" (or "mail.imap.host") to the mail server for the connection (for example, pop.example.com):

// Setup properties
Properties props = System.getProperties();
props.put("mail.pop3.host", host);

When you send mail, you should authenticate the connection, for instance, prompt for a username and password. You can do this by extending JavaMail's Authenticator class. For example, the following class, PopupAuthenticator, uses a Swing JOptionPane to prompt for a username and password. In this example, the user would enter the username and password as a comma-separated list. Notice that the getPasswordAuthentication() method returns the username and password. (Feel free to improve on this to use a JPasswordField instead for the password.).

<!---->
import javax.mail.*;
import javax.swing.*;
import java.util.*;

public class PopupAuthenticator 
    extends Authenticator {

  public PasswordAuthentication 
      getPasswordAuthentication() {
    String username, password;

    String result = JOptionPane.showInputDialog(
      "Enter 'username,password'");

    StringTokenizer st = 
      new StringTokenizer(result, ",");
    username = st.nextToken();
    password = st.nextToken();

    return new PasswordAuthentication(
      username, password);
  }
}


<!---->

After you have the Properties, and an Authenticator, you can get a Session:

// Setup authentication, get session
Authenticator auth = new PopupAuthenticator();
Session session = 
  Session.getDefaultInstance(props, auth);

Then make a connection to the Store with the getStore() method, passing the method the appropriate mail protocol for your server -- either "pop3" or "imap". Here's how you would make the appropriate connection to a POP3 server:

// Get the store
Store store = session.getStore("pop3");
store.connect();

The call to the connect() method of Store triggers a call to PopupAuthenticator. As mentioned earlier, PopupAuthenticator prompts for a valid username and password combination. If you respond with a valid userid and password for the mail account, a connection is established with the mail server and you can then read your mail.

All mail is stored in folders, that is, instances of the Folder class. So to read mail, the first thing you do is connect to the appropriate Folder. In the case of POP mail, there is only one folder, INBOX. In the case of IMAP, the Folder can be INBOX or any other folders that you created. Assuming you want to read mail from your INBOX, simply connect to the folder with the getFolder() method of Session:

// Get folder
Folder folder = store.getFolder("INBOX");

Next, you need to open the Folder with the open() method. You can open it in either Folder.READ_WRITE mode or Folder.READ_ONLY mode. To read messages, you can use read-only, although if you want to delete messages, you need to use READ_WRITE.

folder.open(Folder.READ_ONLY);

Connecting to the Folder gives you access to the individual Message objects. You can use the getMessage() method to get an individual message, or as in the following example, use the getMessages() method to get all the messages:

// Get directory
Message message[] = folder.getMessages();

The Folder class also defines a getNewMessageCount() method to count the number of new messages in the Folder. However you shouldn't use it if you use a POP server -- remember POP doesn't support the concept of "new" messages.

You have several options in deciding what to retrieve from each message. For instance, you can call getFrom() or getSubject() to retrieve the identity of the sender (as an Address array), or the message subject, respectively.

<!---->
// Display from (only first) and subject of messages
for (int i=0, n=message.length; i<n; i++) {
  System.out.println(i + ": " 
    + message[i].getFrom()[0] 
    + "\t" + message[i].getSubject());
}

<!---->

More than likely though, you're interested in the message content. Typically, you use the getContent() method to see the message content:

  System.out.println(message[i].getContent());

You can also use the writeTo() method to get the message content. This permits you to save the entire contents of the message (including headers) to an output stream.

After reading your mail, be sure to close the Folder and the Store. In the case of the Folder, the close() method requires you to specify whether you want to expunge any deleted messages. The Store doesn't require any arguments to its close() method:

// Close connection 
folder.close(false);
store.close();

What follows is a complete program, Fetch, that demonstrates the concepts described above. In order to run the program, you'll need to have the JavaMail API installed, as well as the JavaBeans Activation Framework. Information about where to get the downloads follows the program below.

The Fetch program displays the first 200 characters of any messages currently stored in your INBOX. If your mail server supports IMAP and not POP, change the "pop3" references in the code to "imap". Before you compile the program, remember to first compile the PopupAuthenticator class shown earlier.

Run the Fetch program from the command line like this:

  java Fetch mailserver

Replace "mailserver" with the name of your mail server.

In response, the program will prompt you for your userid and password.

<!---->
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class Fetch {
  public static void main (String args[]) 
      throws Exception {
    String host = args[0];

    // Get system properties
    Properties props = System.getProperties();
    props.put("mail.pop3.host", host);

    // Setup authentication, get session
    Authenticator auth = new PopupAuthenticator();
    Session session = 
      Session.getDefaultInstance(props, auth);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect();

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message message[] = folder.getMessages();
    for (int i=0, n=message.length; i<n; i++) {

       System.out.println(i + ": " 
         + message[i].getFrom()[0] 
         + "\t" + message[i].getSubject());
       String content = 
         message[i].getContent().toString();
       if (content.length() > 200) {
         content = content.substring(0, 200);
       }
       System.out.print(content);
    }

    // Close connection 
    folder.close(false);
    store.close();
    System.exit(0);
  }
}

<!---->

The latest version of the JavaMail API is available for download from the JavaMail API page. To use the JavaMail API, you must also have the JavaBeans Activation Framework installed. The JavaBeans Activation Framework is available for download from the JavaBeans Activation Framework page. You can also get the JavaMail API and the JavaBeans Activation Framework as part of the Java 2 Platform, Enterprise Edition 1.3 download. Source code for the JavaMail classes is available through the J2EE 1.3 Sun Community Source Licensing (SCSL) program.

Here's a variation on the previous approach. If you don't want to use an Authenticator, get a Session without setting any properties. Then, provide the host name, username, and password to the connect() method. The following snippet shows this behavior:

<!---->
// Setup empty properties
Properties props = new Properties();


// Get session
Session session = Session.getDefaultInstance(props, null);


// Get the store
Store store = session.getStore("pop3");
store.connect(host, username, password);

<!---->

Notice that the Fetch example does not deal with any message content as an attachment. For information on fetching attachments, see the tutorial "Fundamentals of the JavaMail API.

Also, if you use Yahoo for mail, you must enable POP Access & Forwarding from their Options screen to get mail through the JavaMail API. You can't use Hotmail though -- it doesn't support remote access.

<!---->
Pixel
<!---->

WORKING WITH THE JAVA COMMUNICATIONS API

The Java Communications (COMM) API is an optional package for the Java 2 platform. It provides support for communicating with peripheral devices through the serial and parallel ports of a computer. It is a special API in the sense that while the API is well defined across platforms, you must download a platform-specific version of the COMM libraries to actually use them.

This tip will demonstrate the COMM API by showing you how to get a list of the available ports on a machine and printing to a printer. The COMM API does not include support for communicating over Universal Serial Bus (USB) ports. Support for USB ports will be provided by a separate API that is currently undergoing a public review through the Java Community Process (JCP). See JSR 80 for details.

To begin, download and unpack the Java Communications API. To get the Java Communications API for Windows and Solaris platforms visit the Java Communications API page. When you do that, you need to do a little setup work. You don't just put the comm.jar file into your class path, though that is the first step. You also must copy the shared library to the bin directory, and the javax.comm.properties file to the lib directory of the runtime environment. For Java 2 SDK, version 1.3 for Windows, that means:

copy comm.jar \jdk1.3\jre\lib\ext
copy win32com.dll \jdk1.3\bin
copy javax.comm.properties \jdk1.3\jre\lib

After doing the setup work, the Java Communications API classes are available from the javax.comm package. The key classes in the package are CommPortIdentifier and CommPort. You use CommPortIdentifier to find out the set of installed CommPort objects. You can then communicate with any individual CommPort object.

To find out what ports are installed, you ask the CommPortIdentifier for the installed set with getPortIdentifiers(). This returns an Enumeration of CommPortIdentifier objects. Each object is of the type PORT_PARALLEL or PORT_SERIAL, two constants in the CommPortIdentifier class.

To demonstrate, the following fetches the set of ports available and reports the name and type of each:

<!---->
import javax.comm.*;
import java.util.Enumeration;

public class ListPorts {
  public static void main(String args[]) {
    Enumeration ports = 
      CommPortIdentifier.getPortIdentifiers();
    while (ports.hasMoreElements()) {
      CommPortIdentifier port = 
        (CommPortIdentifier)ports.nextElement();
      String type;
      switch (port.getPortType()) {
        case CommPortIdentifier.PORT_PARALLEL:
          type = "Parallel"; 
          break;
        case CommPortIdentifier.PORT_SERIAL:
          type = "Serial"; 
          break;
        default:  /// Shouldn't happen
          type = "Unknown"; 
          break;
      }
      System.out.println(port.getName() + ": " + type);
    }
  }
}

<!---->

ListPorts should produce results similar to the following:

COM1: Serial
COM2: Serial
LPT1: Parallel
LPT2: Parallel

In addition to walking through an Enumeration of ports from the CommPortIdentifier, you can ask for a specific port. You do this by passing the name of the port (LPT1, for instance) to the getPortIdentifier() identifier method. This returns the port identifier, or throws a javax.comm.NoSuchPortException if the port doesn't exist.

// Get port
CommPortIdentifier portId = 
  CommPortIdentifier.getPortIdentifier(portname);

To read from or write to a port, use the open() method. The open() method requires an owner name for the port, and a timeout value in milliseconds.

// Open port
// Open requires a owner name and timeout
CommPort port = portId.open("Application Name", 30000);

After you've opened a port, you can read and write to it just like a socket connection. The InputStream is available from the getInputStream() method of CommPort and the OutputStream is available with getOutputStream().

// Setup output
OutputStream os = port.getOutputStream();
BufferedOutputStream bos = 
                          new BufferedOutputStream(os);

Let's use the COMM API to print a file. To do that, you simply find the printer port, open it, get its OutputStream, and send the file contents through it. The following example demonstrates that sequence. It prints a sample PostScript file named sample.ps. You'll need to create the sample file first. Be sure to close the port and streams when you are finished with them.

<!---->
import javax.comm.*;
import java.io.*;

public class PrintFile {
  public static void main(String args[]) 
      throws Exception {
    if (args.length != 2) {
      System.err.println(
        "usage : java PrintFile port file");
      System.err.println(
        "sample: java PrintFile LPT1 sample.ps");
      System.exit(-1);
    }

    String portname = args[0];
    String filename = args[1];

    // Get port
    CommPortIdentifier portId = 
      CommPortIdentifier.getPortIdentifier(portname);

    // Open port
    // Open requires a owner name and timeout
    CommPort port = portId.open("Application Name", 30000);

    // Setup reading from file
    FileReader fr = new FileReader(filename);
    BufferedReader br = new BufferedReader(fr);

    // Setup output
    OutputStream os = port.getOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(os);

    int c;
    while ((c = br.read()) != -1) {
      bos.write(c);
    }

    // Close
    bos.close();
    br.close();
    port.close();
  }
}

<!---->

For more information about the Java Communications API, see the Java Communications API Users Guide.

<!---->
Pixel
<!---->

IMPORTANT: Please read our Terms of Use and Privacy policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/

FEEDBACK
Comments? Send your feedback on the JDC Tech Tips to:
jdc-webmaster@sun.com

SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click "Update".
- To unsubscribe, go to the subscriptions page, uncheck the appropriate checkbox, and click "Update".

- ARCHIVES
You'll find the JDC Tech Tips archives at:
http://java.sun.com/jdc/TechTips/index.html

- COPYRIGHT
Copyright 2002 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.

This document is protected by copyright. For more information, see:
http://java.sun.com/jdc/copyright.html

JDC Tech Tips
January 22, 2002

<!---->

Sun, Sun Microsystems, Java, Java Developer Connection, JavaMail, and JavaBeans are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

<!----><!----><!----><!----><!----><!----><!----><!---->
分享到:
评论

相关推荐

    fast email verifier邮箱验证工具

    3. **SMTP连接**:尝试与邮件服务器建立SMTP连接,检查邮箱是否接受来自外部的邮件。若能成功连接并进行简单交互,说明邮箱可能有效。 4. **隐式验证**:通过发送一个不可见的确认邮件到目标邮箱,然后检查是否收到...

    FrameworkManager Version 0.81开源自动化框架

    通常我们构建的代码会变得很臃肿,过于复杂而难以维护,例如写了很多的Select-Case或If结构的语句(如果输入域仅能接受Email格式数据,则这样;如果只能接受地址,则那样...)。按照这种方式写的脚本会难以维护,...

    rfc821-c.tar.gz_RFC821_TAR?IN TOZU mail

    在描述中提到的“接受email的c语言程序”,意味着源代码包含了一个SMTP(Simple Mail Transfer Protocol)服务器端的实现。SMTP服务器是互联网上的一个关键组件,它接收来自发件人的邮件,并负责将这些邮件转发到收...

    Fast Email Verifier.rar

    《Fast Email Verifier:高效邮箱验证工具的深度解析》 在现代数字通信中,电子邮件作为重要的通讯手段,其有效性与准确性至关重要。然而,当我们通过网络搜集到大量的邮箱地址时,如何确保这些地址真实有效,避免...

    前端开源库-nice-is-email

    这个函数接受一个字符串作为参数,如果字符串符合电子邮件格式,它将返回`true`;否则,返回`false`。例如: ```javascript var email = 'example@email.com'; if (niceIsEmail(email)) { console.log('邮箱地址...

    email.class PHP邮箱类

    此外,类可能还提供了更复杂的验证,如DNS MX记录检查,以确保邮箱服务器存在并接受邮件。 在注册或登录场景下,类可能包含了发送验证邮件的功能。这通常涉及到生成一个唯一的验证码,将其与用户邮箱关联,然后通过...

    emails-input:电子邮件输入组件

    电子邮件输入组件 内容 ... 它接受email作为参数: const emailInput = new EmailInput ( 'email_input' ) ; emailInput . addEmail ( 'john@doe.com' ) ; 如果未传递任何参数,它将随机生成电子

    Python库 | validate_email_wt-1.4.5-py2.py3-none-any.whl

    3. **SMTP连接**:有些库可能还会尝试与邮件服务器建立SMTP连接,进一步确认邮件地址是否接受邮件,但这可能会涉及到隐私和性能问题,因此`validate_email_wt`可能仅提供基本的验证。 4. **自定义规则**:为了满足...

    检测邮件地址是否真实存在的小工具_eMail Verifier

    2. **DNS解析**:接着,工具会进行DNS(Domain Name System)查询,检查邮件服务器的MX(Mail Exchange)记录,确认该域名是否接受邮件。 3. **SMTP连接**:通过SMTP(Simple Mail Transfer Protocol)协议,eMail ...

    很好的email接受邮件

    根据提供的文件信息,我们可以提取出以下相关知识点: ### 一、使用JavaMail处理Gmail邮件 #### 1....JavaMail API是由Sun Microsystems(现为Oracle)开发的一个用于发送和接收电子邮件的标准Java API。...

    Email营销的现状和问题.doc

    因此,建立规范的管理制度,提高Email营销的专业性和针对性,以及增强用户的接受度,是推动Email营销健康发展的重要任务。 综上所述,Email营销的现状是机遇与挑战并存,企业需要深入了解Email营销的本质,采用合法...

    前端开源库-sane-email-validation

    在HTML5中,`&lt;input type="email"&gt;`标签允许开发者创建一个字段来接受电子邮件地址。浏览器会自动提供基本的客户端验证,检查输入是否包含`@`符号和`.`字符。然而,这种验证方式并不全面,无法捕获所有有效的电子...

    Email源码下载(一个接收邮件程序)

    本资源“Email源码下载(一个接收邮件程序)”提供了一个实用的学习实例,帮助开发者深入理解邮件传输的过程以及相关网络协议。下面将详细阐述相关知识点。 1. **SMTP与POP3协议**:邮件的发送和接收主要依赖两种...

    php发送email

    2. **服务器问候**:服务器会返回一条问候消息,如果响应码不是220,则表示服务器未准备好接受邮件。 3. **发送HELO或EHLO命令**:这一步是向服务器标识发件人的主机名。 4. **身份验证**:如果设置了身份验证,将...

    Flex实现简单的Email发送

    使用的原理很简单: Flex-Form 接受用户输入 || ||使用RemoteObject方式就用户输入的数据封装成json格式传递到后台java bean || Java Bean()---&gt;执行真正的Email发送-----&gt;回馈消息----&gt;Flex-Form

    验证Email smtp 有效性

    在IT行业中,验证电子邮件(Email)的SMTP有效性是一项基本任务,尤其在开发涉及邮件发送功能的应用时。SMTP(Simple Mail Transfer Protocol)是互联网标准,用于发送电子邮件。本篇将详细介绍如何利用C++和MFC...

    Email邮件头揭秘

    邮件头是电子邮件的重要组成部分,...因此,本文档中的域名和IP地址都是虚构的,它们与真实的互联网域名和IP地址没有任何联系,使用这些信息是为了说明和教育目的,并且任何基于这些信息的伪造邮件行为都是不可接受的。

    C# 发送Email接收邮件 126发送Email Gmail发送Email

    在IT领域,C#是一种广泛使用的编程语言,尤其在开发Windows应用程序、Web应用程序以及服务器端应用时。在C#中发送和接收电子邮件是一项常见的任务,这通常涉及到使用SMTP(Simple Mail Transfer Protocol)服务。...

    集成Email登录

    这允许用户通过他们的电子邮件地址来注册和登录,提供了一种便捷且普遍接受的身份标识方法。本文将深入探讨如何使用JavaScript和HTML来实现这样的集成登录系统。 首先,我们需要一个HTML表单来收集用户的输入。在`...

Global site tag (gtag.js) - Google Analytics