Java development tool of sending mail Email Author: Rui Feng issued a document time: 2002.12.18 This article describes how to use the Java API to implement an e-mail network tool program. Usually the Email tool uses SMTP (Simple Mail Transfer Protocol, Simple Mail Transfer Protocol) to send emails, using the POP3 protocol to accept email. Only the two agreements are briefly introduced in this article. If interested readers can refer to the following sites: pop3: ftp://ftp.isi.edu/in-notes/rfc1939.txt smtp: ftp://ftp.isi.edu/in-notes/rfc2821.txt java Although JavaMail API is provided, because I will discuss how the email software works from the bottom, I will not use the JavaMail API. The examples in this article are developed under J2SE 1.4.
Email format
Before developing Email software, you need to understand email formats. According to RFC 2882 (http://www.faqs.org/rfcs/rfc2822.html), email consists of many lines, each row
(ASCII code 13 and ASCII code 10) end. The maximum length of each row is 998 characters. Some of these rows provide information necessary to send and receive emails, which are called headers, and all heads constitute a header field. Other rows are used to save the specific content of the email. The head domain provides a lot of information, including the source of the message; the destination of the message, and the subject of the message. Each head is composed of a corresponding value by the name and colon. For example from:, send: and reply-to: The source of the message is recorded. In from: Record the author of the message; in Sender: Specifies the agent to send a message (can be an email address, or the machine name); Reply-to: The email address accepts the reply is specified. An email may have multiple authors, so from: You can specify one or more email addresses. Here is an example of from: from:
From: ray feng
There can be only one Sender in an email. Therefore, the value of Sender: can only contain one email address. If there is only one author in from From: The value of the sender is the same, the value is the same as the value of from:, the sender does not appear in an email, otherwise information redundancy will appear; the reverse Sender: The response should appear in the message. Here is an example of Sender:
Sender: ray feng rayfeng@yahoo.com.cn
You can specify a reply to multiple email addresses in an email. Therefore, reply-to: can include one or more email addresses, separated by commas between each address. If there is reply-to to:, the reply will be sent to all the addresses in the REPLY-TO: if there is no reply-to :, adjusted in the message, the reply will be sent to the address in from: So will anyone receive the email? To: and CC: The email address of the message is saved. The value of the two can contain multiple email addresses. Some other heads are also defined in the RFC 2882 in addition to the source and recipient of the message, such as Subject: The subject of the email contains emails. Below is an example of an email header:
From: ray feng
CC: john
Subject: Test Email
Attachment is allowed to add binary files to emails in MIME, and the file being added is called an attachment. The content of the attachment can be transmitted as part of the message. Is MIME if this function is implemented? A lot of heads in MIME are introduced, with the most important of attachment is Content-Type: and Content-Tracnsfer-Encoding:. In order to distinguish between a part of an email, MIME requires a boundary parameter in the Content-Type: Multipart / Mixed header. The value of the boundary parameter is a string in double quotes. Through this string, the program can distinguish the different parts of the email. Before transmitting the content of the email, the program transmits one first
, Two consecutive characters and boundary parameters. After completing the transmission of Email content, the program will transmit boundary parameters and two hyphens. The following email contains two parts, one part is a text consisting of ISO-8859-1 characters, part of the attachment named file.txt. There is no Content-Transfer-Encoding: Head, indicating the default 7-bit ASCII character.
Content-type: Multipart / Mixed; boundary = "***"
- ***
Content-Type: Text / Plain; Charset = "ISO-8859-1"
This Message has an attachment.
- ***
Content-type: text / plain; name = "file.txt"
Attachment text.
- *** -
send email
Internet-based email usually uses SMTP network protocols to transmit. According to SMTP, when an email program needs to send an email, the program first establishes a two-way communication channel with the same SMTP service program (usually through the socket). This basic SMTP service program is perhaps the ultimate destination of this email, or it is only a springboard to another SMTP service. All in all, when the email program establishes a double-phase transmission channel with the SMTP service program, the email program sends a series of ASCII characters to the SMTP service, and the SMTP service program will generate corresponding responses to these commands indicate The corresponding operation is successful or failed. Let us assume that all the operations have been successful, then email programs will send mail to the SMTP service, if the email is the server running the SMTP service, then the SMTP service will join the mail database In otherwise the SMTP service program will forward the message to the SMTP service program on other SMTP servers until the destination is reached. Figure 2 illustrates this.
SMTP can identify a lot of emails to communicate with the SMTP service program. Some commands require parameters, and some commands are not required. But you must follow one after each command.
. The most commonly used commands are Helo, Mail, RCPT, DATA, RSET, and Quit. These six commands are given in the order in the above order. In addition to RSET, other commands must be sent in a specific order because the SMTP service program is based on state. For each e-mail program that establishes a two-way communication channel, the SMTP service program saves the current communication status. When an email program is connected to the SMTP service, the SMTP service program sends an initialization message to the email program. This message contains a three-digit response code, which is used to identify the SMTP service. In addition, the header of the message sent to the email program in the SMTP service program also has a response code, which is used to indicate successful operation or fail. After the email program receives these response, the corresponding work can be done according to the information contained therein. The text part of the message is given, and the email program can ignore the text section. After receiving the initialization message, the email program starts a transfer message by sending a helo command. Helo command has a parameter that marks the domain name of the server in the SMTP service. It will identify the SMTP service program in the SMTP service. In response, the SMTP service program performs some initialization work, set it yourself to the initial state to receive email. When these work is successfully completed, it sends a successful response message to the email program, which begins with the response code 250. After the Helo command, the email program sends a mail command. The mail command will identify the sender in the SMTP service program, which has two parameters: from: and an email address. If the SMTP service program can successfully resolve the email address, it usually returns a response message at the beginning of 250; whether the message will send back a response message indicating the failure. After Mail is the RCPT command. The RCPT command identifies a message recipient in the SMTP service program, which also has two parameters: to: and an email address. If the message is by multiple recipients, the program needs to send the RCPT command multiple times. After the RCPT command, the program needs to send an email itself. The program first sends a DATA command. When receiving the successful response message, send an email to the SMTP service program. When all rows are sent, the program sends a row consisting of a row. After that, the email program waits for the response message for the SMTP service program to determine that the message is received by the SMTP service program. After all this is successful, the program can send the RSET command to exit the mail transfer process. Finally, the program sends a Quit command when it is to be disconnected and the SMPT service program is established. The main reminder is that although the above command is capitalized, the case is not sensitive to the case of the actual protocol. Maybe you care about what is the format of the response code. The leftmost number represents whether the operation is successful, and the 1 represents the command, 2 represents the successful completion, 3 represents the following period, 4 representative operations temporarily unable to complete (email programs can be resended during the current mail transfer process Command), 5 representative operations cannot be completed (email programs cannot resend commands during current mail transfer). The second digit representative response domain, 0 represents a grammatical error, 1 represents a message request, 2 represents the transfer channel, 3 and 4 do not specify, 5 representatives related to the mail system. The most one-digit number is added to the second digit, which is no longer detailed here. According to the above information, we can see that the 250 represented command has been successfully completed; 220 Represents the SMTP service program is waiting for the help command; and 503 represents the command order error. Interested friends can see RFC 2821.
The following provides a command line-based example SMTPDEMO, which can help you understand the SMTP-based mail transport mechanism. This program will connect to an SMTP service using standard port 25. In order to make the program to run, you need to change Home to the address of the mail server you use. // smtpdemo.java
Import java.io. *;
Import java.net. *;
Class smtpdemo
{
Public static void main (string [] args)
{
String smtpserver = "home
INT SMTPPORT = 25;
Socket client = NULL;
Try
{
/ / Create a socket connection to the SMTP service program.
Client = New Socket (SMTPSERVER, SMTPPORT);
// Create a BufferedReader object to read the user input from the command line.
Bufferedreader stdin;
Stdin = New BufferedReader (NEW INPUTSTREAMREADER (System.in);
// Create a BufferedReader object to read the output from the socket.
InputStream IS = Client.getInputStream ();
Bufferedreader sockin;
Sockin = New BufferedReader (NEW InputStreamReader (IS));
// Create a PrintWriter object to write content to the socket.
Outputstream Os = Client.getOutputStream ();
Printwriter sockout;
SOCKOUT = New PrintWriter (OS, TRUE);
// Display the handshake process with the SMTP service program.
System.out.println ("S:" Sockin.Readline ());
While (True)
{
System.out.print ("C:");
// Read user input.
String cmd = stdin.readline ();
// Send the command input to the SMTP service program.
SOCKOUT.PRINTLN (CMD);
// Read the response message for the SMTP service program from the socket and display it on the screen.
String reply = sockin.readline ();
System.out.println ("s:" reply);
/ / If the data command is sent and the successful response message is sent, the line is read from the input device.
/ / These rows constitute an email until the journey is read until the journey consists entirely.
IF (cmd.tolowercase () .StartSwith ("Data") &&
Reply.substring (0, 3). Equals ("354")))
{
DO
{
CMD = stdin.readline ();
IF (cmd! = null && cmd.Length ()> 1 &&
cmd.charat (0) == '.')
CMD = "."
SOCKOUT.PRINTLN (CMD);
IF (cmd.equals (".")))
Break;
}
While (True);
// Read the response message from the SMTP service program and display.
Reply = sockin.readline ();
System.out.println ("s:" reply);
CONTINUE;
}
// If the user enters the Quit command, exit the program.
IF (cmd.tolowercase () .StartSwith ("quit"))
Break;
}
}
Catch (IOException E)
{
System.out.println (E.TOString ());
}
Finally
{
Try
{
IF (client! = null)
Client.Close ();
}
Catch (IOException E)
{
}
}
}
}
When you run SMTPDEMO, you will see the output below. Where C: follow is the user's input, S: followed by the information returned by the SMTP service.
S: 220 Home.digital.com Microsoft Esmtp Mail Service, Version: 4.0.2195.2966 Ready
At Fri, 13 DEC 2002 15:06:58 0800
After running SMTPDemo, the mail service program returns to initialization information.
C: Helo Digital.com
S: 250 Home.digital.com Hello [23.2.254.53]
Start the mail transfer process by sending the helo digital.com command. Digital.com is the domain name of the domain where the mail server is located. Then the mail service program returns the welcome information starting with 250.
C: mail from: rayfeng@digital.com
S: 250 2.1.0 rayfeng@digital.com .... Sender OK
Next is the information of entering the mail sender Mail from :. The mail service program returns successful information.
C: rcpt to: rayfeng@digital.com
S: 250 2.1.5 rayfeng@digital.com
Then via the RCPT TO: Specifies the recipient of the message.
C: Data
S: 354 Start Mail Input; End with
Subject: Test Email
This is the test email.
.
S: 250 2.6.0 Homeoulkez00vnuhkdy00000002@Home.digital.com Queued Mail for Delivery
Next is the content of entering the mail. After sending the DATA command, wait for the server to send back the back command to be successfully received response message. When receiving the response message starting with 354, you can enter the content of the email. After completion
end.
C: quit
S: 221 2.0.0 Home.digital.com Closing Connection
Finally, I'm exiting the process of sending an email. Please note that the response code 221, the leftmost 2 represents the operation, and the middle 2 indicates the transmission channel, and 1 means the connection is closed. I have discussed the issue of attachment. An attachment can also be sent via SMTPDEMO. By sending the following command to the mail service, file.txt can be added to the message as an attachment.
Helo Digital.net
Mail from: rayfeng@digital.com
RCPT to: rayfeng@digital.com
Data
Subject: Attachment Demo
Content-type: Multipart / Mixed; boundary = "***"
- ***
Content-Type: Text / Plain; Charset = "ISO-8859-1"
This Message has an attachment.
- *** Content-Type: Text / Plain; Name = "file.txt"
Attachment text.
- *** -
quit
To this end, we introduced how to use Java to implement the email tool to send the email tool, and analyze the mechanism for mail from the formation, I don't know if you have already mastered these content. In the next article, we will come together to study the reception function of the Email tool. Source: http://develop/article/ccidnet.com/pub/Article/c322_a33989_p1.html