Java springboot 發送郵箱,普通文字、HTML(普通拼接HTML、使用freemaker 生成HTML)、附件、圖片

一、maven項目添加依賴

<!-- 發送郵件 spring-boot-starter-mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- freemarker 模板 -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

二、接口編寫

service 層

/**
 * @Description 發送郵件接口
 */
public interface MailService {

    /**
     * @Description 發送簡單的文本文件,to:收件人 subject:主題 content:內容
     * @Param [to, subject, content]
     **/
    public void sendSimpleMail(String to, String subject, String content);

    /**
     * @Description 發送html,to:收件人 subject:主題 content:內容
     * @Param [to, subject, content]
     **/
    public void sendHtmlMail(String to, String subject, String content);

    /**
     * @Description 發送一個帶附件的郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     * @param filePath 文件路徑
     */
    public void sendAttachmentMail(String to, String subject, String content, String filePath);
    
    /**
     * @Description 發送一個圖片帶附件的郵件
     * @param to 收件人
     * @param subject 主題
     * @param content 內容
     * @param rscPath 圖片
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath);
}

serviceImpl 

import java.io.File;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 */
@Service
public class MailServiceImpl implements MailService {

    // 發送人的用戶名,郵箱地址
    @Value("${spring.mail.username}")
    private String from;

    /**
     * JavaMailSender 用來發送郵件
     * springboot application.properties 文件設置 spring.mail
     */
    @Autowired
    private JavaMailSender mailSender;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        mailSender.send(mailMessage);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);

            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //將content裏面的標籤進行處理,否則爲正常的文本處理
            messageHelper.setText(content, true);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(message);

    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            // 帶上附件,參數傳true,否則會報錯.
            // Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);

            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content);
            
            //設置附件
            FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
            String filename = fileSystemResource.getFilename();
            messageHelper.addAttachment(filename, fileSystemResource);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        } finally {
		}
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            //帶上附件,參數傳true,否則會報錯.
            //Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            //構造郵件內部的圖片
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            //對應的圖片src路徑
            messageHelper.addInline("img", file);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(mimeMessage);
    }
}

三、application.propertis 文件配置

springboot 使用郵箱的方式
# QQ/163郵箱
#smtp.163.com smtp.qq.com
#spring.mail.host=smtp.qq.com
#spring.mail.username=賬號
#spring.mail.password=授權碼
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true
#spring.mail.default-encoding=UTF-8

# 騰訊企業郵箱
spring.mail.host=smtp.exmail.qq.com
spring.mail.username=賬號
spring.mail.password=密碼
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
#騰訊企業郵箱 端口的寫法有些區別
spring.mail.properties.mail.smtp.socketFactory.port=465

QQ授權碼獲取: POP3/SMTP服務 開啓後會得到授權碼

163 (網易)開啓授權碼

XML 配置 FreeMarkerConfigurer / 也可直接創建對象(讀取ftl文佳,生成HTML)

<!-- 配置freeMarkerConfigurer進行屬性值的注入 -->  
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
    <property name="templateLoaderPaths" value="classpath:templates" />  
    <property name="freemarkerSettings">  
        <props>  
             <prop key="template_update_delay">1800</prop>模板更新延時  
             <prop key="default_encoding">UTF-8</prop>  
             <prop key="locale">zh_CN</prop>  
        </props>  
    </property>
</bean>

mail.ftl freeMaker模板編寫

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf8">
    </head>
    <body>
        用戶名爲:<font color='green' size='16'>${name}</font></br>
        <font color='blue' size='16'>${id}</font>
    </body>
</html>

四、springboot 測試

package com.monitor.application;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.monitor.email.MailService;

/**
 * springboot 郵箱測試類
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailSendTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    
    private String to = "[email protected]";

    //主題
    String subject = "主題內容";

    @Test
    public void test01() {
        String content = "一個簡單的文本發送";

        mailService.sendSimpleMail(to,subject,content);
    }

    @Test
    public void test02() {
        String content = "<html> <h1 style=\"color:red \" >一個簡單的html發送</h1></html>";

        mailService.sendHtmlMail(to,subject,content);
    }

    @Test
    // XML配置:發送html文件,通過freemarker模板構造
    public void getFreemarkerByXml() throws IOException, TemplateException {
    	Template template =  freeMarkerConfigurer.getConfiguration().getTemplate("mail.ftl");
	    
	    // FreeMarker通過Map傳遞動態數據
	    Map<String,Object> map = new HashMap<String,Object>();
	    // 注意動態數據的key和模板標籤中指定的屬性相匹配
	    map.put("name","freeMarker 姓名");
	    map.put("id","ID:456125");
	    
	    // 解析模板並替換動態數據,最終content將替換模板文件中的${content}標籤。
	    String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
	    
	    mailService.sendHtmlMail(to, subject , htmlTxt);
    }

    @Test
    // 創建對象:通過freemarker模板構造郵件內容
    public void getFreemarkerByObject() throws IOException, TemplateException {
        
	    // 通過指定模板名獲取FreeMarker模板實例
        
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
		
		Properties settings = new Properties();
		settings.setProperty("locale", "zh_CN");
		settings.setProperty("default_encoding", "UTF-8");
		freeMarkerConfigurer.setFreemarkerSettings(settings);
		
		String path = System.getProperty("user.dir");  // 獲取項目根目錄
		FileTemplateLoader ftl1 = new FileTemplateLoader(new File(path + "\\src\\main\\resources\\templates"));  // 拼接上自己對應的模板位置
		ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
		TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ctl };  // 可配置多個路徑, ftl2,ftl3 ,添加在{} 裏面即可.
		MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
		
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);  // 根據自己引入的版本設置
		configuration.setTemplateLoader(mtl);
		
		freeMarkerConfigurer.setConfiguration(configuration);
		
		
	    Template template =  freeMarkerConfigurer.getConfiguration().getTemplate("mail.ftl");
	    
	    // FreeMarker通過Map傳遞動態數據
	    Map<String,Object> map = new HashMap<String,Object>();
	    // 注意動態數據的key和模板標籤中指定的屬性相匹配
	    map.put("name","freeMarker 姓名");
	    map.put("id","ID456125");
	    
	    // 解析模板並替換動態數據,最終content將替換模板文件中的${content}標籤。
	    String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
	    
	    mailService.sendHtmlMail(to, subject , htmlTxt);
    }

    @Test
    public void test04() {
        String content = "一個簡單的帶附件發送";

        String filePath = "C:\\Users\\DELL\\Desktop\\Test.docx";
        mailService.sendAttachmentMail(to,subject,content,filePath);
    }

    @Test
    //發送圖片
    public void test05() {
        //src對應img
        String content = "<html><body>一個簡單的圖片發送:<img src=\'cid:img" + "\'></img></body></html>";
        //圖片地址
        String filePath = "D:\\head.png";
        mailService.sendInlineResourceMail(to,subject,content,filePath);
    }
}

五、驗證郵箱是否真實有效

大佬文章:Java與郵件系統交互之使用Socket驗證郵箱是否存在(非正則表達式)

 

其它實現大佬:Spring結合freemaker配置發送郵件, XML 文件配置

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