Web development (10) Use javamail to send mail, (using QQ, 163, Sina mailbox server)

I saw a good article on the Internet, written in detail.

The following is a reference to that blog post. Reprinted in "http://www.cnblogs.com/whgk/p/6506027.html", it is here for reference only.

 

The principle of sending emails

    Before understanding its principle, you must know two protocols, SMTP and POP3

      SMTP: Simple Mail Transfer Protocol, the Simple Mail Transfer Protocol, the protocol for sending mail, the default port, 25

      POP3: Post Office Protocol 3, the post office protocol, the protocol for receiving mail, the default port, 110

    Knowing these two protocols, let's talk about the schematic diagram of email sending and receiving. There are two types. The same email (QQ mailbox to QQ mailbox) and different emails (QQ mailbox to 163 mailbox) are different.

          

       explain:    

          For the sake of convenience, the Sina mailbox, [email protected] is referred to as user A, and the Sohu mailbox, [email protected] is referred to as user B

        User A (Sina mailbox, [email protected]) sends an email to user B (Sohu mailbox, [email protected]), then the whole process is the solid line part in the figure. User A uses OutLook (browser or Client) log in to their email account, write emails, use the Smtp protocol to send to the Smtp server (specially used for sending) in Sina's mail server, and then transmit to the Smtp server in Sohu's mail server through the SMTP protocol , and then send the email to user B's storage device through Sohu's Smtp server for storage (each user will have a storage space for storing emails). At this point, user A is equivalent to sending successfully, because it has arrived. Destination, if user B needs to view the content of the mail, it must be obtained from its own storage device through the POP3 server, and then returned to the browser or client to display.

        User B sends an email to user A, then the whole process is the dotted line part in the figure, which is the same step as A sends to B

        User A sends an email to a user C who also uses Sina mailbox, then the process is much simpler, first through the SMTP server, and then the smtp server will send it to the storage device of user C, and A sends the email successfully Now, if user C wants to display the mails in his mailbox, he will fetch all the mails from his own storage device through the POP3 server for viewing.

 

 

2. Send emails through Java code

     2.1. Prepare the jar package

        core: mail.jar

        Dependency: activation.jar, used when emails need to send attachments

     2.2, use 163 mailbox to send mail

        2.2.1. First, register an account in 163 mailbox. If so, omit this step

        2.2.2, write java code to send email, remember three steps

           2.2.2.1, get a connection (connect to the server of the mailbox and log in)

                   

        code

copy code
1 //0.1 Determine the connection position
 2         Properties props = new Properties();
 3 //Get the address of the 163 mailbox smtp server,
 4         props.setProperty("mail.host", "smtp.163.com");
 5 //Whether to perform permission verification.
 6         props.setProperty("mail.smtp.auth", "true");
 7         
 8         
 9 //0.2 Determine permissions (account and password)
10         Authenticator authenticator = new Authenticator() {
11             @Override
12             public PasswordAuthentication getPasswordAuthentication() {
13 //Fill in the login account and authorization password of your own 163 mailbox. The acquisition of the authorization password will be explained later.
14 return new PasswordAuthentication("163 Email Account","Authorization Code");
15             }
16         };
17
18 //1 get connected
19         /**
20 * props: object containing configuration information, Properties type
21 * Configure the email server address, configure whether to perform permission verification (account password verification), etc.
22          *
23 * authenticator: determine permissions (account and password)        
24          *
25 * So build these two objects on it.
26          */
27         
28         Session session = Session.getDefaultInstance(props, authenticator);
copy code

 

          2.2.2.2, create message (1, sender, 2, recipient, 3, email title, 4, email content)  

                      

    code

copy code
1 //2 create message
 2         Message message = new MimeMessage(session);
 3 // 2.1 Sender [email protected]
 4         message.setFrom(new InternetAddress("[email protected]"));
 5         /**
 6 * 2.2 recipients
 7 * The first parameter:
 8 * RecipientType.TO represents the recipient
 9 * RecipientType.CC CC
10 * RecipientType.BCC Bcc
11 * For example, A wants to send an email to B, but A thinks it is necessary to let C also see its content. When sending an email to B,
12 * Copy the content of the email to C, then C can also see its content, but B can also know that A has copied the email to C
13 * And if it is blindly sent (blind) to C, then B does not know that A has sent the email to C.
14 * second parameter
15 * The recipient's address, or an Address[], used to contain a list of CC or Bcc. Or for group posting. It can be the same mailbox server, or it can be different
16 * Here we send to our qq mailbox
17          */
18         message.setRecipient(RecipientType.TO, new InternetAddress("邮箱"));
19 // 2.3 Theme (Title)
20 message.setSubject("Subject of the message");
21 // 2.4 Text
22         String str = "李四: <br/>" +
23 "Hello, you are a registered user in this forum, click the following url to activate<br/>" +
24                         "http://ww......<br/>" +
25 "If you can't click, please copy and activate directly<br/>" +
26 "If it's not me, please delete the message";
27 //Set the encoding to prevent Chinese garbled characters from being sent.
28         message.setContent(str, "text/html;charset=UTF-8");
copy code

          2.2.2.3. Send email

              

    code

1 //3 send message
2         Transport.send(message);

 

          full code

copy code
1 package javamail;
 2
 3 import java.util.Properties;
 4
 5 import javax.mail.Authenticator;
 6 import javax.mail.Message;
 7 import javax.mail.MessagingException;
 8 import javax.mail.PasswordAuthentication;
 9 import javax.mail.Session;
10 import javax.mail.Transport;
11 import javax.mail.Message.RecipientType;
12 import javax.mail.internet.AddressException;
13 import javax.mail.internet.InternetAddress;
14 import javax.mail.internet.MimeMessage;
15
16 public class Mail163Test {
17     public static void main(String[] args) throws Exception{
18 //0.1 Determine the connection position
19         Properties props = new Properties();
20 //Get the address of the 163 mailbox smtp server,
21         props.setProperty("mail.host", "smtp.163.com");
22 //Whether to perform permission verification.
23         props.setProperty("mail.smtp.auth", "true");
24         
25         
26 //0.2 Determine permissions (account and password)
27         Authenticator authenticator = new Authenticator() {
28             @Override
29             public PasswordAuthentication getPasswordAuthentication() {
30 //Fill in the login account and authorization password of your own 163 mailbox. The acquisition of the authorization password will be explained later.
31 return new PasswordAuthentication("163 mailbox account", "authorization code");
32             }
33         };
34
35 //1 get connected
36         /**
37 * props: object containing configuration information, Properties type
38 * Configure the email server address, configure whether to perform permission verification (account password verification), etc.
39          *
40 * authenticator: determine permissions (account and password)        
41          *
42 * So build these two objects on it.
43          */
44         
45         Session session = Session.getDefaultInstance(props, authenticator);
46
47         
48 //2 Create message
49         Message message = new MimeMessage(session);
50 // 2.1 Sender [email protected] Our own email address is the name
51         message.setFrom(new InternetAddress("[email protected]"));
52         /**
53 * 2.2 recipients
54 * The first parameter:
55 * RecipientType.TO represents the recipient
56 * RecipientType.CC CC
57 * RecipientType.BCC Blind
58 * For example, A wants to send an email to B, but A thinks it is necessary to let C also see its content, just when sending an email to B,
59 * CC the content of the email to C, then C can also see its content, but B can also know that A has CCed the email to C
60 * If it is a blind send (blind send) to C, then B does not know that A sent the email to C.
61 * second parameter
62 * The recipient's address, or an Address[], used to contain a list of CC or Bcc. Or for group posting. It can be the same mailbox server, or it can be different
63 * Here we send to our qq mailbox
64          */
65         message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
66 // 2.3 Themes (titles)
67 message.setSubject("Subject of the message");
68 // 2.4 Text
69         String str = "李四: <br/>" +
70 "Hello, you are a registered user in this forum, click the following url to activate<br/>" +
71                         "http://ww......<br/>" +
72 "If you can't click, please copy and activate directly<br/>" +
73 "If it's not me, please delete the message";
74 //Set the encoding to prevent Chinese garbled characters from being sent.
75         message.setContent(str, "text/html;charset=UTF-8");
76         
77         
78 //3 send message
79         Transport.send(message);
80     }
81 }
copy code

 

       2.2.3. Explanation of authorization code

         What is an authorization code? This is very simple. If you do not log in at 163's email address, but log in your email account and password in some third-party clients, you must authorize to obtain an authorization code, and use the authorization code to log in to third-party clients. login on the terminal. The authorization code is equivalent to our password, and the account number is unchanged, that is, we say that we want to log in to the mailbox in the java code, then we must use the authorization code to log in. What if I get an authorization code?

         Log in to our 163 mailbox in the webpage

         

          After logging in, the home page must be displayed. There is a setting on the home page. Click Settings, and a series of setting options will be displayed on the left. Click the client authorization password, and it will be displayed as shown in the figure. Let it set the client authorization. If it is not turned on, it is turned off by default, and then click Turn on according to the steps, and set it step by step, you can get the authorization code.

          If the authorization code is not used, then the java program will report an error. The error message is that the verification failed, indicating that the account password is incorrect. At this time, the password is incorrect, because the password here should write the authorization code.

          

          

 

      2.2.4. The email is successfully sent.

          

 

 

 

    2.3. Use QQ mailbox to send emails

        2.3.1. First, register an account in QQ mailbox. If so, omit this step

        2.3.2, carry out three steps, create a connection, create a message, and send a message

            The steps are the same, and the authorization code is used to log in when logging in (the authorization code is similar to 163, first log in, then find the settings, there are steps to set the authorization code), but you will find that an error will be reported after writing the code, The error message is as follows

            Exception in thread "main" javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28

            AuthenticationFailedException appears this authorization verification failed exception, see the exception information, saying that a secure connection is required like ssl, more information visit this website: http://service.mail.qq.com/cgi-bin/help? id=28

            After visiting, I found that there is only one problem related to SSL

            

          Click to enter, you will find a flow chart about the third-party client setting SSL encryption, but we can know that the reason for our error is that the QQ mailbox sends or receives emails for SSL encryption. So I googled it, and I just need to add these four lines of code to get it done

          

      code

1 //SSL encryption of QQ mailbox.
2         MailSSLSocketFactory sf = new MailSSLSocketFactory();
3         sf.setTrustAllHosts(true);
4         props.put("mail.smtp.ssl.enable", "true");
5         props.put("mail.smtp.ssl.socketFactory", sf);

          In fact, the SSL encryption algorithm has been encapsulated in mail.jar, and you only need to take it out and use it.

      full code

copy code
1 package javamail;
 2
 3 import java.security.GeneralSecurityException;
 4 import java.util.Properties;
 5
 6 import javax.mail.Authenticator;
 7 import javax.mail.Message;
 8 import javax.mail.MessagingException;
 9 import javax.mail.PasswordAuthentication;
10 import javax.mail.Session;
11 import javax.mail.Transport;
12 import javax.mail.Message.RecipientType;
13 import javax.mail.internet.AddressException;
14 import javax.mail.internet.InternetAddress;
15 import javax.mail.internet.MimeMessage;
16
17 import com.sun.mail.util.MailSSLSocketFactory;
18
19 public class QQMailTest {
20     
21     public static void main(String[] args) throws AddressException, MessagingException, GeneralSecurityException {
22         
23 //0.5, props and authenticator parameters
24         Properties props = new Properties();
25         props.setProperty("mail.host", "smtp.qq.com");
26         props.setProperty("mail.smtp.auth", "true");
27         
28 //SSL encryption of QQ mailbox.
29         MailSSLSocketFactory sf = new MailSSLSocketFactory();
30         sf.setTrustAllHosts(true);
31         props.put("mail.smtp.ssl.enable", "true");
32         props.put("mail.smtp.ssl.socketFactory", sf);
33         
34 //authenticator parameter, log in your own email account password,
35         Authenticator authenticator = new Authenticator() {
36             @Override
37             public PasswordAuthentication getPasswordAuthentication() {
38                 /**
39 * Note that the rule of QQ mailbox is that if it is not opened and logged in by Tencent's webpage or client, it can be used anywhere else.
40 *Log in to the mailbox, the password must use the authorization code, the authorization code will be explained below, vlyvawibbsribgee
41 *xxxxxxx: your own QQ mailbox login account, that is, QQ number
42 *yyyyyyy: password, use the authorization code to log in instead of the original QQ password
43                  */
44 return new PasswordAuthentication("qq email account", "authorization code");
45             }
46         };        
47 //1, connect
48         /**
49          * props
50 * Connection configuration information, the address of the mail server, whether to verify the authority
51          * authenticator
52 * Authority verification, that is, account password verification
53 * So you need to configure these two parameters first
54          */
55         Session session = Session.getDefaultInstance(props, authenticator);                
56         
57 //2. The sent content object Message
58         Message message = new MimeMessage(session);
59 //2.1. Who is the sender
60         message.setFrom(new InternetAddress("[email protected]"));
61 // 2.2 , to: recipient; cc: CC; bcc : CC.
62         /**
63 * Who is the recipient?
64 * The first parameter:
65 * RecipientType.TO represents the recipient
66 * RecipientType.CC CC
67 * RecipientType.BCC Blind
68 * For example, A wants to send an e-mail to B, but A feels it necessary to let C also see its content, just when sending an e-mail to B,
69 * Copy the content of the email to C, then C can also see the content, but B can also know that A has copied the email to C
70 * And if it is a blind send (blind send) to C, then B does not know that A sent the email to C.
71 * Second parameter
72 * The recipient's address, or an Address[], used to contain a list of CC or Bcc. Or for group posting.
73          */
74 message.setRecipient(RecipientType.TO, new InternetAddress("Recipient's email address [email protected]"));
75 // 2.3 Theme (Title)
76         message.setSubject("hello");
77 // 2.4 Text
78 String str = "Bitter water moistens the throat: <br/>" +
79                         "hah<br/>";
80         message.setContent(str, "text/html;charset=UTF-8");
81 //3. Send
82         Transport.send(message);
83     }
84
85 }
copy code

 

    2.4. Summary

        The above uses QQ mailbox and 163 mailbox to send emails. Other mailbox servers should be similar, even if there are some subtle differences, just like the above QQ mailbox needs to use SSL encryption, but 163 does not need the same, you can Baidu yourself if you encounter errors Fix it. Then it must be noted that the premise of sending emails above is that you must be connected to the Internet. If you cannot connect to the Internet, you will not be able to send emails successfully, and an exception will be reported. Looking at this picture, you should understand why you need to connect to the Internet, because no When we are connected to the Internet, we can't even resolve the server address, let alone send emails.

           

 

        I'm afraid that some people can't connect to the Internet, so they can't judge whether the code they wrote is correct, and they can't experience the feeling of being able to send emails by themselves. Therefore, the following will introduce the installation of the mailbox server and client on this machine, so that you can send and receive emails without connecting to the Internet.

 

Third, install the mailbox server and client

    3.1. Types of Mailbox Servers and Clients

       Mailbox server: eyoumailserverstup.exe The download address can be found on Baidu, and the resource is also available on the CSDN forum

       Client: Foxmail_7.0.exe Same as above

              

    3.2, install the mailbox server

             After installation, a

                      

            This one doesn't matter, it doesn't affect the use, the appearance after installation

                    

            1. Delete Admin, and click Settings to set our custom domain name

                    

            2. Click on the new account to create two accounts, one wuhao and one zhangsan

                    

                    

                    

 

            3. What does the above operation mean? It is equivalent to creating a mailbox server by myself and registering two users on the server, for example, two people register two accounts in the 163 mailbox.

            4. Test, wuhao sends email to zhangsan

                    The code is based on the set of 163, without using ssl encryption or authorization code, directly use our login password

                    Email server address: 127.0.0.1 is the local address

                    Account password: wuhao 123

                    Sender's address: [email protected] wh.cn is the domain name we set in the server

                    Recipient's address: [email protected]  

                    The key parameters have been said above, what is the result? In the server, zhangsan did receive an email, and you can see from the comments below that it was indeed an email sent by wuhao to zhangsan.

                  

            5. Because this is the server, you cannot see the content of the email. Just like the schematic diagram we mentioned at the beginning, if you want to see the content of the email, you need to install the client and view it through the pop3 protocol.

 

     3.3. Install a third-party email client   

          Foxmail7.0

         3.3.1. After installation, set the email address, we need to check the email to get zhangsan, so fill in [email protected], because this server is opened by ourselves, so there is no prompt.  

                      

        3.3.2. Set the account password, and the mailbox type. Select POP3 for the mailbox type, which is used to receive the mail protocol.

               

        3.3.3. Both the receiving and sending mail servers should write the local address 127.0.0.1, because our local machine is a mailbox server, and if it is another mailbox server, it will be different, such as the sohu mailbox server, For example, QQ mailbox server and 163 mailbox server should use pop.163.com and smtp.163.com to get the server address. And noticed here, there is an option to use ssl to connect to the server, remember the problems we encountered when using QQ mailbox, yes, if you are bound to your QQ mailbox, then you need to tick the secondary option here select.

              

        3.3.4. After the setting is completed, it will show that zhangsan has a new email

                  

            

 

 4. Summary

      Sending emails with javamail is all explained here. Have you learned it? However, this technology is not used much now, and it is more often used to verify directly with a mobile phone number instead of an email. But it's good to learn, such as sending 100 emails to one person in a row. Haha, not very good, in short, I hope this article is helpful to everyone. I also hope that everyone can manually implement this function and play it by themselves.

            

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325115371&siteId=291194637