Talk about using Java to implement the socket programming of SMTP sending mail

Source: Internet
Author: User
Tags base64 map vector what interface

Many other content Welcome to personal site Http://icodeyou.com

A few days ago using the socket to implement the Java language to build webserver, the whole process should be the socket this thing has been used very familiar. Although abstract, once used once you will feel how powerful it is in network communication. Well, just keep using the socket today to practice sending a simple email using the SMTP protocol below. Today's story is, I'm asking my Goddess to go out to dinner ~ ~ ~ So, face SMTP. Only succeed, don't fail.

The global assumption my mailbox for [email protected] Goddess's mailbox for [email protected] password are computer (yo, or a couple mailbox ~)

In order to embody the procedural ape's tall. So I chose to use the command line Way (SB program ape:

。 )。 Open cmd, and at the command line, type Telnet, "well. To show me that Telnet is not an internal or external command "! What to do, this is the first step. On the wrong foot, it seems that today to kneel, quickly want to solve the method. Go to Control Panel---programs and features---Start or turn off Windows features---telnetclient. Tick on and then OK (some people's computers will also see "Telnet Server", be careful not to choose the wrong.) The server is for your computer to be logged in as the servers, and what we have to do now is to use our own computer as client landing Mailbox server.

Try again in cmd, direct input Telnet smtp.163.com 25, the first line shows the welcome message returned by mail server, I return here is "163.com anti-spam GT for Coremail System (163co M[20121016]) "220 indicates that the mail server has established a connection with me, it has started to want to help me, haha. Friendly, with the server Big Brother say hello, input HELO Huan , (Huan is casually input, enter anything. Server is not the bird you enter what exactly), then the server returned is "OK", indicating that now the server waiting for me to continue to send commands.

Enter MAIL from:<[email protected] > The server unexpectedly returned to me 553, and told me to need certification. Also, since the landing of the server, there must be someone else's account.

So then enter AUTH LOGIN. The server returned 334 and something I couldn't read, which required us to enter username and password information. But all know, like usernamepassword such information can not be transmitted in the Internet in plaintext, and smtpserverusername and password use is Base64 encoded encryption method, So in Baidu search an online base64 encryption site is good. (for example, http://base64.xpcha.com/).

The obtained ciphertext to the console paste after the carriage return, then the server will ask me to enter password, and just like the way you can, assuming the correct words. will return 235. And told me that the certification was successful. Perfect. has progressed to half. Go on!

I will tell the server from which mailbox to send, to whom. So enter MAIL from:<[email protected] > Enter RCPT to:<[email protected] > after the return sender and the recipient are set up. Naturally it's time to tell the server what I'm going to send, so enter DATA and return, the server returns me 354, and let me enter to <CR><LF>.<CR><LF> end, OK. Then enter the text directly: Can I date with you?

Then "enter" "." "Enter" to tell the server that my content input is complete. It can be sent out. This time the shocking scene appeared. The server did not give me the correct code to return 2XX, but returned 554 to me. That's why. The server brother won't help me?

Watch it give me the link, like 163 of my own error description document. I copied it, opened the browser to see a bit, the original is 163server think I sent is junk mail. So it refused to send me letters. But eldest brother, I this is true, ah, which is what junk mail ah, please let me send it (think about it too, assuming that a lot of people have sent the goddess a bunch of junk mail, I will be unhappy%>_<%).

Analyze why it is considered spam: The message must have a subject (subject), the sender (from). Recipient (to). Message body, and so on. But I just wrote an email message, and maybe the server thinks it's junk mail. Well, the more you imagine, the more reasonable, try it. This time I entered the data.  Server Let me enter the content, I first entered the subject:would you go on a date with me?    Then enter from:[email protected] Enter To:[email protected] Enter Can you eat a meal together? Enter. Enter haha, this time the server returned to me is mail OK, I sent a successful!

The next step was to wait for the goddess's answer.

。。 All process See: (Leave a question, the Goddess's mailbox will certainly receive this email, but will receive I originally wanted to send the text "Can you eat a meal together?"

"?" Suppose not to know. Check the message format. or see the following Java program, control the data format after the body part of the difference)


All processes:

Telnet smtp.163.com 25s:220 163.com anti-spam GT for coremail System <163com[20121016]>c:helo huans:250 Okc:auth logins:334 dxnlcm5hbwu6c:y25zbxrwmde=s:334 ugfzc3dvcmq6c:y29tchv0zxi=s:235 Authentication Successfulc:mail FROM:< ; [Email protected]>s:250 mail okc:rcpt to:<[email protected]>s:250 mail okc:datas:354 End data with <cr> ; <lf>.<cr><lf>c:subject:would you go on a date with me? C:from:[email Protected]c:to:[email Protected]c:can you eat a meal together? C:. s:250 Mail OK Queued as Smtp7,c8cowedpwfyp_eruqxx8aa--. 14s2 1413807190c:rsets:250 okc:quits:221 Bye


It was almost the same, and I thought the goddess would have sent me an email. How to see, open the browser to enter 163 mailbox? Too out, too low. Direct command Line! Telnet pop.163.com 110, which has just demonstrated all of the SMTP commands. So the operation of pop should be very easy, direct:

Did you see what the goddess replied to me?

。 Dog Blood.

All right. The process of sending and receiving mails is all conquered. And the result is. ,。 was rejected. Actually, it is. I did not say, my Goddess is numbered, from goddess No. 0, goddess number 1th ... Goddess N, did I decay after the No. 0 goddess rejected me? How to do that, I have to get more and more brave, continue to send messages to the rest of the goddess. But, I am so many goddess, I can not send every goddess e-mail to use such a command line, it does not kill me. So the question is-----------which strong? Since we are learning computer, we should make software. Let the software for our bulk hair, simply perfect!

So back to this issue, how to use Java to implement SMTP send mail? Yes, or ask for a big God socket to help.

Experienced the last time the socket was tortured and the command line just honed. The next step is to put them in a smart mix. So, don't go away.

1, define some we will use the mailbox name, Usernamepassword and other information (normal programming No one will write username and password so clear ...

):

String sender = "[email protected]";         String receiver = "[email protected]om";         String Password = "Computer";//As stated above, this username and password are to be encrypted using Base64. The encryption method is described in Appendix 1 below for specific explanations of         String user = new Base64encoder (). Encode (sender.substring (0, Sender.indexof ("@")). GetBytes ());  Intercept "CNSMTP01" and encrypt         String pass = new Base64encoder (). Encode (Password.getbytes ());   Encrypt "Computer"

2. Establish socket connection:

Socket socket = new Socket ("smtp.163.com");  SMTP Service uses port 25th for monitoring

3. Get the input and output stream of the socket

        InputStream InputStream = Socket.getinputstream ();         OutputStream outputstream = Socket.getoutputstream ();         BufferedReader reader = new BufferedReader (new InputStreamReader (InputStream));         PrintWriter writter = new PrintWriter (OutputStream, true);  I TM go to this true too key. I didn't write this particular hole! You can try to do this without adding the effect. Appendix 2 below will write why plus true

4. Send helo information

        HELO         writter.println ("HELO Huan");         System.out.println (Reader.readline ());


5. Send Auth Login information

        AUTH Login         writter.println ("AUTH login");         System.out.println (Reader.readline ());         WRITTER.PRINTLN (user);         System.out.println (Reader.readline ());         Writter.println (pass);         System.out.println (Reader.readline ());         Above   Authentication Successful


6. Send sender and recipient information

        Set Mail from   and   rcpt to         writter.println ("Mail from:<" + sender + ">");         System.out.println (Reader.readline ());         Writter.println ("rcpt to:<" + receiver + ">");         System.out.println (Reader.readline ());


7. Tell the server I want to pass data

        Set Data         writter.println ("data");         System.out.println (Reader.readline ());


8. Email subject, recipient, sender, text

        Writter.println ("Subject: Goddess, is Me");         Writter.println ("From:" + sender);         Writter.println ("to:" + receiver);         Writter.println ("content-type:text/plain;charset=\" gb2312\ "");//Assume that the sending body must add this. And the following should have a blank line         writter.println ();         Writter.println ("Goddess." Can I have dinner in the evening? ");         Writter.println ("."); /Tell the server what I sent to complete the         writter.println ("");         System.out.println (Reader.readline ());


9, help you e-mail, thank the server, and it say goodbye bar, do not have to invite it to eat, how good

        Writter.println ("RSet");         System.out.println (Reader.readline ());         Writter.println ("Quit");         System.out.println (Reader.readline ());


So, with exceptions and so on, all the code such as the following:

public class Smtpmain {public static void main (string[] args) {String sender = "[email protected]";         String receiver = "[email protected]";         String Password = "Computer";         String user = new Base64encoder (). Encode (sender.substring (0, Sender.indexof ("@")). GetBytes ());        String pass = new Base64encoder (). Encode (Password.getbytes ());             try {Socket socket = new Socket ("smtp.163.com", 25);             InputStream InputStream = Socket.getinputstream ();             OutputStream outputstream = Socket.getoutputstream ();             BufferedReader reader = new BufferedReader (new InputStreamReader (InputStream));  PrintWriter writter = new PrintWriter (OutputStream, true);             I TM go to this true too key!             System.out.println (Reader.readline ());             HELO writter.println ("HELO Huan");             System.out.println (Reader.readline ());   AUTH login writter.println ("AUTH login");          System.out.println (Reader.readline ());             WRITTER.PRINTLN (user);             System.out.println (Reader.readline ());             Writter.println (pass);             System.out.println (Reader.readline ()); Above authentication successful <pre name= "code" class= "Java" >  
            Set Mail from and RCPT to Writter.println ("Mail from:<" + sender + ">");             System.out.println (Reader.readline ());             Writter.println ("rcpt to:<" + receiver + ">");                        System.out.println (Reader.readline ());             Set Data writter.println ("data");             System.out.println (Reader.readline ());             Writter.println ("Subject: Goddess, is Me");             Writter.println ("From:" + sender);             Writter.println ("to:" + receiver);             Writter.println ("content-type:text/plain;charset=\" gb2312\ "");             Writter.println (); Writter.println ("Goddess, can you have dinner in the evening?")             ");             Writter.println (".");             Writter.println ("");             System.out.println (Reader.readline ());             Say GoodBye writter.println ("RSet");             System.out.println (Reader.readline ());             Writter.println ("Quit"); System.out.println (Reader.readlINE ());            } catch (Exception e) {e.printstacktrace (); }         }   }

This, I am completely not afraid of Lanxiang excavator, this is my date artifact. Just to change the goddess X mailbox, the program is executed, I sent the message instantly, haha, simply witty like a dog.

Now execute the program, look at the console output

Execute the program several times, Goddess No. 1th. Number 2nd ... e-mail messages (such as the ability to add multiple goddess mailboxes to the collection [list map vector ...] In And then one more cycle. Minutes to take care of)

As to what interface or what. Let's benevolent see the beholder. Accustomed to the Java swing, accustomed to Android can also be XML, in fact I think Android is more convenient, the control is easier to use some. It is recommended to use Windows Builder if you forget the Java write interface. can help you to draw the interface very quickly. Then all you have to do is get the controls, write the listener, and so on.

Appendix 1:

About Base64 Encryption:

Details what is Base64 encryption, such a concept of something can be found in the Baidu Encyclopedia I will not say. Say how to use it in Java.

1, first download a tool jar file, called "Sun.misc.BASE64Decoder.jar" (Baidu Search can be found, assuming that I can not find the last offer I github up to download down to use)

2. After having the jar file. The jar package needs to be imported into project by right-clicking the project name-build path-configure Build path-add External JARS, and selecting the jar package you just downloaded is ok

3. Then write to the new Base64encoder () in the Java file. Encode (Password.getbytes ()); When You will be prompted not to import the appropriate package, you can press CTRL + Shift + O (OU) to let the IDE to voluntarily import for us (if your JAR package import is not a problem)

Appendix 2:

Talk about the Printwriter.println () method (or the Write () method, in fact, a line break, the rest of the parameters are the same).  PrintWriter writter = new PrintWriter (OutputStream, true); In the Printwritter constructor. Can not add true. Can also add true, the difference is: Add true, the following writter.println ("HelloWorld"), after the "HelloWorld" will be sent out immediately, instead of true, Must be in Writter.println ("HelloWorld"), and then call Writter.flush (); To empty the buffer and force it to be sent out. I started without adding true, and did not call the flush () method, I thought it was serversb, the result.

。。

Appendix 3:

Why Telnet the POP protocol when logging in to server input username and password will be clear, which makes me very strange, I want someone to help me answer.

Appendix 4:

Have you noticed that when using the SMTP protocol, authentication requires you to enter the sender's information. Do you want to write the sender's information again after entering data? Is the server stupid, do you have to enter two times? Can think about why. Then try it yourself, because we usually use the e-mail agent to the two feel that the same, so cover up a message when the small trick, that can disguise deception. Give yourself a try in detail. The impression will be more profound.

Appendix 5:

Uppercase and lowercase issues. Did you notice that the command part I typed in Cmd was capitalized, and the commands that were output in the Java program were all lowercase? I would like to say that the command section does not distinguish between uppercase and lowercase, but the following commands are strictly differentiated in uppercase and lowercase, you can try. (such as mailbox username and password are originally to distinguish between uppercase and lowercase bar)

Appendix 6:

Questions about the Telnet itself.

A line in Telnet entered the wrong data. I want to delete and then continue entering the correct, enter. This time you will find that the input is not a problem, but the server returned is the error code, for example, error:bad syntax reason is to command you to enter the correct one time. Suppose you lose the wrong way halfway. No backspace, it's late, just hit a return. will be the error, and then the right to enter the correct. Suppose you always make a mistake, like a 163server to disconnect you directly, it thinks you malicious to attack it. Like Sina's mailbox server, is very loyal, in the effective connection time has been waiting for you to enter the correct command, this can be self-test.


Appendix 7:

Remember when I used the shell to send a message in Linux, I didn't have to force me to log on to the mailbox server with a legitimate identity to send mail operations, why? Because at that time my own machine is equivalent to SmtpServer. Of course I don't have to verify my identity. Now you want to use the SMTP protocol to log in to someone else's server (such as 163), at which point 163 will need a legitimate user identity talent to log on to the concurrent mail.


This article also explains: This is just to understand a very basic explanation of SMTP. For the Code section. In order to embody the main body, there is obviously lack of the server return code inference statement, so the above program lacks robustness. In understanding the actual programming should consider the real network request situation, consider the packet loss situation, according to the server return code for the corresponding inference.

Well, it's written here, I'm going to have dinner with the goddess ~ where there is a problem can be in the following message ~

Personal Github:http://github.com/icodeu

Code Escrow Address: Http://github.com/icodeu/JavaForSMTP

Personal number: Qqwanghuan only for technical exchange

Many other content Welcome to personal site Http://icodeyou.com

Talk about using Java to implement the socket programming of SMTP sending mail

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.