Springboot发送邮件
添加依赖
首先添加发送邮件依赖的包:spring-boot-starter-mail
<!--Email-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
这里我们使用的是
org.springframework.mail.javamail.JavaMailSender 接口
里面包含了几个方法
JavaMailSender
public interface JavaMailSender extends MailSender {
MimeMessage createMimeMessage();
MimeMessage createMimeMessage(InputStream var1) throws MailException;
void send(MimeMessage var1) throws MailException;
void send(MimeMessage... var1) throws MailException;
void send(MimeMessagePreparator var1) throws MailException;
void send(MimeMessagePreparator... var1) throws MailException;
}
当然邮件有不同的类型的邮件:普通文本内容、Html内容、带附件的邮件等
这里我们创建一个MailUtil,里面放置发送邮件的工具方法:
@Component
public class MailUtil {
@Resource
private JavaMailSender mailSender;
/**你的邮件地址*/
private final String SENDER = "******@qq.com"
//发送普通文本内容的邮件
public void sendTextMessage(String receiver,String title,String content){
//...
}
//发送 HTML内容的邮件
public void sendHtmlMessage(String receiver,String title,String content){
//...
}
//发送携带附件的邮件
//public void sendAccessoriesMessage(){}
}
发送普通文本文件
@Async
public void sendTextMessage(String receiver,String title,String content){
/**简单的邮件(普通文本内容邮件)*/
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(SENDER);
message.setTo(receiver);
message.setSubject(title);
message.setText(content);
//发送邮件
mailSender.send(message);
System.out.println("["+receiver+"]的邮件已经成功发送。"+new Date());
}
我们来看看这个SImpleMailMessage 对象:
SimpleMailMessage
public class SimpleMailMessage implements MailMessage, Serializable {
@Nullable
private String from;
@Nullable
private String replyTo;
@Nullable
private String[] to;
@Nullable
private String[] cc;
@Nullable
private String[] bcc;
@Nullable
private Date sentDate;
@Nullable
private String subject;
@Nullable
private String text;
public SimpleMailMessage() {
}
//....
}
里面共8个属性,可以在里面进行设置
from(发送人)、replyTo(回复)、to(接收人,表示希望得到回应)、cc(副本抄送,并不希望对邮件进行回复)、bcc(Blind Carbon Copy,密件抄送)、sentDate(发送日期)、subject(标题)、text(文本内容)
Controller中测试:
@Autowired
MailUtil mailUtil ;
@RequestMapping("/")
public Map<String,Object> sendTextMessage(String to,String title,String content){
Map<String,Object> map = new HashMap<>();
try{
mailUtil.send("********@qq.com","【标题】邮件测试","邮件文本内容");
map.put("msg","success");
map.put("code",200);
}catch(MailException e){
map.put("msg","发送失败");
map.put("code",500);
}
return map;
}
当然这里只是简单的测试,并不符合controller的定位和实际开发:
controller 不负责处理业务、在controller中不应使用try/catch ,应使用controllerAdvice 捕获异常,自动跳转页面
发送Html邮件
先看代码
@Async
public void sendHtmlMessage(String receiver,String title,String content){
MimeMessage mimeMessage = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setFrom(SENDER);
helper.setTo(receiver);
helper.setSubject(title);
helper.setText(content,true);
mailSender.send(mimeMessage);
System.out.println("HTML 邮件发送完成");
}catch (MessagingException e) {
e.printStackTrace();
}
}
这里使用了MimeMessage 用于发送
MimeMessage\
public class MimeMessage extends Message implements MimePart {
protected DataHandler dh;
protected byte[] content;
protected InputStream contentStream;
protected InternetHeaders headers;
protected Flags flags;
protected boolean modified;
protected boolean saved;
protected Object cachedContent;
private static final MailDateFormat mailDateFormat = new MailDateFormat();
private boolean strict;
private boolean allowutf8;
private static final Flags answeredFlag;
//....
}
字段属性包括:DataHander(数据处理器)、content(文章内容)、contentStream(文章流)、headers(标题)、Flags(邮件标志)、modified(修改)、saved(保存)、cachedContent(缓存内容)、mailDateForm(邮件日期表)、strict(严格模式)、allowutf8(允许HeaderUtf8编码)、answeredFlag(邮件回复标志)
在控制器中测试:
@RequestMapping("/sendHtml")
public Map<String,Object> sendHtml(){
Map<String,Object> map = new HashMap<>();
String message = "<html><head></head><body><h1>你好</h1></body></html>";
try{
mailUtil.sendHtmlMessage("815787213@qq.com","Html - Tiltle",message);
map.put("msg","发送成功");
map.put("code","200");
}catch (Exception e){
map.put("msg","发送失败"+e);
map.put("code","500");
}
return map;
}
可以看到HTML邮件已经发送成功了,内容也是正确的
可以看到中间我们使用了 MimeMessageHelper ,在spring 的官网上这样说道:org.springframework.mail.javamail.MimeMessageHelper
是处理JavaMail邮件时比较顺手组件之一。它可以让你摆脱繁复的JavaMail API。 通过使用MimeMessageHelper
,创建一个MimeMessage
实例将非常容易
MimeMessageHelper
public class MimeMessageHelper {
public static final int MULTIPART_MODE_NO = 0;
public static final int MULTIPART_MODE_MIXED = 1;
public static final int MULTIPART_MODE_RELATED = 2;
public static final int MULTIPART_MODE_MIXED_RELATED = 3;
private static final String MULTIPART_SUBTYPE_MIXED = "mixed";
private static final String MULTIPART_SUBTYPE_RELATED = "related";
private static final String MULTIPART_SUBTYPE_ALTERNATIVE = "alternative";
private static final String CONTENT_TYPE_ALTERNATIVE = "text/alternative";
private static final String CONTENT_TYPE_HTML = "text/html";
private static final String CONTENT_TYPE_CHARSET_SUFFIX = ";charset=";
private static final String HEADER_PRIORITY = "X-Priority";
private static final String HEADER_CONTENT_ID = "Content-ID";
private final MimeMessage mimeMessage;
@Nullable
private MimeMultipart rootMimeMultipart;
@Nullable
private MimeMultipart mimeMultipart;
@Nullable
private final String encoding;
private FileTypeMap fileTypeMap;
private boolean validateAddresses = false;
//....
}
有四种模式、子类型、文章内容类型、标题类型可以设置。字段属性包括 MimeMultipart encoding等,让对邮件的设置更加的便捷。
发送附件
这个相对于来说很简单,就是调用他的一个方法
FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addAttachment("CoolImage.jpg", file);
这个是官网上给出的示例。