[Javaweb] can you find npy without some technical work? ❤️ Look at this email ❤️ (1024 is a programmer's holiday)

Keywords: Java Operation & Maintenance server

Take qq mailbox as an example

To realize the mail function on the network, there must be a special mail server

The mail server is similar to the real post office. It is mainly responsible for receiving the mail delivered by the user and delivering the mail to the e-mail of the mail recipient.

1. Zhang San connects to the SMTP server through the SMTP protocol, and then sends an email to Netease's mail server;

2. Netease analysis found that it needs to go to qq's mail server and transfer the mail to qq's SMTP server through SMTP protocol

3.qq stores the received email in the space of Li Si's email account

4. Li Si connects to the pop3 server through the pop3 protocol to receive mail

5. Take out the email from the space of Li Si's email account

6.Pop3 server sends the mail to Li Si

Note: it is possible that your recipient address, sender address and other information are correct, and the console also prints the correct information, but you can't receive the information in your inbox. It is likely that the inbox server rejects your email (for example, it thinks your email is an advertisement). At this time, it may be found in the dustbin or not. The solution is not to send duplicate email content multiple times, or change your inbox

1. Send email to QQ email

1.1 Guide Package

To send Email using Java, you need to prepare JavaMail API and Java Activation Framework to get two jar packages mail.jar and activation.jar

This package must not be imported incorrectly, otherwise the SSL encryption error of QQ setting will appear later

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

1.2 configure in mailbox

We want to open the QQ mailbox settings

Turn the first on. Security verification is generally required

Save the verification code yourself

1.3 MailDemo01

package com.hxl;


import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

//Send a simple email
public class MailDemo01 {
    public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");//Set up qq mail server
        prop.setProperty("mail.transport.protocol", "smtp");//Mail sending protocol
        prop.setProperty("mail.smtp.auth", "true");//User name and password need to be verified

        //For qq mailbox, you also need to set SSL encryption
        //SSL encryption is required for QQ mailbox, but not for other mailboxes
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);


        //Five steps to send mail using javaMail
        //1. Create a session object that defines the environment information required by the entire application
        //QQ! Not for other mailboxes
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //Sender mail user name and authorization code
                return new PasswordAuthentication("XXXX@qq.com","Authorization code");
            }
        });

        //Turn on the debug mode of the session, so that you can view the running status of the Email sent by the program
        session.setDebug(true);
        //2. Get the transport object through the session
        Transport ts=session.getTransport();

        //3. Connect to the mail server using the user name and authorization code of the mailbox
        ts.connect("smtp.qq.com","XXXX@qq.com","Authorization code");

        //4. Create mail: write file
        //Note that the session needs to be passed
        MimeMessage message=new MimeMessage(session);
        //Indicates the sender of the message
        message.setFrom(new InternetAddress("XXXX@qq.com"));
        //Indicates the recipient of the message
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("XXXX@qq.com"));
        //Mail title
        message.setSubject("Sent title");
        //Text content of the message
        //You can also add styles to the content, such as the price < H1 style ='color: Red '></h1>
        message.setContent("content","text/html;charset=UTF-8");

        //5. Send mail
        ts.sendMessage(message,message.getAllRecipients());

        //6. Close the connection
        ts.close();
    }
}

1.4 run view results

If there is no network, errors will occur if the verification code is incorrect.


2. Send complex content

MIME (Multipurpose Internet mail extension type)

MimeBodyPart class: javax.mail.internet.MimeBodyPart class represents a MIME message, which is inherited from the Part interface like MimeMessage class

MimeMultipart class: javax.mail.internet.MimeMultipart is the implementation subclass of the abstract class Multipart. It is used to combine multiple MIME messages. A MimeMultipart object can contain multiple mimebudypart objects representing MIME messages.

2.1 picture address

Right click to find the picture address we need

2.2 sending Mail with pictures

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

//Sending with pictures
public class MailDemo02 {
    public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");//Set up qq mail server
        prop.setProperty("mail.transport.protocol", "smtp");//Mail sending protocol
        prop.setProperty("mail.smtp.auth", "true");//User name and password need to be verified

        //For qq mailbox, you also need to set SSL encryption
        //SSL encryption is required for QQ mailbox, but not for other mailboxes
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);


        //Five steps to send mail using javaMail
        //1. Create a session object that defines the environment information required by the entire application
        //QQ! Not for other mailboxes
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //Sender mail user name and authorization code
                return new PasswordAuthentication("xxxxx@qq.com","Authorization code");
            }
        });

        //Turn on the debug mode of the session, so that you can view the running status of the Email sent by the program
        session.setDebug(true);
        //2. Get the transport object through the session
        Transport ts=session.getTransport();

        //3. Connect to the mail server using the user name and authorization code of the mailbox
        ts.connect("smtp.qq.com","xxxxx@qq.com","Authorization code");

        //4. Create mail: write file
        //Note that the session needs to be passed
        MimeMessage message=new MimeMessage(session);
        //Indicates the sender of the message
        message.setFrom(new InternetAddress("xxxxx@qq.com"));
        //Indicates the recipient of the message
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("xxxxx@qq.com"));
        //Mail title
        message.setSubject("With pictures");
        //Text content of the message
        //=================================Prepare picture data=======================================
        MimeBodyPart image=new MimeBodyPart();
        //Images need to be processed by DataHandler
        //Change to your own picture address
        DataHandler dh=new DataHandler(new FileDataSource("D:\\aAAAA\\util\\FunctionExtensio\\mail-java\\src\\main\\resources\\1.jpg"));
        //Put the processed image data in the MimeBodyPart
        image.setDataHandler(dh);
        //Set an ID name for this picture, which can be used later
        image.setContentID("bz.jpg");

        //Prepare data for text
        MimeBodyPart text=new MimeBodyPart();
        //The cid here is the setContentID above
        text.setContent("This is a text with pictures<img src='cid:bz.jpg'>","text/html;charset=UTF-8");

        //Describe data relationships
        MimeMultipart mm=new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");

        //Set to the message and save the changes
        message.setContent(mm);//Send the last edited email to the message
        message.saveChanges();//Save changes

        //5. Send mail
        ts.sendMessage(message,message.getAllRecipients());

        //6. Close the connection
        ts.close();
    }
}

2.3 test results

3. Send mail with file

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class MailDemo03 {
    public static void main(String[] args) throws MessagingException, GeneralSecurityException {

        //Create a configuration file to save and read information
        Properties properties = new Properties();

        //Set up qq mail server
        properties.setProperty("mail.host","smtp.qq.com");
        //Set the protocol for sending
        properties.setProperty("mail.transport.protocol","smtp");
        //Set whether the user needs authentication
        properties.setProperty("mail.smtp.auth", "true");


        //=====Only QQ has a feature that requires a secure link
        // For QQ mailbox, you should also set SSL encryption and add the following code
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //====Preparations are complete

        //1. Create a session object;
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("xxxxxxx@qq.com", "Authorization code");
            }
        });

        //You can start the Dubug mode through the session to view all the processes
        session.setDebug(true);


        //2. Get the connection object and get the Transport through the session object. You need to catch or throw an exception;
        Transport tp = session.getTransport();

        //3. When connecting to the server, an exception needs to be thrown;
        tp.connect("smtp.qq.com","xxxxxxx@qq.com","Authorization code");

        //4. After connecting, we need to send an email;
        MimeMessage mimeMessage = imageMail(session);

        //5. Send mail
        tp.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //6. Close the connection
        tp.close();

    }


    public static MimeMessage imageMail(Session session) throws MessagingException {

        //Fixed information of message
        MimeMessage mimeMessage = new MimeMessage(session);

        //Mail sender
        mimeMessage.setFrom(new InternetAddress("xxxxx@qq.com"));
        //Mail recipients can send it to many people at the same time. We only send it to ourselves here;
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("xxxxxx@qq.com"));
        mimeMessage.setSubject("With file"); //Mail subject


        /*
        Write mail content
        1.picture
        2.enclosure
        3.text
         */

        //picture
        MimeBodyPart body1 = new MimeBodyPart();
        body1.setDataHandler(new DataHandler(new FileDataSource("D:\\aAAAA\\util\\FunctionExtensio\\mail-java\\src\\main\\resources\\1.jpg")));
        body1.setContentID("bz.jpg"); //Picture setting ID

        //text
        MimeBodyPart body2 = new MimeBodyPart();
        body2.setContent("Please note that I am not advertising<img src='cid:bz.jpg'>","text/html;charset=utf-8");

        //enclosure
        MimeBodyPart body3 = new MimeBodyPart();
        body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/log4j.properties")));
        body3.setFileName("log4j.properties"); //Attachment setting name

        MimeBodyPart body4 = new MimeBodyPart();
        body4.setDataHandler(new DataHandler(new FileDataSource("src/resources/1.txt")));
        body4.setFileName(""); //Attachment setting name

        //Assemble message body content
        MimeMultipart multipart1 = new MimeMultipart();
        multipart1.addBodyPart(body1);
        multipart1.addBodyPart(body2);
        multipart1.setSubType("related"); //1. Text and picture embedding succeeded!

        //new MimeBodyPart().setContent(multipart1); // Set the assembled text content as the main body
        MimeBodyPart contentText =  new MimeBodyPart();
        contentText.setContent(multipart1);

        //Splicing accessories
        MimeMultipart allFile =new MimeMultipart();
        allFile.addBodyPart(body3); //enclosure
        allFile.addBodyPart(body4); //enclosure
        allFile.addBodyPart(contentText);//text
        allFile.setSubType("mixed"); //The body and attachments are stored in the message, and all types are set to mixed;


        //Put in Message
        mimeMessage.setContent(allFile);
        mimeMessage.saveChanges();//Save changes


        return mimeMessage;

    }

}

4. Send mail via Java Web

Now many websites provide user registration function. Usually, after we register successfully, we will receive an Email from the registered website. The contents of the Email may include our registered user name and password, as well as a hyperlink to activate the account. Today, we will also implement such a function. After the user is registered successfully, the user's registration information will be sent to the user's registration mailbox in the form of Email. To realize the mail sending function, we have to use JavaMail.

When guiding the package, be sure to import the correct one,

4.1 project preparation

Create a new Java Web project, configure Tomcat, and add jar packages

<dependencies>
    <!--Servlet rely on-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <!--JSP rely on-->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>

4.2 front page

index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>register</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
  user name:<input type="text" name="username"><br/>
  password:<input type="password" name="password"><br/>
  Email:<input type="text" name="email"><br/>
  <input type="submit" value="register">
</form>

</body>
</html>
Info.jsp (prompt)
<<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Prompt information</title>
</head>
<body>
${message}
</body>
</html>

4.3 User entity class

package com.hxl.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private String password;
    private String email;

    public User() {
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public User(String username, String password, String email) {
        this.username = username;
        this.password = password;
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

4.4 Servlet

package com.hxl.servlet;

import com.hxl.pojo.User;
import com.hxl.utils.Sendmail;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//Scaffolding
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //Receive user requests and encapsulate them into objects
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            User user = new User(username,password,email);

            //After the user is registered successfully, send an email to the user
            //We use threads to send mail specifically to prevent time-consuming and excessive number of website registrations;
            Sendmail send = new Sendmail(user);
            //Start the thread. After the thread starts, it will execute the run method to send mail
            send.start();

            //Registered user
            request.setAttribute("message", "Registration is successful. We have sent an email with registration information. Please check it! If the network is unstable, you may receive it later!!");
            request.getRequestDispatcher("info.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", "Registration failed!!");
            request.getRequestDispatcher("info.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

4.5 registering servlet s

<servlet>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.hxl.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>

4.6 utils tools

package com.hxl.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import com.hxl.pojo.User;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

//Website 3 second principle: user experience
//Multithreading for user experience!! (asynchronous processing)
public class Sendmail extends Thread{
    //Mailbox used to send mail to users
    private String from = "xxxx@qq.com";
    //User name of mailbox
    private String username = "xxxx@qq.com";
    //Password for mailbox
    private String password = "Authorization code";
    //Address of the server sending the mail
    private String host = "smtp.qq.com";

    private User user;
    public Sendmail(User user){
        this.user = user;
    }

    //Override the implementation of the run method and send mail to the specified user in the run method
    @Override
    public void run() {
        try{
            Properties prop = new Properties();
            prop.setProperty("mail.host", host);
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.auth", "true");

            // For QQ mailbox, you should also set SSL encryption and add the following code
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);

            //1. Create a Session object that defines the environment information required for the entire application
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //Sender mail user name and authorization code
                    return new PasswordAuthentication("xxxx@qq.com", "Authorization code");
                }
            });

            //Turn on the debug mode of Session, so that you can view the running status of the Email sent by the program
            session.setDebug(true);

            //2. Get the transport object through session
            Transport ts = session.getTransport();

            //3. Use the user name and authorization code of the mailbox to connect to the mail server
            ts.connect(host, username, password);

            //4. Create message
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from)); //Sender
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); //addressee
            message.setSubject("User registration email"); //The title of the message

            String info = "Congratulations on your successful registration. Your user name:" + user.getUsername() + ",Your password:" + user.getPassword() + ",Please keep it properly. If you have any questions, please contact the website customer service!!";

            message.setContent(info, "text/html;charset=UTF-8");
            message.saveChanges();

            //Send mail
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

4.7 it is possible to report an error:

This is because the jar package is not imported. First, let's take a look at Artifacts in Project Structure and select our own module to view the jar package. It is also possible that these two packages are not available in Tomcat. We need to copy these two packages to the Tomcat folder

4.8 test results


5. Implemented in springboot

@Autowired
JavaMailSenderImpl mailSender;

@Test
Public void contextLoads(){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setSubjext("theme");
    message.setText("text");
    message.setFrom("Where's the mailbox from");
    message.setTo("Go to the mailbox there");
    mailSender.send(message);
}
@Test
Public void contextLoads2() throws Exception{
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true)
    helper.setSubjext("theme");
    helper.setText("<h1>text</h1>",true);
    //enclosure
    helper.addAttachment("1.jpg",new File(""));
    helper.setFrom("Where's the mailbox from");
    helper.setTo("Go to the mailbox there");
    mailSender.send(helper);
}

Configure in application.properties

spring.mail.username=xxxxx@qq.com
spring.mail.password=Authorization code
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true

Posted by ailgup on Sat, 23 Oct 2021 15:11:19 -0700