Send email with java Development Email tool

Source: Internet
Author: User
Tags exit command line ftp header implement socket stdin java web
Send mail Author: Feng

This article describes how to use the Java Web API to implement an e-mail tool. Typically, email tools use the SMTP (Simple Mail Transfer Protocol, Simplicity Mail Transfer Protocol) to send mail and use the POP3 protocol to accept e-mail messages. Only the two protocols are briefly described 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

Although the JavaMail API is provided in Java, I will not use the JavaMail API in this article because I'll discuss how e-mail software works from the bottom up. The examples in this article were developed under J2SE 1.4.


Format of e-mail


Before you develop your email software, you need to know the format of your email. According to RFC 2882 (http://www.faqs.org/rfcs/rfc2822.html), e-mail is made up of a number of rows, each of which ends with 〈crlf〉 (ASCII code 13 and ASCII code 10). The maximum length of each row is 998 characters. Some of these lines provide the information necessary to send and receive e-mail messages, which are called headers, and all headers form the Header field (header field). Other lines are used to save the details of the message.

The header field provides a lot of information, including the source of the message, the destination of the message, and the subject of the message. Each header is comprised of a name and a colon plus the corresponding value. For example, from:, Send: And reply-to: The source of the message is recorded. The author of the message is recorded in from: The agent that sent the message (either the mail address or the machine name) is specified in sender: reply-to: The e-mail address that accepts the reply is specified in.

A message may have multiple authors, so you can specify one or more mailbox addresses from:. Here are examples from:

From:ray feng〈rayfeng@yahoo.com.cn〉, bogus@yahoo.com.cn



There can be only one sender in an e-mail message. Therefore sender: The value can only contain one mailbox address. If there is only one author in from: and the value of sender: is the same as the value from: Then sender: It will not appear in the e-mail message, otherwise information redundancy will occur, and vice versa sender: Should appear in the message. Here is an example of a sender:

Sender:ray Feng rayfeng@yahoo.com.cn



In an e-mail message, you can specify that a reply be sent to multiple mailbox addresses. So reply-to: can contain one or more mailbox addresses, separated by commas between each address. If there is a reply-to in the message: The reply will be sent to all the addresses listed in reply-to: If there is no reply-to in the message: The reply will be sent to the address listed in from:. So who's going to get the mail? To: and CC: The mailbox address of the accepted message is saved. Both values can contain multiple mailbox addresses.

In addition to the source and recipient of the message, RFC 2882 also defines a number of other headers, such as Subject: Topics that contain e-mail messages. The following is an example of an E-mail header field:

From:ray feng〈rayfeng@yahoo.com.cn〉
to:bogus〈bogus@yahoo.com.cn〉
cc:john〈john@yahoo.com.cn〉
Subject:test Email



Attachment

In mime, a binary file is allowed to be added to an e-mail message, and the file being added is called an attachment. The contents of the attachment can be transmitted as part of the message. What if MIME is implementing this functionality? A lot of headers are introduced in mime, and the most important thing associated with attachments is Content-type: and content-tracnsfer-encoding:. To distinguish between different parts of an e-mail message, MIME requires that a boundary parameter be included in the content-type:multipart/mixed header. The value of the boundary parameter is a string in double quotes. With this string, the program can differentiate between different parts of an e-mail message. Before transmitting the contents of an e-mail message, the program first transmits a 〈crlf〉, two hyphens, and boundary parameters. When the email content is completed, the program transmits the boundary parameters and two hyphens at the end.

The following email contains two sections, one of which is a text consisting of iso-8859-1 characters, and part of an attachment named File.txt. This does not contain the content-transfer-encoding: header, which indicates that the default 7-bit ASCII character is used.

content-type:multipart/mixed; boundary= "* * *"
--***
Content-type:text/plain; charset= "Iso-8859-1"
This message is has an attachment.
--***
Content-type:text/plain; Name= "File.txt"
Attachment text.
--***--




Send E-mail






screen.width-333) this.width=screen.width-333; " >

internet-based e-mail is usually transmitted using the SMTP network protocol. According to SMTP, when an e-mail program needs to send an e-mail message, the program first establishes a two-way communication channel (usually through sockets) for the same SMTP service program. This basic SMTP service may be the ultimate destination for this e-mail, or it may be just a springboard to another SMTP service program. In general, when an e-mail program establishes a dual-phase transport channel with an SMTP service program, the e-mail program sends a series of ASCII-character-based commands to the SMTP service program, and the SMTP service responds to these commands to indicate whether the operation succeeded or failed.

Let's assume that all the operations are successful, then the e-mail program will send the message to the SMTP service program, and if the e-mail address is exactly the server that the SMTP service is running on, the SMTP service will join the mail in the mail database. Otherwise, the SMTP service will forward the mail to the SMTP service program on the other SMTP server until the destination is reached. Figure II illustrates this by illustration.





SMTP recognizes many of the commands that e-mail messages use to communicate with the SMTP service program. Some commands require parameters, and some commands are not required. But each command must be followed by a 〈crlf〉. The six most commonly used commands are helo,mail,rcpt,data,rset and quit.

It is no coincidence to give these six orders in the order shown above. In addition to RSet, other commands must be sent in a specific order because the SMTP service is state based. For each e-mail program that establishes a two-way communication channel, the SMTP service saves the current communication state.

When an e-mail program is contacted with an SMTP service program, the SMTP service sends an initialization message to the e-mail program. The message contains a three-bit response code that is used to identify the SMTP service program. In addition, the headers of messages sent to an e-mail program by the SMTP service have a response code, which is used to indicate a successful or unsuccessful operation. After the e-mail program receives these response codes, it can complete the work according to the information contained therein. The text part of the message is for people to see, and the e-mail program can ignore the text section.

When an initialization message is received, the e-mail program begins to transmit the message by sending the HELO command. The HELO command has a parameter that flags the domain name of the server on which the SMTP service is located. It identifies the SMTP service program in the SMTP service program. In response, the SMTP service does some initialization work, setting itself to the initial state to receive e-mail. When the work is completed successfully, it sends back a successful response message to the e-mail program, which begins with response code 250.

After the HELO command, the e-mail program sends the Mail command. The Mail command identifies the departing person in the SMTP service program, which has two parameters: from: and an e-mail address. If the SMTP service can successfully resolve an e-mail address, it usually returns a response message that starts with 250, and no person sends back a response message that indicates the operation failed.

After Mail is the RCPT command. The RCPT command identifies the recipient of a message in the SMTP service program, and it has two parameters: to: and an e-mail address. If a message is sent by more than one recipient, the program needs to send the RCPT command multiple times.

After the RCPT command, the program needs to send the email itself. The program sends a data command, and when it receives a successful response message, sends the e-mail message line to the SMTP service, and when all the rows are sent, the program sends a line that consists of a period. After this, the e-mail program waits for the SMTP Service program's response message to determine that the message was received properly by the SMTP service program. After all this is successful, the program can send the RSet command to exit the message transfer process. Finally, when you want to disconnect from the Smpt service program, the program sends the QUIT command. The main caveat is that although the above commands are uppercase, the actual protocols are not sensitive to case.
Now maybe the question you're concerned about is how the response code is formatted. The leftmost digit represents the success of the operation, 1 delegates receive the command, 2 represents the successful completion of the operation, 3 waits for subsequent commands, and 4 represents a temporary failure to complete the operation (the e-mail program can resend the command during the current message transfer). 5 means that the operation cannot be completed (the e-mail program cannot resend the command during the current message transfer). The second digit represents the field of the response, 0 represents a syntax error, 1 represents a message request, 2 represents a transmission channel, 3 and 4 are not specified, and 5 is associated with the messaging system. The second digit is supplemented by a number that is not detailed here. Based on the information above, we can see that 250 of the requested commands have completed successfully, 220 on behalf of the SMTP service waiting for the HELO command, and 503 for the command order error. Interested friends can refer to RFC 2821.

The following provides a command-line-based example Smtpdemo, which helps you understand the SMTP-based message transfer mechanism. This program will use standard port 25 to connect to an SMTP service program. In order for the program to run, you need to change home to the address of the mail server you are using.

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
{
Establish a socket connection to the SMTP service program.
Client = new Socket (SmtpServer, Smtpport);
Create a BufferedReader object to read user input from the command line.
BufferedReader stdin;
stdin = new BufferedReader (new InputStreamReader (system.in));
Creates a BufferedReader object to read the output from the socket.
InputStream is = Client.getinputstream ();
BufferedReader Sockin;
Sockin = new BufferedReader (new InputStreamReader (IS));
Creates a PrintWriter object to write content to the socket.
OutputStream OS = Client.getoutputstream ();
PrintWriter sockout;
Sockout = new PrintWriter (OS, true);
Displays 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 ();
Sends the command entered by the user to the SMTP service program.
Sockout.println (CMD);
Reads the response message from the SMTP service program from the socket and displays it on the screen.
String reply = Sockin.readline ();
System.out.println ("S:" + Reply);
If you send the data command and get a successful response message, read the row from the input device,
These lines form an e-mail message until they are read to a line that consists entirely of a period.
if (Cmd.tolowercase (). StartsWith ("Data") &&
Reply.substring (0, 3). Equals ("354"))
{
Todo
{
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 it.
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: followed by the user's input, S: followed by the information returned by the SMTP service program.

s:220 home.digital.com Microsoft ESMTP MAIL Service, version:4.0.2195.2966 ready
At Fri 2002 15:06:58 +0800



When Smtpdemo is run, the Mail Service program returns initialization information.

C:helo digital.com
s:250 home.digital.com Hello [23.2.254.53]



Start the message transfer process by sending the helo digital.com command. Digital.com is the domain name for the mail server. The Mail service then returns a welcome message that starts with 250.

C:mail from:rayfeng@digital.com
s:250 2.1.0 Rayfeng@digital.com....sender OK



The next step is to enter the message sender's information mail from:. The Mail Service returned success information.

C:RCPT to:rayfeng@digital.com
s:250 2.1.5 Rayfeng@digital.com



Then it is through RCPT to: Specifies the recipient of the message.

C:data
s:354 Start mail input; End with〈crlf〉.〈crlf〉
Subject:test Email
This is the test Email.
.
s:250 2.6.0 HOMEOulkEZ00VNuHKDy00000002@home.digital.com Queued mail for delivery



The next step is to enter the contents of the message. After the data command is sent, wait for the server to send back a response message that the command was successfully received. When you receive a response message that starts with 354, you can enter the contents of the e-mail message. Finish with 〈crlf〉.〈crlf〉 end.

C:quit
s:221 2.0.0 home.digital.com Closing connection



Finally quit the process of sending e-mail. Note that response code 221, the leftmost 2 represents the success of the operation, the middle 2 represents the transmission channel, 1 means the connection is closed.

I have discussed the issue of annexes before. Attachments can also be sent via Smtpdemo. By sending the following command to the Mail Service program, you can add file.txt as an attachment in your message.

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 is has an attachment.
--***
Content-type:text/plain; Name= "File.txt"
Attachment text.
--***--
Quit



So far, we have introduced how to use Java to implement the sending function of email tools, and from the formation analysis of the mechanism of mail delivery, I do not know whether you have mastered these content. In the next article, we'll look at the receiving function of the email tool.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.