一。如何实现
1. 引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 配置文件
# JavaMailSender 邮件发送的配置
spring.mail.host=hwhzimap.qiye.163.com
spring.mail.protocol=smtp
spring.mail.username=发件箱地址
spring.mail.password=发件箱的授权码#需要自行去邮箱设置,也可以直接使用邮箱的登录密码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
3. 编写MailService
import com.alibaba.fastjson.JSONObject;
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.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;
@Service
public class MailService {
@Resource
private JavaMailSender mailSender; //框架自带的,直接注入即可
@Value("${spring.mail.username}")
private String Sender; //读取配置文件中的参数
public void sendAttachmentsMail(String email) {//参数email表示收件箱地址
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(Sender);
helper.setTo(email);
helper.setSubject("主题:这是一封带附件的邮件");
helper.setText("纪要详情见附件!");//如果要发送html,加入第二个参数并设置为true:helper.setText("纪要详情见附件!", true);
FileSystemResource file1 = new FileSystemResource(new File("D:\\voice\\1.txt"));
FileSystemResource file = new FileSystemResource(new File("D:\\voice\\1.wav"));
//加入附件
helper.addAttachment("小说.txt", file1);
helper.addAttachment("语音.wav", file);
} catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
}
}
4. 在需要发送邮件的地方调用即可
二。遇到的问题
1.报错提示: Invalid Padding length: 165
bug 描述:每次重启程序后都可以正常发送邮件,但是发到第四封的时候就开始报错。捣鼓了一整天,发现是 jdk 的问题。
解决办法:替换 jdk 下的 jre>lib>security 目录下的 local_policy.jar 和 US_export_policy.jar 两 个jar 包即可。
jar包下载 链接: https://pan.baidu.com/s/1GCisn2vUxrkA3DSakIA56w 提取码: vhkh