springboot 整合邮件服务(网易 163 邮箱)

1. 新建 maven 项目,引入依赖

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

2. 新建接口文件

package com.example.demo.service;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;

public interface MailService {
	/**
	 * 1. from 发件人
	 * 2. to 收件人
	 * 3. subject 邮件主题
	 * 4. cc 抄送
	 * 5. bcc 密送
	 */
	void sendMail(String to, String subject, String content, Path path) throws MessagingException, UnsupportedEncodingException;

}

3. 新建实现类

package com.example.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

@Slf4j
@Service
public class MailServiceImpl implements MailService {

	@Value("${mail.from.mail.addr}")
	private String from;
	@Value("${mail.from.mail.pass1}")
	private String password1;
	@Value("${mail.from.mail.pass2}")
	private String password2;

	@Override
	public void sendMail(String to, String subject, String content, Path path) throws MessagingException, UnsupportedEncodingException {
		log.info("send start");
		log.info("username >>> " + from);
		log.info("p1 >>> " + password1);
		log.info("p2 >>> " + password2);

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.host", "smtp.163.com");
		properties.setProperty("mail.smtp.username", from);
		properties.setProperty("mail.smtp.password", password1);
		properties.setProperty("mail.smtp.defaultEncoding", "UTF-8");
		properties.setProperty("mail.smtp.auth", "true");
//		安全类型:ssl 端口号:465
		properties.setProperty("mail.smtp.port", "465");
		properties.put("mail.smtp.ssl.enable", "true");

		Session session = Session.getDefaultInstance(properties, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, password2);
			}
		});

		//得到一个邮件
		MimeMessage message = new MimeMessage(session);

		// 设置发件人 from
		message.setFrom(new InternetAddress(from));

		//设置收件人 to
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

		//设置主题 subject
		message.setSubject(subject);

		//设置包含 html 内容的 mimebodypart
		Multipart multipart = new MimeMultipart();
		BodyPart html = new MimeBodyPart();
		html.setContent(content, "text/html; charset=utf-8");
		multipart.addBodyPart(html);

		//设置附件。。。

		if (path != null) {
			File file = path.toFile();

			String fileName = file.getName();
			log.info("fileName >>> " + fileName);
			BodyPart bodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(file);
			bodyPart.setDataHandler(new DataHandler(source));
			//避免 filename 乱码
			bodyPart.setFileName(MimeUtility.encodeWord(fileName));
			multipart.addBodyPart(bodyPart);
		}
		//设置邮件内容
		message.setContent(multipart);
		Transport.send(message);
		log.info("send end");
	}
}

4. 在配置文件中配置用户名、密码信息

application.properties

mail.from.mail.addr=xxx
mail.from.mail.pass1=xxx
# 客户端的授权码
mail.from.mail.pass2=xxx 

5. 测试类

package com.example.demo;

import com.example.demo.service.MailServiceImpl;

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 javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;

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

	@Autowired
	MailServiceImpl mailService;

	@Test
	public void test() {

		try {
			mailService.sendMail("XXX@163.com",
					"test-mail",
					"<h1>TEST</h1>",
					Paths.get("/Users/zhangzheng/Desktop/test-mail.rtf"));
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值