1. 程式人生 > >springboot初學---email郵件的發送

springboot初學---email郵件的發送

初學 郵件發送 resource shm tle demo artifact src service

1.jar包依賴

<!-- 郵件 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.在application.properties中添加配置

# 郵箱的配置
## 郵箱服務器地址
spring.mail.host=smtp.163.com
## 用戶名
spring.mail.username=郵箱全名
## 密碼
spring.mail.password=郵箱的授權碼,不是登錄密碼
## 編碼格式
spring.mail.default-encoding=UTF-8
## 以誰來發郵件
mail.fromMail.addr=郵箱全名

3.編寫emailservice的接口類

public interface MailService {

	public void sendSimpleMail(String to, String subject, String content);

	public void sendHtmlMail(String to, String subject, String content);

	public void sendAttachmentsMail(String to, String subject, String content, String filePath);

	public void sendInlineResourceMail(String to, String subject, String content, Map<String, String> rscPath);
}

4.編寫emailServiceImpl的實現類

import java.io.File;
import java.util.Map;

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.Component;

import com.example.demo.service.MailService;

/**
 * 發送郵件
 * @author Leruan
 *
 */
@Component
public class MailServiceImpl implements MailService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private JavaMailSender mailSender;

	@Value("${mail.fromMail.addr}")
	private String from;

	/**
	 * 簡單的發送郵件
	 */
	@Override
	public void sendSimpleMail(String to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(content);

		try {
			mailSender.send(message);
			logger.info("簡單郵件已經發送。");
		} catch (Exception e) {
			logger.error("發送簡單郵件時發生異常!", e);
		}

	}

	/**
	 * 發送html格式的郵件
	 */
	@Override
	public void sendHtmlMail(String to, String subject, String content) {
		MimeMessage message = mailSender.createMimeMessage();

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

			mailSender.send(message);
			logger.info("html郵件發送成功");
		} catch (MessagingException e) {
			logger.error("發送html郵件時發生異常!", e);
		}

	}

	/**
	 * 發送帶附件的郵件
	 */
	@Override
	public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
		MimeMessage message = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content, true);

			FileSystemResource file = new FileSystemResource(new File(filePath));
			String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
			helper.addAttachment(fileName, file);

			mailSender.send(message);
			logger.info("帶附件的郵件已經發送。");
		} catch (MessagingException e) {
			logger.error("發送帶附件的郵件時發生異常!", e);
		}

	}

	@Override
	/**
	 * 發送嵌入靜態資源的郵件
	 */
	public void sendInlineResourceMail(String to, String subject, String content, Map<String, String> rscPath) {
		MimeMessage message = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(from);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content, true);

			for (String key : rscPath.keySet()) {
				FileSystemResource res = new FileSystemResource(new File(rscPath.get(key)));
				helper.addInline(key, res);
			}

			mailSender.send(message);
			logger.info("嵌入靜態資源的郵件已經發送。");
		} catch (MessagingException e) {
			logger.error("發送嵌入靜態資源的郵件時發生異常!", e);
		}

	}

}

5.郵件的測試

<1>.簡單郵件測試

/**
 * 郵件測試
 * @author Leruan
 *
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceTest {

	@Autowired
	private MailService mailService;

	@Test
	/**
	 * 簡單郵件的測試
	 * @throws Exception
	 */
	public void testSimpleMail() throws Exception {
		mailService.sendSimpleMail("[email protected]", "給華爺的一封信", "我愛你,華爺");
	}
}

<2>.html格式的郵件測試

@Test
/**
 * html格式的郵件測試
 * @throws Exception
 */
public void testHtmlMail() throws Exception {
	String content = "<html>\n" + "<body>\n" + "    <h3>親愛的華爺:你好!!!</h3>\n" + "</body>\n" + "</html>";
	mailService.sendHtmlMail("[email protected]", "致華爺的一封信", content);
}

<3>.帶附近的郵件測試

@Test
/**
 * 測試帶附件的郵件發送
 */
public void sendAttachmentsMail() {
	String filePath = "C:\\Users\\Leruan\\Desktop\\測試用-圖片\\sdfgsdfgsfdgsfdg.jpg";
	mailService.sendAttachmentsMail("[email protected]", "主題:帶附件的郵件", "有附件,請查收!", filePath);
}

<4>.嵌入圖片的郵件測試

@Test
/**
 * 發送帶嵌入圖片的郵件
 */
public void sendInlineResourceMail() {
	String rscId = "neo006";
	String rscId2 = "007";
	String rscId3 = "008";
	String imgPath = "C:\\Users\\Leruan\\Desktop\\測試用-圖片\\fhgjfgjh.jpg";
	String imgPath2 = "C:\\Users\\Leruan\\Desktop\\測試用-圖片\\fdgdrtreh.jpg";
	String imgPath3 = "C:\\Users\\Leruan\\Desktop\\測試用-圖片\\和鋼結構焊接.jpg";
	Map<String, String> map = new HashMap<String, String>();
	map.put(rscId, imgPath);
	map.put(rscId2, imgPath2);
	map.put(rscId3, imgPath3);
	String content = "<html><body>這是有圖片的郵件:" + "<br/>第一行圖片:<br/><img src=\‘cid:" + rscId
			+ "\‘ ><br/>第二行圖片:<br/><img src=\‘cid:" + rscId2 + "\‘ ><br/>第三行圖片:<br/><img src=\‘cid:" + rscId3
			+ "\‘ ></body></html>";
	mailService.sendInlineResourceMail("[email protected]", "主題:這是有圖片的郵件", content, map);
}

<5>.模板類型的郵件測試---html格式

1).引入thymeleaf的jar包依賴

<!-- thymeleaf模板 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2).在resorces/templates下創建emailTemplate.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>Title</title>
    </head>
    <body>
        您好,這是驗證郵件,請點擊下面的鏈接完成驗證,<br/>
        <a href="#" th:href="@{ http://www.baidu.com/huaye/{id}(id=${id}) }">激活賬號</a>
    </body>
</html>

3).測試

@Autowired
private TemplateEngine templateEngine;

@Test
/**
 * 測試模板類型的郵件
 */
public void sendTemplateMail() {
	//創建郵件正文
	Context context = new Context();
	context.setVariable("id", "006");
	String emailContent = templateEngine.process("emailTemplate", context);

	mailService.sendHtmlMail("[email protected]", "主題:這是模板郵件", emailContent);
}

  

springboot初學---email郵件的發送