Details of struts2 integration javamail email example

  • 2020-06-23 01:42:29
  • OfStack

1. Code preview
I have been sending emails on struts2 these two days. Previous projects have been useful to spring, and it's easy to do this with spring's mail support class, but now you're running into a series 1 problem with struts2.

Please add your own mail. jar and activation. jar to classpath


package com.nerve.cloudoffice.common.util;

import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class EMailSender {
     /**
     *  Send an email to the user 
     */
    private static final long serialVersionUID = 1L;

    private MimeMessage mimeMsg; // MIME Email object 

    private Session session; //  Mail session object 

    private Properties props; //  System property 

    private boolean needAuth = false; // smtp Whether certification is required 

    private String username = ""; // smtp Authenticate user name and password 

    private String password = "";

    private Multipart mp; // Multipart object , Email content , The title , The attachment and other contents are added to it and then regenerated 

    private String log;

    public EMailSender() {

    }

    public EMailSender(String smtp) {
        setSmtpHost(smtp);
        createMimeMessage();
    }

    public void setSmtpHost(String hostName) {
        System.out.println(" Set system properties: mail.smtp.host = " + hostName);
        if (props == null)
            props = System.getProperties(); //  Get the system properties object 
        props.put("mail.smtp.host", hostName); //  Set up the SMTP The host 
        props.put("mail.smtp.localhost", "localHostAdress");
    }

    public boolean createMimeMessage() {
        try {
            System.out.println(" Ready to get the mail session object! ");
            session = Session.getDefaultInstance(props, null); //  Get the mail session object 
        } catch (Exception e) {
            log = " Error retrieving mail session object! " + e.toString();
            System.err.println(log);
            return false;
        }
        try {
            mimeMsg = new MimeMessage(session); //  create MIME Email object 
            mp = new MimeMultipart(); // mp 1 a multipart object 
            // Multipart is a container that holds multiple body parts.
            return true;
        } catch (Exception e) {
            log = " create MIME Mail object failed! " + e;
            System.err.println(log);
            return false;
        }
    }

    public void setNeedAuth(boolean need) {
        System.out.println(" Set up the smtp Identity Authentication: mail.smtp.auth = " + need);
        if (props == null)
            props = System.getProperties();
        if (need) {
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }
    }

    public void setNamePass(String name, String pass) {
        System.out.println(" The program gets the username and password ");
        username = name;
        password = pass;
    }

    public boolean setSubject(String mailSubject) {
        System.out.println(" Set your email subject! ");
        try {
            mimeMsg.setSubject(MimeUtility.encodeText(mailSubject,"utf-8","B"));
            return true;
        } catch (Exception e) {
            log = " Error setting email subject! "+e;
            System.err.println(log);
            return false;
        }
    }

    public boolean setBody(String mailBody) {
        try {
            System.out.println(" Set the mail frame ");
            BodyPart bp = new MimeBodyPart();
            //  Convert to Chinese format 
            bp.setContent(
                    "<meta http-equiv=Content-Type content=text/html; charset=utf-8>"
                            + mailBody, "text/html;charset=utf-8");
            mp.addBodyPart(bp);
            return true;
        } catch (Exception e) {
            log = " Error setting message body! " + e;
            System.err.println(log);
            return false;
        }
    }

    public boolean setFiles(List<String> files){
        try{
            for(String s:files){
                MimeBodyPart mbp=new MimeBodyPart();  
                FileDataSource fds=new FileDataSource(s); // Get the data source   
                mbp.setDataHandler(new DataHandler(fds)); // Get the attachment itself and go in BodyPart  
                mbp.setFileName(fds.getName());  // Get the same filename to in BodyPart  
                mp.addBodyPart(mbp);
            }
            return true;
        }catch(Exception e){
            log = " Error while adding attachments: "+e;
            e.printStackTrace();
            return false;
        }
    }

    public boolean addFile(String path, String name){
        try{
            MimeBodyPart mbp=new MimeBodyPart();  
            FileDataSource fds=new FileDataSource(path); // Get the data source   
            mbp.setDataHandler(new DataHandler(fds)); // Get the attachment itself and go in BodyPart  
            mbp.setFileName(MimeUtility.encodeText(name,"utf-8","B"));
            mp.addBodyPart(mbp);
            return true;
        }catch(Exception e){
            log = " Error while adding attachments: "+e;
            e.printStackTrace();
            return false;
        }
    }

    public boolean setFrom(String from) {
        System.out.println(" Set up senders! ");
        try {
            mimeMsg.setFrom(new InternetAddress(from)); //  Set the sender 
            return true;
        } catch (Exception e) {
            log = " Error setting sender :"+e;
            return false;
        }
    }

    public boolean setTo(String to) {
        System.out.println(" Set the addressee ");
        if (to == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
                    .parse(to));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean setCopyTo(String copyto) {
        if (copyto == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.CC,
                    (Address[]) InternetAddress.parse(copyto));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean sendout() {
        try {
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            System.out.println(" Sending mail ....");
            Session mailSession = Session.getInstance(props, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String) props.get("mail.smtp.host"), username,
                    password);
            transport.sendMessage(mimeMsg, mimeMsg
                    .getRecipients(Message.RecipientType.TO));
            // transport.send(mimeMsg);
            System.out.println(" Email sent successfully! ");
            transport.close();
            return true;
        } catch (Exception e) {
            log = " Email failed to send! " + e;
            System.err.println(log);
            return false;
        }
    }

    public String getLog(){
        return log;
    }
}

2. Problem summary

2.1 Error in local execution

I used javaee 5, jdk1.6. When running locally, Exception of ClassNotFound appears, but these classes are available in ES26en.jar again. This is because the classes in the jar package we added are in conflict with those in javaee5. The solution I recommend is to delete the activation package and mail package in javaee5.

Here's how:

Find javaee5 package referenced by eclipse, open it with rar software, find activation and mail package, delete and save. (Remember to refresh the reference package under 1 in ide)

2.2 javax.mail.MessagingException: 501 Syntax: HELO hostname

After the local test passed, I deployed to the linux server, but I encountered the exception of javax.mail.MessagingException: 501 Syntax: HELO hostname, which was found for the following reasons:

When Javamail extracts local hostname, it will change dig to hostname, and then change ip to send email.

Since hostname is corresponding to ip address, linux cannot resolve (if it is windows, there is no problem, windows USES THE netbios protocol to get the host's ip address) to the local hostname's ip, so javamail cannot call to send ip. When Postfix receives such mail, it will reject delivery, resulting in 501 errors.

The web site says that it can be solved by modifying the hosts file on the server, but I find that it can be solved directly in the code (just add 1 line of code, which is very convenient), that is, in the setSmtpHost() method, add the following line:


props.put("mail.smtp.localhost", "localHostAdress");

2.3 The Chinese name in the attachment is confused
If there is a Chinese name in the attachment, direct setName () will be confused, which can be solved by the following methods:


mbp.setFileName(MimeUtility.encodeText(name,"utf-8","B"));


Related articles: