Java Fundamentals 16

31. Mail sending

Sending E-mail using a Java application is very simple, but first you have to install JavaMail API and Java Activation Framework (JAF) on your client machine.

  • You can download the latest version of JavaMail from the Java website, open the Downloads link on the right side of the page, and click on it to download.
  • The latest version of JAF (version 1.1.1) can be downloaded from the Java website.

You can also use the download link provided below:

Download and decompress these files. In the newly created top-level directory, you will find some jar files for these two applications. Need to add the mail.jar and activation.jar files to the CLASSPATH of the local My Computer->Environment Variables.

If you are using a third-party mail server such as QQ's SMTP server, you can view the complete example of user authentication at the bottom of the article.

1. Send a simple E-mail

Send a simple E-mail. The premise is that the local host is connected to the network.

// 文件名 SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail{
   public static void main(String [] args){   
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
 
         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");
 
         // 设置消息体
         message.setText("This is actual message");
 
         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Run this program to send a simple E-mail:

$ java SendEmail
Sent message successfully....

To send an e-mail to multiple recipients, you can use the following methods to specify multiple recipient IDs:

void addRecipients(Message.RecipientType type,Address[] addresses) throws MessagingException

Explanation of parameters:

  • type: To be set to TO, CC or BCC, where CC stands for CC and BCC stands for secret CC. Example: Message.RecipientType.TO
  • addresses: This is an array of email IDs. When specifying the email ID, you will need to use the InternetAddress() method.

2. Send an HTML E-mail

If you want to send HTML E-mail. Assume that the local host is already connected to the network.
It is similar to the above, except that you need to use the setContent() method to set the content to specify the HTML content to be sent through the second parameter as "text/html".

// 文件名 SendHTMLEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendHTMLEmail{
   public static void main(String [] args){
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象。
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象。
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
 
         // Set Subject: 头字段
         message.setSubject("This is the Subject Line!");
 
         // 发送 HTML 消息, 可以插入html标签
         message.setContent("<h1>This is actual message</h1>","text/html" );
 
         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Run this program to send HTML e-mail:

$ java SendHTMLEmail
Sent message successfully....

3. Send E-mail with attachments

An example of sending an E-mail with attachments. The premise is that your local host is already connected to the network.

// 文件名 SendFileEmail.java
 
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendFileEmail{
   public static void main(String [] args){
      // 收件人电子邮箱
      String to = "[email protected]";
 
      // 发件人电子邮箱
      String from = "[email protected]";
 
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
 
      // 获取系统属性
      Properties properties = System.getProperties();
 
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
 
      // 获取默认的 Session 对象。
      Session session = Session.getDefaultInstance(properties);
 
      try{
         // 创建默认的 MimeMessage 对象。
         MimeMessage message = new MimeMessage(session);
 
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
 
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
 
         // Set Subject: 头字段
         message.setSubject("This is the Subject Line!");
 
         // 创建消息部分
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 消息
         messageBodyPart.setText("This is message body");
        
         // 创建多重消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 附件部分
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整消息
         message.setContent(multipart );
 
         //   发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

The program can send an email with attachments:

$ java SendFileEmail
Sent message successfully....

32, MySQL database connection

This section introduces how to use JDBC to connect to the MySQL database for the friends.
Note: In fact, there are many versions of the database. The database corresponds to JDBC in Java and has corresponding drivers. The configuration methods are similar. You can query by yourself! The only databases commonly used in domestic work are MySQL and Oracle, and SQL Server uses less! But SQL statements still need to be written!
Java requires a driver package to connect to MySQL. The download address of the latest version is: http://dev.mysql.com/downloads/connector/j/ , the jar library file is obtained after decompression, and then the library file is imported into the corresponding project.
You can also download the jar package provided by this blogger: mysql-connector-java-5.1.39-bin.jar

Eclipse, import the jar package:

Insert picture description here

The database connection of MySQL 8.0 and above is different:

1. The driver package version of MySQL 8.0 or above is mysql-connector-java-8.0.16.jar.

2. Replace com.mysql.jdbc.Driver with com.mysql.cj.jdbc.Driver.

  • MySQL version 8.0 and above does not need to establish an SSL connection, it needs to be displayed closed.
  • allowPublicKeyRetrieval=true allows the client to obtain the public key from the server.
  • Finally, you need to set the CST.

The way to load the driver and connect to the database is as follows:

Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_demo?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","password");

One, create test data

Create a database in MySQL [database name is jiuling, you can customize the name], and create a website data table, the table structure is as follows:

CREATE TABLE `websites` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) NOT NULL DEFAULT '' COMMENT '站点名称',
  `url` varchar(255) NOT NULL DEFAULT '',
  `alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名',
  `country` char(10) NOT NULL DEFAULT '' COMMENT '国家',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

Insert some data:

INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), 
('2', '淘宝', 'https://www.taobao.com/', '13', 'CN'), 
('3', '菜鸟教程', 'http://www.runoob.com', '5892', ''), 
('4', '微博', 'http://weibo.com/', '20', 'CN'), 
('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA');

The data table is shown as follows:

Insert picture description here

Two, connect to the database

Use JDBC to connect to the MySQL database. Note that some data such as username and password need to be configured according to the actual development environment:

package com.runoob.test;
import java.sql.*;
public class MySQLDemo {
    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
 
    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
 
 
    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "123456";
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);
        
            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
        
            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
        
            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
    
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 站点名称: " + name);
                System.out.print(", 站点 URL: " + url);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

Output result:

Insert picture description here

summary:

E-mail sending: E-mail sending is not only through a small tool class can be explained! As the so-called knowledge points are dead, you have to see how to use them in detail! Email sending and email verification will also be used in large projects! Combined with more complex message queues and middleware to achieve JMS mailbox verification and so on! There is even SMS message verification! This is what needs to be further learned in the future!
MySQL database connection: The database connection is just a basis for entering the database. Know how to configure the database and how to use JDBC. Databases are actually difficult, this is just the beginning! Need to explore slowly in the future study! In fact, the deeper the bottom layer of the database will involve data structure and locks, etc.! Now just have a preliminary understanding of how to use it! Learn more in the future!

to sum up:

Today I finally passed the first subject, and the effort paid off! It was supposed to be over last Friday. Later, I heard that a construction team accidentally cut the optical cable during construction, which caused all the traffic management stations to be disconnected, and they were all moved to today. Early in the morning, I went to the vehicle management station to line up. Since the people of the two days have merged, there are so many people! From the morning until 12:00 noon, I entered the waiting hall! It took another hour for the team to enter the examination room, with a total of more than 100 questions, and it only took 10 minutes to complete! And he passed the test steadily, as the saying goes: "Every test must be passed!".
      Today is the second day of the college entrance examination. After the college entrance examination, the friends can finally relax! Hanchuang study hard, how many times have I searched for the best solution in the problem sea tactics! Now, the sweat once swayed will also be your biggest gain! After the college entrance examination is over, you can relieve the pressure that has not been released! You can also do what you once wanted to do! At the same time, you can also plan your career in university!
      At the same time, graduating from high school will also mean a transition from an ignorant youth to an adult! Once in high school, you might rely on your parents, friends, teachers, etc.; when you enter the university and face a new environment, you will meet some new friends, roommates, classmates and teachers; can you adapt to this new environment? This is facing a huge challenge! Only after experiencing these challenges can you truly know yourself and understand your shortcomings and shortcomings!
      Early warning friends who did not plan and plan before going to university! Before going to college, first want to understand why go to college? This is very important! Does the university want to continue the postgraduate entrance examination or just for employment? If it is the former, you have to study hard and face the postgraduate entrance examination; if you are employed, you have to study professional knowledge well and understand the employment trend in advance! If you don’t have a specific plan, take a while to figure it out! After thinking it through, list the plan according to your own situation, and then implement your plan step by step! College taboos: greed for pleasure, love for leisure and work, ceaselessly failing courses, not seeking improvement, obsessed with female sex, self-destroying future! Universities should try their best to develop a good habit of self-discipline, and learn to benefit from self-discipline for life!
      Wish: Everyone who participates in the college entrance examination will get an excellent result every time the exam is passed, and all of them will be able to have a gold list title!
      If this blog is helpful to friends, I hope you can like and follow! Thank you all my friends!
      Finally, I hope that we can all achieve different achievements in all walks of life, and live up to the expectations of relatives, friends, teachers, elders and the country! Be able to use what you have learned to contribute your own strength to the country! work hard together!
                                                                                                                       Night of June 8, 2021