JAVA-SMTP send mail

Source: Internet
Author: User
Tags mailmessage smtpclient

 

Author: Rockay (Liu Qichao, Liu Tao)Page: http://www.cnblogs.com/RockayEmail: rockay_liu@126.com

Note: Some of them refer to online materials.

 

Recently, a JAVA mail group function has been provided for friends. Because I have been engaged in. NET in the past year, and JAVA has almost forgotten it, I checked some information online. Share with you:

SMTP command

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

 

Title

//////////////////////////////////////// /// MailMessage entity class ////////////////////////////////// /////

 

Package gxa. sf. rockay;

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;

/**
* SMTP client call class
* @ Author Rockay (Liu Qichao, Liu Tao)
* Http://www.cnblogs.com/Rockay
*/

Public class SMTPClient {
 
Public SMTPClient ()
{

}
Private boolean debug = true;
BASE64Encoder encode = new BASE64Encoder (); // used to send the user name and password after Encryption

Public boolean Send (String server, String from, String [] to, String [] cc, String [] bc,
String subject, String content, String user, String pwd) throws UnknownHostException, IOException
{
MailMessage message = new MailMessage ();
Message. setFrom (from); // sender
For (int I = 0; I <to. length; I ++)
{
Message. setTo (to [I]); // recipient
Message. setDatato (to [I]); // recipient, displayed in the recipient column of the email
}
For (int I = 0; I <cc. length; I ++)
{
Message. setCc (cc [I]); // recipient
}
For (int I = 0; I <bc. length; I ++)
{
Message. setBc (bc [I]); // recipient
}
Message. setDatafrom (from); // sender, which is displayed in the sender column of the email.

Message. setSubject (subject); // subject
Message. setContent (content); // mail content
Message. setUser (user); // user name used to log on to the mailbox
Message. setPassword (pwd); // 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! ");
}
Return flag;
}

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;
}
}

 

 

 

 

//////////////////////////////////////// /// SMTP client call class ///////////////////////////////// //////

Package gxa. sf. rockay;

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;

/**
* SMTP client call class
* @ Author Rockay (Liu Qichao, Liu Tao)
* Http://www.cnblogs.com/Rockay
*/

Public class SMTPClient {
 
Public SMTPClient ()
{

}
Private boolean debug = true;
BASE64Encoder encode = new BASE64Encoder (); // used to send the user name and password after Encryption

Public boolean Send (String server, String from, String [] to, String [] cc, String [] bc,
String subject, String content, String user, String pwd) throws UnknownHostException, IOException
{
MailMessage message = new MailMessage ();
Message. setFrom (from); // sender
For (int I = 0; I <to. length; I ++)
{
Message. setTo (to [I]); // recipient
Message. setDatato (to [I]); // recipient, displayed in the recipient column of the email
}
For (int I = 0; I <cc. length; I ++)
{
Message. setCc (cc [I]); // recipient
}
For (int I = 0; I <bc. length; I ++)
{
Message. setBc (bc [I]); // recipient
}
Message. setDatafrom (from); // sender, which is displayed in the sender column of the email.

Message. setSubject (subject); // subject
Message. setContent (content); // mail content
Message. setUser (user); // user name used to log on to the mailbox
Message. setPassword (pwd); // 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! ");
}
Return flag;
}

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 );
AuthLogin (message, in, out );
Mailfrom (message. getFrom (), in, out)
Rcpt (message. getTo (), in, out );
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;
}
}

 

 

Related Article

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.