SpringBoot發送Email筆記

1、依賴

<!-- Email發送 -->
        <dependency>  
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-mail</artifactId>
		</dependency>  
		<!-- 發送模板郵件 -->
		<dependency> 
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-velocity</artifactId>
			<version>1.1.3.RELEASE</version>
		</dependency>

2、配置郵箱信息,這裏本來我是配置在yml裏結果一直測不成功,就乾脆將配置放在了代碼裏,所以我yml裏沒有配置關於發送郵件的任何東西,改天再測放到yml裏

EmailUtils

package com.demo.springboot.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.collections.map.HashedMap;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class EmailUtils{

    private JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    private VelocityEngine velocityEngine = new VelocityEngine();
    List<String> tos = new ArrayList<String>();
    
    private String username = "***@zatxtech.com";
    private String pass = "******";
	
    private void init(){
    			//普通qq配置
    			//設置郵箱主機 若使用企業郵箱則爲smtp.exmail.qq.com
    			//mailSender.setHost("smtp.qq.com");
    			//設置用戶名
    			//mailSender.setUsername("[email protected]");
    			//設置密碼,該處的密碼是QQ郵箱開啓SMTP的授權碼而非QQ密碼 企業郵箱則爲客戶端專用密碼,需綁定微信後設置
    	        //mailSender.setPassword("oebjutrcnamahbhe");
    	        //mailSender.setDefaultEncoding("UTF-8");
    			
    			//騰訊企業郵箱配置
    			mailSender.setHost("smtp.exmail.qq.com");
    			mailSender.setUsername(username);
    			mailSender.setPassword(pass);
    			mailSender.setDefaultEncoding("UTF-8");

    }
    
	/**
	 * 發送一條簡單的郵件
	 * @param to
	 * @param subject
	 * @param content
	 */
    @Async
	public void sendSimpleMail(String to, String subject, String content) {

		init();
		
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要創建一個multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(username);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            System.out.println("發送成功~");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("發送失敗~");
        }
    }
	
	/**
	 * 發送一個HTML郵件
	 * @param to	發送地址
	 * @param subject	主題
	 * @param HTMLContent	內容《HTML格式》
	 */
	public void sendHtmlMail(String to, String subject, String HTMLContent) {
		init();
		
		MimeMessage message = mailSender.createMimeMessage();
	    try {
	        MimeMessageHelper helper = new MimeMessageHelper(message, true);
	        helper.setFrom(username);
	        helper.setTo(to);
	        helper.setSubject(subject);
	        helper.setText(HTMLContent, true);
	        System.out.println("發送成功~");
	    } catch (MessagingException e) {
	        e.printStackTrace();
	        System.out.println("發送失敗~");
	    }

	    mailSender.send(message);
	}
	
	/**
	 * 發送一個模板消息
	 * @param to	發送地址
	 * @param subject	標題
	 * @param data	模板數據
	 */
	public void sendTemplateMail(String to, String subject,HashMap data) {
		init();
		
		try {
			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(username);
			helper.setTo(to);
			helper.setSubject(subject);
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("username", data.get("username"));
			String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "template.vm", "UTF-8", model);
			helper.setText(text, true);
			mailSender.send(mimeMessage);
			System.out.println("發送成功~");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("發送失敗~");
		}
	}
	
	/**
	 * 獲取touser列表
	 * @return
	 */
	public List<String> getToUsers(){
		try {
			Properties prop = new Properties();
			//讀取屬性文件a.properties
			InputStream in = EmailUtils.class.getClassLoader().
					getResourceAsStream("email.properties");
//			InputStream in = new BufferedInputStream (
//					new FileInputStream("email.properties"));
			prop.load(in);     ///加載屬性列表
			Iterator<String> it=prop.stringPropertyNames().iterator();
			while(it.hasNext()){
			    String key=it.next();
//            System.out.println(key);
			    tos.add(key);
			}
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("找不到email配置文件");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("讀取異常");
		}
		return tos;
	}
	
	public static void main(String[] args) {
//		new EmailUtils().sendSimpleMail("***@qq.com","hello!","hello!");
		
//		StringBuffer sb = new StringBuffer();
//        sb.append("<h1>大標題-h1</h1>")
//          .append("<p style='color:#F00'>紅色字</p>")
//          .append("<p style='text-align:right'>右對齊</p>");
//		new EmailUtils().sendHtmlMail("***@qq.com", "HTML", sb.toString());
		
//		HashMap<String, String> map = new HashMap<String, String>();
//		map.put("username", "ddd");
//		new EmailUtils().sendTemplateMail("***@qq.com", "Template", map);
	}
}

3、email.properties

***@zatxtech.com
***@zatxtech.com
***@zatxtech.com

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章