JavaMail sends HTML mail

Posted by amax on Thu, 06 Jun 2019 20:59:58 +0200

objective

In some customer response systems, in the face of customer needs, we may need to notify customers by mail or feedback information to customers.

For example, the bank billing system needs to process the customer's checking request and send billing email. At this time, the billing data can be written into HTML documents and sent to the customer's mailbox by mail for feedback. The customer response of mobile operators also includes query balance, query package and other functions, which can be subscribed by mail. The server only needs to set the template and nest the data, so it can send different feedback information to each customer.

So today's example is to send an HTML message in a Java program that sets the notification object and content.

Tools used

1. First of all, we need to operate HTML documents. In java programs, as long as we use Dom4j to operate HTML and XML, we can convert documents into document objects and read and write them in the program.

2. To send mail, we need to use javamail tools. We need to study the configuration and use of javamail to send mail. I wrote a javamail tool class that uses constructor configuration parameters, and I used it directly.~

Code

template file

pageTemplet.html

<html>
    <head>
        <title>Notification mail</title>
        <meta charset="utf-8"/>
        <style type="text/css">
            body{
                font-size: 10pt;
            }
            .header,.content,.footer{
                width: 600px;
                height: 180px;
            }
            .footer{
                text-align: right;
            }
            #name{
                color: grey;
            }
            #message{
                color: grey;
            }
        </style>

    </head>
    <body>
        <div class="header">
            <img src="http://www.zhku.edu.cn/images/logo.jpg" alt="zhkulogo"/>
        </div>
        <div class="content">
            //Hello,<span id="name"></span>Classmate:<br/><br/>
            <div id="message">
                <span>    </span><span id="message"></span>
            </div>
            <div class="footer">
                //Campus Notice(<span id="time"></span>)
            </div>
        </div>

    </body>
</html>

Mail Tool Class

MailSender .java

package util;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender {
    private final Properties prop = new Properties();
    private final Session session;
    private final Message msg;
    private final Transport transport;

    //Builder
    public static class Builder{
        private final String mailContent;
        private final String toAddress;

        private String debug = "true";
        private String auth = "true";
        private String host = "smtp.163.com";
        private String protocol = "smtp";

        private String subject = "Notification mail";
        //sender address
        private String fromAddress= "xxxxx@163.com";
        //Sending account password
        private String fromCount = "xxxxx";
        private String fromPassword = "xxxxx";
        public Builder Debug(String debug) {
            this.debug = debug;
            return this;
        }
        public Builder Subject(String subject) {
            this.subject = subject;
            return this;
        }
        public Builder Auth(String auth) {
            this.auth = auth;
            return this;
        }
        public Builder Host(String host) {
            this.host = host;
            return this;
        }
        public Builder FromCount(String fromCount) {
            this.fromCount = fromCount;
            return this;
        }
        public Builder FromAddress(String fromAddress) {
            this.fromAddress = fromAddress;
            return this;
        }
        public Builder FromPassword(String fromPassword) {
            this.fromPassword = fromPassword;
            return this;
        }
        public Builder(String mailContent, String toAddress) {
            this.mailContent = mailContent;
            this.toAddress = toAddress;
        }
        public Builder Protocol(String protocol) {
            this.protocol = protocol;
            return this;
        }
        public MailSender send() throws Exception{
            return new MailSender(this);
        }

    }
    private MailSender(Builder builder) throws Exception{
        prop.setProperty("mail.debug", builder.debug);
        prop.setProperty("mail.smtp.auth", builder.auth);
        prop.setProperty("mail.host", builder.host);
        prop.setProperty("mail.transport.protocol",builder.protocol);

        session = Session.getInstance(prop);
        msg = new MimeMessage(session);
        transport = session.getTransport();
        msg.setSubject(builder.subject);
        msg.setFrom(new InternetAddress(builder.fromAddress,"Notification mail"));
        transport.connect(builder.fromCount,builder.fromPassword);
        //Here contentType is set to text/html, and the encoding format is set as appropriate.
        msg.setContent(builder.mailContent, "text/html;charset=utf-8");
        transport.sendMessage(msg, new Address[] {new InternetAddress(builder.toAddress)});
    }

}

Sample main program

SendHTMLMail.java

package practice;

import java.io.FileReader;
import java.io.FileWriter;
import java.util.Calendar;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import util.MailSender;

/**
 * Class Description: An example of how to send html messages based on html templates
 * @author xiezd
 *
 */
public class SendHTMLMail {
    @Test
    public void send(){
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            //Getting Template html Documents
            document = reader.read(SendHTMLMail.class.getResource("../file/pageTemplet.html").getPath());
            Element root = document.getRootElement();
            //Get the nodes whose id is name, message and time respectively.
            Element name = getNodes(root,"id","name");
            Element message = getNodes(root,"id","message");
            Element time = getNodes(root, "id", "time");

            //Set the recipient's name, notification information, current time
            Calendar calendar = Calendar.getInstance();
            time.setText(calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DATE));
            name.setText("Xiao Ming");
            //Write casually
            message.setText("Because you and I are destined to form a circle. To further optimize the educational environment,"
                    + "Strengthen the interaction between home and school to promote the growth and progress of students. In the spirit of home-school co-education, our school decided to hold a meeting of high-school presidents."
                    + "I hope you can spare some time in your busy schedule and make time to visit us to have in-depth face-to-face exchanges with the head teachers about the children's performance at home and at school."
                    + "According to the different characteristics of each child, discuss with the teacher the strategy of educating the child, and promote the progress of your child to the greatest extent.");

            //Save to temporary file
            FileWriter fwriter = new FileWriter("d:/temp.html");
            XMLWriter writer = new XMLWriter(fwriter);
            writer.write(document);
            writer.flush();
            //Read the temporary file and write the html data into the string str, which is sent through the mailbox tool
            FileReader in = new FileReader("d:/temp.html");
            char[] buff = new char[1024*10];
            in.read(buff);
            String str = new String(buff);
            System.out.println(str.toString());

            new MailSender.Builder(str.toString(),"xxx@qq.com").send();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     /**
     * Method Description: Recursively traverse the child node, according to the attribute name and value, find the corresponding attribute name and value of the descendant node.
     * @param node Nodes to be traversed by child nodes
     * @param attrName Property name
     * @param attrValue Attribute value
     * @return Return the corresponding node or null
     */
    public Element getNodes(Element node, String attrName, String attrValue) {  

            final List<Attribute> listAttr = node.attributes();// All attributes of the current node  
            for (final Attribute attr : listAttr) {// Traversing through all attributes of the current node  
                final String name = attr.getName();// Property name  
                final String value = attr.getValue();// Values of attributes  
                System.out.println("Property name:" + name + "---->Attribute values:" + value);
                if(attrName.equals(name) && attrValue.equals(value)){
                    return node;
                }
            }  
            // Recursively traverses all the child nodes of the current node  
            final List<Element> listElement = node.elements();// list of all first-level subnodes  
            for (Element e : listElement) {// Traversing all first-level subnodes  
                Element temp = getNodes(e,attrName,attrValue);
                // recursion
                if(temp != null){
                    return temp;
                };  
            }  

            return null;
        }  

}

Effect

Topics: Java Session Attribute Mobile