SMTP-based Java email sending program!

Source: Internet
Author: User
Tags mailmessage smtpclient

If you encounter this problem, write it out and share it with you.

This program does not use the javamail API, but directly processes the sent mail according to the requirements of the SMTP protocol. Although it is troublesome, it is helpful to understand the details of the mail protocol.

This article is divided into two parts, the first part is the SMTP command introduction (this is copied from somewhere else, hey); the second part is a real understanding of the mail sending process through an instance.

I. Introduction to SMTP commands

What is SMTP
SMTP (Simple Mail Transfer Protocol): the transmission protocol used to transmit an email from a client to a server or from one server to another. SMTP is a request/response protocol. commands and responses are based on ASCII text and end with Cr and LF characters. The response includes a three-digit code that indicates the returned status. SMTP listens for connection requests on TCP port 25.

What is ESMTP?
ESMTP (Extended SMTP), as its name implies, is an extension of the standard SMTP protocol. It differs from the SMTP service in that the user account does not need to be verified when sending mail via SMTP. When sending mail via ESMTP, the server requires the user to provide the user name and password for authentication. The email sending process after verification is no different from the SMTP method.

SMTP commands include:
Helo identifies the user to the server. The sender can cheat and lie, but generally the server can detect it.
EHLO identifies the user to the server. The sender can cheat and lie, but generally the server can detect it.
The address specified in the mail from command is the sender address.
Rcpt to identifies a single email recipient; multiple rcpt to can be used; it is often behind the MAIL command.
After one or more RCPT commands, data indicates that all Email recipients have been identified, and data transmission is initialized, ending with CRLF. CRLF.
VRFY is used to verify whether the specified user or email address exists. This command is often disabled by the server for security reasons.
EXPN verifies whether the specified mailbox list exists and expands the mailbox list.
Help query commands supported by the server
No Noop operation, the server should respond OK
Rset resets the session and the current transmission is canceled.
Quit end session

Connect to postfix and use SMTP commands to send emails
For example, the IP address of the email server installed with Postfix is 192.168.0.1 (the Blue font content is input by the client, and the red font content is returned by the service)

Telnet 192.168.0.1 25 --------------------------------------------------- use the Telnet command to connect to port 25 of the server
Helo test.com ----------------------------------------------------------- send mail from command to the server to identify the user
EHLO test.com ----------------------------------------------------------- ESMTP command, the mail must be authenticated.
Auth login ---------------------------------------------------------------- for user Identity Authentication
334 vxnlcm5hbwu6
Y29zdgfayw1hegl0lm5lda = ----------------------------------- base64 encrypted user name
334 ugfzc3dvcmq6
Mtk4mjixna = -------------------------------------------------------- base64 encrypted password
235 authentication successfully -------------------------------- authentication successful
(535 authentication failed --------------------------------- ------ identity authentication failed)
Accounts sent to the domain name in the system can skip identity authentication.
Mail from: <test1@domain.com> ---------------------------- mail from address test1@domain.com
250 OK ------------------------------------------------------- ---------- the command is successfully executed.
Rcpt to: <test2@domain.com> -------------------------------- delivered to address test2@domain.com
250 OK ------------------------------------------------------- ---------- the command is successfully executed.
Data --------------------------------------------------------- data transmission Initialization
354 end data . ----------------------------------------- Start Data Transmission
From: test1@domain.com
To: test2@domain.com
Date: Mon, 25 Oct 2004 14:24:27 + 0800
Subject: Test mail

Hi, Test2
This is a test mail, you don't reply it.

.
------------------------------------------------------------ Data content, including base64 encrypted mail content, ends data transmission with CRLF. CRLF
250 OK: queued as 2f6de3929 ----------------------------------- Command Execution successful
Quit --------------------------------------------------------- end the session
221 bye
Connection closed by foreign host. ------------------------- disconnect

The above is a basic command for sending emails.

Let's talk about the basic process of sending emails:

If your email address is a@host.com, and you want to use this mailbox to send an email to the to@tohost.com, you need to connect to the server host.com, of course this connection may need to be authenticated, and now basically all have to be verified, then, send an email to the server host.com to close the connection. On host.com, the email you sent enters the sending queue. When it is your turn to send the email, the host.com host will contact tohost.com to transfer the email to the server tohost.com.

Ii. instance applications

Bytes -----------------------------------------------------------------------------------------------------------------------

Mailmessage. Java

----------------------------------------

// This class is actually a basic JavaBean that is used to complete the setting of some basic information, or you can simply write it in the program, but it is more clear, the modification is also convenient.

Package mail;

Public class mailmessage {
 
Private string from;
Private string;
Private string datafrom;
Private string datato;
Private string subject;
Private string content;
Private string date;
Private string user;
Private string password;

Public String GetPassword (){
Return password;
}

Public void setpassword (string password ){
This. Password = password;
}

Public String getuser (){
Return user;
}

Public void setuser (string user ){
This. User = user;
}

Public String getcontent (){
Return content;
}

Public void setcontent (string content ){
This. content = content;
}

Public String getdatafrom (){
Return datafrom;
}

Public void setdatafrom (string datafrom ){
This. datafrom = datafrom;
}

Public String getdatato (){
Return datato;
}

Public void setdatato (string datato ){
This. datato = datato;
}

Public String getdate (){
Return date;
}

Public void setdate (string date ){
This. Date = date;
}

Public String getfrom (){
Return from;
}

Public void setfrom (string from ){
This. From = from;
}

Public String getsubject (){
Return subject;
}

Public void setsubject (string subject ){
This. Subject = subject;
}

Public String getto (){
Return;
}

Public void setto (string ){
This. To =;
}

}

---------------------------------------------

Smtpclient. Java

------------------------------

// The main functions are completed here

Package mail;

Import java. Io. bufferedreader;
Import java. Io. bufferedwriter;
Import java. Io. ioexception;
Import java. Io. inputstreamreader;
Import java. Io. outputstreamwriter;
Import java.net. Socket;
Import java.net. socketexception;
Import java.net. unknownhostexception;
Import java. util. stringtokenizer;

Import sun. Misc. base64encoder;

Public class smtpclient {

Private Boolean DEBUG = true;
Base64encoder encode = new base64encoder (); // used to send the user name and password after Encryption
Public static void main (string [] ARGs) throws unknownhostexception, ioexception {
// Todo auto-generated method stub
Mailmessage message = new mailmessage ();
Message. setfrom ("wasingmon@163.com"); // sender
Message. setto ("wasingmon@eyou.com"); // recipient
String Server = "smtp.163.com"; // Mail Server
Message. setsubject ("test"); // subject
Message. setcontent ("test"); // mail content
Message. setdatafrom ("wangxingmou@eyou.com"); // sender, displayed in the sender column of the message
Message. setdatato ("wasingmon@163.com"); // recipient, displayed in the recipient column of the email
Message. setuser ("wasingmon"); // username used to log on to the mailbox
Message. setpassword (""); // password used to log on to the mailbox

Smtpclient SMTP = new smtpclient (server, 25 );
Boolean flag;
Flag = SMTP. Sendmail (message, server );
If (FLAG ){
System. Out. println ("email sent successfully! ");
}
Else {
System. Out. println ("failed to send email! ");
}

}
Private Socket socket;
Public smtpclient (string server, int port) throws unknownhostexception, ioexception {
Try {
Socket = new socket (server, 25 );
} Catch (socketexception e ){
System. Out. println (E. getmessage ());
} Catch (exception e ){
E. printstacktrace ();
} Finally {
System. Out. println ("A connection has been established! ");
}

}
// Register with the email server
Public void Helo (string server, bufferedreader in, bufferedwriter out) throws ioexception {
Int result;
Result = getresult (in );
// After the email service is connected, the server returns a 220 response
If (result! = 220 ){
Throw new ioexception ("failed to connect to the server ");
}
Result = sendserver ("HELO" + server, in, out );
// 250 is returned after the HELO command is successful
If (result! = 250)
{
Throw new ioexception ("An error occurred while registering the email server! ");
}
}
 
Private int sendserver (string STR, bufferedreader in, bufferedwriter out) throws ioexception {
Out. Write (STR );
Out. newline ();
Out. Flush ();
If (Debug)
{
System. Out. println ("sent command:" + Str );
}
Return getresult (in );
}
Public int getresult (bufferedreader in ){
String line = "";
Try {
Line = in. Readline ();
If (Debug ){
System. Out. println ("server return status:" + line );
}
} Catch (exception e ){
E. printstacktrace ();
}
// Read the status code from the server response message and convert it to an integer.
Stringtokenizer ST = new stringtokenizer (line ,"");
Return integer. parseint (St. nexttoken ());
}
 
Public void authlogin (mailmessage message, bufferedreader in, bufferedwriter out) throws ioexception {
Int result;
Result = sendserver ("auth login", in, out );
If (result! = 334 ){
Throw new ioexception ("user verification failed! ");
}

Result = sendserver (encode. encode (message. getuser (). getbytes (), in, out );
If (result! = 334 ){
Throw new ioexception ("the user name is incorrect! ");
}
Result = sendserver (encode. encode (message. GetPassword (). getbytes (), in, out );

If (result! = 235 ){
Throw new ioexception ("Verification Failed! ");
}
}
// Start to send the message, mail Source Address
Public void mailfrom (string source, bufferedreader in, bufferedwriter out) throws ioexception {
Int result;
Result = sendserver ("mail from: <" + Source + ">", in, out );
If (result! = 250 ){
Throw new ioexception ("specified source address error ");
}
}
// Set the email recipient
Public void RCPT (string touchman, bufferedreader in, bufferedwriter out) throws ioexception {
Int result;
Result = sendserver ("rcpt to: <" + touchman + ">", in, out );
If (result! = 250 ){
Throw new ioexception ("the specified destination address is incorrect! ");
}
}
 
// Body
Public void data (string from, string to, string subject, string content, bufferedreader in, bufferedwriter out) throws ioexception {
Int result;
Result = sendserver ("data", in, out );
// After entering data, press Enter. If you receive the 354 response, continue to enter the email content.
If (result! = 354 ){
Throw new ioexception ("data cannot be sent ");
}
Out. Write ("from:" + from );
Out. newline ();
Out. Write ("to:" + );
Out. newline ();
Out. Write ("Subject:" + subject );
Out. newline ();
Out. newline ();
Out. Write (content );
Out. newline ();
// Enter the end email content after the end and press ENTER
Result = sendserver (".", in, out );
System. Out. println (result );
If (result! = 250)
{
Throw new ioexception ("data sending error ");
}
}
 
// Exit
Public void quit (bufferedreader in, bufferedwriter out) throws ioexception {
Int result;
Result = sendserver ("quit", in, out );
If (result! = 221 ){
Throw new ioexception ("failed to exit correctly ");
}
}
 
// Main program for sending emails
Public Boolean Sendmail (mailmessage message, string server ){
Try {
Bufferedreader in = new bufferedreader (New inputstreamreader (socket. getinputstream ()));
Bufferedwriter out = new bufferedwriter (New outputstreamwriter (socket. getoutputstream ()));
Helo (server, in, out); // HELO command
Authlogin (message, in, out); // auth login command
Mailfrom (message. getfrom (), in, out); // MAIL FROM
RCPT (message. getto (), in, out); // RCPT
Data (message. getdatafrom (), message. getdatato (), message. getsubject (), message. getcontent (), in, out); // data
Quit (In, out); // quit
} Catch (exception e ){
E. printstacktrace ();
Return false;

}
Return true;
}

}

Because SMTP authentication is usually required for SMTP servers, this verification is also added in this example. Otherwise, it will not be sent in the mail (as I did in the beginning ), the necessary comments in the program are also basically available. I believe that beginners can easily understand them.

End!

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.