1. 程式人生 > >java方式郵件整體流程(最新最詳細版)

java方式郵件整體流程(最新最詳細版)

郵件作為較正式的溝通方式,在專案中會經常用到,無論是通知或者是審批功能,郵件都是義不容辭.

那麼專案中是發郵件的流程是什麼呢?過程如下

一,專案說明:java語言. Maven專案.SSM框架:Spring+SpringMvc+Mybatis

二,整體流程

1,建立郵件基本資訊類MailMessage

import java.util.List;
import java.util.Map;
/** 
 * @author  李光光(編碼小王子)
 * @date    2018年10月24日 上午10:18:17 
 * @version 1.0   
 */
public class MailMessage {
    
    private String server;// 郵件型別,eg,163郵箱還是qq郵箱

    private String username;// 發件箱的使用者名稱

    private String password;// 發件箱的郵箱密碼

    private String nickname;// 發件箱的暱稱

    private String sender;// 發件箱的郵箱賬號

    private String receiver;// 收件人的郵箱賬號

    private List<String> receiverList;// 收件人的郵箱賬號的列表

    private String subject;// 郵件主題

    private Map<String, String> map;// 郵件內容

    private String templateName;// 郵件模板

    //get和set方法
}

2,建立郵件基本資訊類MailSender

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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;

/** 
 * @author  李光光(編碼小王子)
 * @date    2018年10月24日 上午10:21:43 
 * @version 1.0   
 */
public class MailSender {
    
    private MimeMessage mimeMsg;// 郵件物件
    
    private Session session; // 郵件會話物件
    
    private Properties props; // 系統屬性
    
    private Multipart mp; // Multipart物件,郵件內容,標題,附件等內容均新增到其中後再生成
    
    private String username;// 發件人的使用者名稱
    
    private String password;// 發件人的密碼
    
    private String nickname;// 發件人的暱稱
    
    public MailSender(String smtpHost) {
        setSmtpHost(smtpHost);
        createMimeMessage();
    }
    
    public void setSmtpHost(String hostName) {
        if (props == null) {
            props = System.getProperties();
            props.put("mail.smtp.host", hostName);
        }
    }
    
    public void createMimeMessage() {
        // 獲得郵件會話物件
        session = Session.getDefaultInstance(props, null);
        // 建立MIME郵件物件
        mimeMsg = new MimeMessage(session);
        mp = new MimeMultipart();
    }
    
    // 設定是否身份認證
    public void setNeedAuth(boolean isAuth) {
        if (isAuth) {
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }
    }
    
    // 設定令牌口令
    public void setNamePass(String userName, String password, String nickname) {
        this.username = userName;
        this.password = password;
        this.nickname = nickname;
    }
    
    // 設定主題
    public void setSubject(String subject) throws UnsupportedEncodingException,MessagingException {
        mimeMsg.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));
    }
    
    
    // 設定內容
    public void setBody(String mailBody) throws MessagingException {
        BodyPart bp = new MimeBodyPart();
        bp.setContent("" + mailBody, "text/html;charset=utf-8");
        mp.addBodyPart(bp);
    }
    
    // 郵件接收人
    public void setReceivers(List<String> receivers) throws AddressException, MessagingException {
        InternetAddress[] address = new InternetAddress[receivers.size()];
        for (int i = 0; i < receivers.size(); i++) {
            address[i] = new InternetAddress(receivers.get(i));
        }
        mimeMsg.setRecipients(Message.RecipientType.TO, address);
    }
    
    
    // 發件人
    public void setSender(String sender) throws UnsupportedEncodingException,AddressException, MessagingException {
        nickname = MimeUtility.encodeText(nickname, "utf-8", "B");
        mimeMsg.setFrom(new InternetAddress(nickname + " <" + sender + ">"));
    }
    
    public void sendout() throws MessagingException {
        mimeMsg.setContent(mp);
        mimeMsg.saveChanges();
        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.close();
    }
}

3,建立郵件傳送的工具類MailUtils

import java.io.IOException;
import javax.mail.MessagingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.template.TemplateException;

/** 
 * @author  李光光(編碼小王子)
 * @date    2018年10月24日 上午10:11:50 
 * @version 1.0   
 */
public class MailUtils {
    private static Logger  logger  =LoggerFactory.getLogger(MailUtils.class);
    
    public static void sendMail(MailMessage mailMessage) throws IOException, TemplateException,MessagingException {
        String mailBody = "";
        MailSender mail = new MailSender(mailMessage.getServer());
        mail.setNeedAuth(true);
        mail.setNamePass(mailMessage.getUsername(), mailMessage.getPassword(), mailMessage.getNickname());
        // 獲取郵件傳送內容
        mailBody = TemplateFactory.getHtmlFromFtl(mailMessage.getTemplateName(), mailMessage.getMap());
        // 設定郵件傳送引數
        mail.setSubject(mailMessage.getSubject());
        mail.setBody(mailBody);
        mail.setReceivers(mailMessage.getReceiverList());
        mail.setSender(mailMessage.getSender());
        // 傳送郵件
        try {
            mail.sendout();
            logger.error("傳送人" + mailMessage.getSender() + "接收人" + mailMessage.getReceiverList() + "內容" + mailBody);
        } catch (Exception e) {
            logger.error("傳送郵件失敗原因" + e.getMessage());
            e.printStackTrace();
        }
        }
}

4,建立郵件模板,模板在專案中的位置如下:

模板具體內如如下:大家可以根據需要自行修改模板內如,模板是使用如下格式接收傳值的${引數名}

<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<title>訪客通知</title>
</head>
<body>
    <br/>
	<p>您好</p>
	<p>您為訪客${visitorName}等${visitorNum}人開通了${visitTime}日預約。</p>
    <p>以上為系統郵件,請勿回覆,謝謝.</p>
    <p>===================================================</p>
</body>
</html>

5,建立獲取模板內容的工具類 TemplateFactory

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/** 
 * @author  李光光(編碼小王子)
 * @date    2018年10月24日 上午10:33:19 
 * @version 1.0   
 */
public class TemplateFactory {
    
    private static  String  ENCODING= "UTF-8";
    
    private static  String  pathPrefix ="/template";//模板路徑
    
    private static  Configuration  conf  = new Configuration();//模板配置
    
    static{
        conf.setClassForTemplateLoading(TemplateFactory.class, pathPrefix);
        conf.setDefaultEncoding(ENCODING);
    }
    
    private static Map<String, Template> tempMap = new HashMap<String, Template>();// 郵件模板快取池
    
    /**
     *@param templateName 模板名稱
     *@param  param   引數資料模型
     */   
  public  static String  getHtmlFromFtl(String templateName,Map<String,String> param)throws TemplateException, IOException{
      Template templete = null;
      ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outBytes, ENCODING));
      // 獲取當前模板
      templete = getTemplateByName(templateName);
      templete.setEncoding(ENCODING);
      templete.process(param, out);
      String outStr = new String(outBytes.toByteArray(), ENCODING);
      return outStr.toString();
  }
  
  /**
   * @param templateName 模板名稱
   * */
   private static Template getTemplateByName(String templateName) throws IOException {
       if (tempMap.containsKey(templateName)) {
           return tempMap.get(templateName);// 快取中有該模板直接返回
       }
       // 快取中沒有該模板時,生成新模板並放入快取中
       Template temp = conf.getTemplate(templateName);
       tempMap.put(templateName, temp);
       return temp;
   }
}

6,建立傳送郵件的service介面SendMailService

import com.jd.am.visit.domain.bespeak.Bespeak;

/** 
 * @author  李光光(編碼小王子)
 * @date    2018年10月24日 上午11:22:29 
 * @version 1.0   
 */
public interface SendMailService {
    
    void  sendMail(Bespeak bespeak) throws Exception;
}

7,建立service層SendMailService介面的實現類SendMailServiceImpl,並在方法裡呼叫傳送郵件工具類裡的方法,傳送郵件

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** 
 * @author  李光光(編碼小王子)
 * @date    2018年10月24日 上午11:25:55 
 * @version 1.0   
 */
@Service
public class SendMailServiceImpl implements SendMailService {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserinfoService userinfoService;
    
    private String smtpHost = "smtp.163.com";
    
    private String username = "郵箱賬號";
    
    private String password = "郵箱密碼";
    
    private String nickname = "郵箱賬號";
    
    private String sender = "郵箱賬號";

    @Override
    public void sendMail(Bespeak bespeak) throws Exception {
        MailMessage mailMessage = new MailMessage();
        mailMessage.setServer(smtpHost);
        mailMessage.setUsername(username);
        mailMessage.setPassword(password);
        mailMessage.setNickname(nickname);
        mailMessage.setSender(sender);
        List<String> receiverList = new ArrayList<String>();
        receiverList.add("接收郵箱賬號");
        mailMessage.setReceiverList(receiverList);
        mailMessage.setSubject("訪客通知");
        mailMessage.setTemplateName("mealEmail.ftl");
        Map<String, String> param = getMailContent();
        mailMessage.setMap(param);
        try{
			//呼叫傳送郵件的工具類中的方法,傳送郵件
            MailUtils.sendMail(mailMessage);
        } catch (Exception ex) {
            logger.error("傳送失敗" + ex.getMessage());
            ex.printStackTrace();
            throw new RuntimeException("郵件傳送失敗!");
        }
    }
    
    private Map getMailContent(){
        Map<String, String> param = new HashMap<String, String>();
        param.put("visitorName", "張三");
        param.put("visitorNum", "1");
        return param;
        
    }
}