Spring Boot項目中發送郵件

項目地址

  • 碼雲 https://gitee.com/txiaoqiang/springboot_mail.git(發送郵件)
  • 碼雲 https://gitee.com/txiaoqiang/javamails.git (讀取郵件,發送郵件)

郵件發送關鍵點

  • 使用spring boot 項目,咱們能夠節約不少的工做,spring boot將一些基礎的配置都幫咱們約束好了,咱們只須要按照標準去配置便可。
  • 項目主配置文件配置(application.yml ),這裏我將演示三種不一樣類型的郵箱帳號發送郵件:
    • QQ 企業郵箱
# QQ企業郵箱
 spring:
 mail:
 host: smtp.exmail.qq.com  # 對應各郵箱官方提示
 username: tangz***g@wei***ada.net  # 帳號
 password: ETQpK***gxYGd  # 企業郵箱爲 客戶端專用密碼
 properties:
 mail:
 smtp:
 auth: true # 使用
 starttls: # 使用 SSL 安全協議,必須配置以下
 enable: true
 required: true
 port: 465  # 端口
 protocol: smtps # 協議

 # 配置常量
 mail:
 fromMail:
 addr: tang***ng@w***.net  # 發送人
 receptionMail:
 addr: 332***4141@qq.com  # 接收人
複製代碼
- QQ 普通郵箱
複製代碼
# 普通QQ郵箱
spring:
 mail:
 host: smtp.qq.com
 username: 191***933@qq.com # 郵箱帳號
 password: twuhvbfgndkwbgbf # 受權碼(下面將會告訴你怎麼申請)
 properties:
 mail:
 smtp:
 auth: true
 starttls:
 enable: true
 required: true
mail:
 fromMail:
 addr: 191****33@qq.com
複製代碼
- 網易 163 郵箱
複製代碼
# 網易 163 郵箱
spring:
 mail:
 host: smtp.163.com
 username: 1****61@163.com # 郵箱登陸帳號
 password: ****.  # 郵箱登陸密碼
mail:
 fromMail:
 addr: 1****61@163.com
複製代碼

QQ企業郵箱客戶端專用碼申請(關於申請 QQ企業郵箱不作多的介紹)

  • 第一步:登陸企業郵箱後點擊 設置 並找到 客戶端設置肯定開啓了 POP/SMTP服務。

  • 第二步:開啓安全登陸,並生產 客戶端專用密碼

QQ普通郵箱開啓受權碼

  • 第一步:點擊 設置 > 帳戶 ,向下拉,找到 POOP/SMTP服務並開啓。

  • 第二步:點擊 生成受權碼,按照官方的提示完成驗證便可生成 受權碼

項目pom.xml文件準備

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        
        <!--spring boot mail 集成jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
複製代碼

mail 服務接口定義

public interface MailService {

    /** * 發送純文本郵件 * @param toAddr 發送給誰 * @param title 標題 * @param content 內容 */
    public void sendTextMail(String toAddr, String title, String content);

    /** * 發送 html 郵件 * @param toAddr * @param title * @param content 內容(HTML) */
    public void sendHtmlMail(String toAddr, String title, String content);

    /** * 發送待附件的郵件 * @param toAddr * @param title * @param content * @param filePath 附件地址 */
    public void sendAttachmentsMail(String toAddr, String title, String content, String filePath);

    /** * 發送文本中有靜態資源(圖片)的郵件 * @param toAddr * @param title * @param content * @param rscPath 資源路徑 * @param rscId 資源id (可能有多個圖片) */
    public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId);

}
複製代碼

服務接口的實現

@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;

    /** * 發送文本郵件 * @param toAddr * @param title * @param content */
    @Override
    public void sendTextMail(String toAddr, String title, String content) {
        // 純文本郵件對象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(toAddr);
        message.setSubject(title);
        message.setText(content);

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

    }

    /** * 發送html郵件 * @param toAddr * @param title * @param content */
    @Override
    public void sendHtmlMail(String toAddr, String title, String content) {
        // html 郵件對象
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示須要建立一個multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(toAddr);
            helper.setSubject(title);
            helper.setText(content, true);

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


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

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

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

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


    /** * 發送正文中有靜態資源(圖片)的郵件 * @param toAddr * @param title * @param content * @param rscPath * @param rscId */
    public void sendInlineResourceMail(String toAddr, String title, String content, String rscPath, String rscId){
        MimeMessage message = mailSender.createMimeMessage();

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

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

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

測試類

@RunWith(SpringRunner.class)
@SpringBootTest
public class BasemailApplicationTests {

	@Value("${mail.receptionMail.addr}")
	private String receptionMailAddr;

	@Autowired
	private MailService mailService;

	@Autowired
	private TemplateEngine templateEngine;

	/** * 測試 文本郵件 * @throws Exception */
	@Test
	public void testSimpleMail() throws Exception {
		mailService.sendTextMail(receptionMailAddr,"測試文本郵箱發送","你好你好!");
	}

	/** * 測試 html 郵箱 * @throws Exception */
	@Test
	public void testHtmlMail() throws Exception {
		String content="<html>\n" +
				"<body>\n" +
				" <h3>hello world ! 這是一封html郵件!</h3>\n" +
				"</body>\n" +
				"</html>";
		mailService.sendHtmlMail(receptionMailAddr,"test simple mail",content);
	}

	@Test
	public void sendAttachmentsMail() {
		String filePath="C:\\\\Users\\\\Administrator\\\\Desktop\\\\java併發學習.txt";
		mailService.sendAttachmentsMail(receptionMailAddr, "主題:帶附件的郵件", "有附件,請查收!", filePath);
	}


	@Test
	public void sendInlineResourceMail() {
		String rscId = "neo006";
		String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>";
		String imgPath = "C:\\\\Users\\\\Administrator\\\\Desktop\\\\testMail.png";

		mailService.sendInlineResourceMail(receptionMailAddr, "主題:這是有圖片的郵件", content, imgPath, rscId);
	}


	@Test
	public void sendTemplateMail() {
		//建立郵件正文
		Context context = new Context();
		context.setVariable("id", "006");

		// 傳遞 emailTemplate.html 模板須要的值,並將模板轉換爲 String
		String emailContent = templateEngine.process("emailTemplate", context);

		mailService.sendHtmlMail(receptionMailAddr,"主題:這是模板郵件",emailContent);
	}

}
複製代碼
相關文章
相關標籤/搜索