Springboot中配置Mail和普通mail的实现方式
作者:喵喵@香菜
这篇文章主要介绍了Springboot中配置Mail和普通mail的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
一、开通SMTP
SMTP是一种简单的邮件传输协议,SMTP只能够推送邮件,如果想要在邮件服务器上下拉邮件,可以使用POP3或者IMAP协议。
自己的邮箱就可以开通SMTP,以QQ邮箱为例(163或者其他邮箱开通大同小异)
1)打开自己的QQ邮箱—【设置】—【账户】—【POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务】
将这几个开启,如果你没有开启的话,开启后点击页面上的【生成授权码】,然后根据提示(发送短信)操作就可以。
这里的授权码在代码中要用到,用于发送邮件时的密码,注意这里不是登陆邮箱的密码,可以生成多个授权码,有这个授权码就可以通过你的邮箱发送邮件。
开通完毕
二、springboot中配置mail(spring boot环境已经搭好)
1)application.yml文件如下
spring: mail: #如果是163 就为 smtp.163.com host: smtp.qq.com #刚才开通了SMTP的QQ邮箱 username: 你的QQ邮箱@foxmail.com # 在页面生成的授权码 password: 授权码 default-encoding: utf-8 protocol: smtp # 默认端口 port: 25 properties: mail: smtp: # 设置是否需要认证,如果为true,那么用户名和密码就必须的, # 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。 auth: true starttls: # STARTTLS[1] 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。 enable: true required: true #邮件配置(自定义设置,主要配置了收件人和发件人,这些可以当做发送邮件的参数) mail-config: environmental: 邮件测试 # 发件人邮箱 from: 发件人@foxmail.com # 收件人邮箱(抄送人) recipient: - "收件人1的邮箱@foxmail.com" - "收件人2的邮箱@qq.com"
2)maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
3)读取发件人和收件人配置类
package com.zlc.mail.coonfig; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * @描述 : 邮件配置 * @Author : 追到乌云的尽头找太阳 * @Date : 2019/10/18 14:52 **/ @Configuration @ConfigurationProperties(prefix = "mail-config") public class MailConfig { private String environmental; private String from; private String [] recipient = null; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String[] getRecipient() { return recipient; } public void setRecipient(String[] recipient) { this.recipient = recipient; } public String getEnvironmental() { return environmental; } public void setEnvironmental(String environmental) { this.environmental = environmental; } }
4)发送邮件工具类
package com.zlc.mail.util; import com.zlc.mail.coonfig.MailConfig; 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 javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; /** * @描述 : 邮件工具 * @Author : zlc * @Date : 2019/10/10 16:41 **/ @Component public class MailUtil { private final JavaMailSender mailSender; private final MailConfig mailConfig; public MailUtil(JavaMailSender mailSender , MailConfig mailConfig) { this.mailSender = mailSender; this.mailConfig = mailConfig; } public void sendSimpleMail(String subject, String content) { // new 一个简单邮件消息对象 SimpleMailMessage message = new SimpleMailMessage(); // 和配置文件中的的username相同,相当于发送方 message.setFrom(mailConfig.getFrom()); // setCc 抄送,setTo 发送,setBCc密送 message.setCc(mailConfig.getRecipient()); message.setSubject("【类型】:【文本】-【来源】【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】"); // 正文 message.setText(content); // 发送 mailSender.send(message); } public void sendHtmlMail(String subject, String content) { //使用MimeMessage,MIME协议 MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper; //MimeMessageHelper帮助我们设置更丰富的内容 try { helper = new MimeMessageHelper(message, true); helper.setFrom(mailConfig.getFrom()); helper.setTo(mailConfig.getRecipient()); helper.setSubject("【类型】:【HTML】【来源】-【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】"); //true代表支持html helper.setText(content, true); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); // logger.error("发送HTML邮件失败:", e); } } public void sendAttachmentMail(String subject, String content, File file) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper; try { helper = new MimeMessageHelper(message, true); //true代表支持多组件,如附件,图片等 helper.setFrom(mailConfig.getFrom()); helper.setTo(mailConfig.getRecipient()); helper.setSubject("【类型】:【附件】-【来源】-【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】"); helper.setText(content, true); FileSystemResource file1 = new FileSystemResource(file); String fileName = file1.getFilename(); //添加附件,可多次调用该方法添加多个附件 helper.addAttachment(fileName, file1); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } public void sendInlineResourceMail(String subject, String content, String rscPath, String rscId) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper; try { helper = new MimeMessageHelper(message, true); helper.setFrom(mailConfig.getFrom()); helper.setTo(mailConfig.getRecipient()); helper.setSubject("【类型】:【图片】-【来源】-【" + mailConfig.getEnvironmental() + "】-主题【" + subject + "】"); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); //重复使用添加多个图片 helper.addInline(rscId, res); mailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } }
三、普通发送邮件的类,和是否SpringBoot没关系
package com.zlc.mail.javamail; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.util.Properties; /** * @author : 追到乌云的尽头找太阳-(Jacob) * @date : 2019/10/29 17:51 **/ public class MailUtil { public static void sendImageMail(String subject, String conent, String imagePath ) throws MessagingException { // 邮件配置文件 Properties properties = new Properties(); properties.setProperty("mail.protocol","smtp"); properties.setProperty("mail.host","smtp.qq.com"); properties.setProperty("mail.smtp.auth", "true"); //发送邮件时使用的环境配置 Session session = Session.getInstance(properties); //session.setDebug(true); MimeMessage message = new MimeMessage(session); //设置邮件的头 message.setFrom(new InternetAddress("发件人邮箱地址@foxmail.com")); message.setRecipients(Message.RecipientType.TO, "收件人邮箱@foxmail.com"); message.setSubject("【人脸识别】-【主题】-【" + subject + "】"); //设置正文 //搞出文本部分 MimeBodyPart textPart = new MimeBodyPart(); //搞图片部分 MimeBodyPart imagePart = new MimeBodyPart(); imagePart.setContentID("mm"); //把磁盘上的文件加到part中使用到了JAF框架 try { DataHandler dh = new DataHandler(new FileDataSource(imagePath)); imagePart.setDataHandler(dh); }catch (Exception e){ e.printStackTrace(); conent+="读取图片异常,异常信息为:" + e.getMessage(); } textPart.setContent("<h3>内容:"+ conent +"<br/><img src='cid:mm'/>", "text/html"); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(imagePart); //有关系的 mp.setSubType("related"); message.setContent(mp); message.saveChanges(); //发送邮件 Transport ts = session.getTransport(); //密码为授权码不是邮箱的登录密码 ts.connect("开通了smtp的邮箱地址@foxmail.com", "授权码"); //对象,用实例方法 ts.sendMessage(message, message.getAllRecipients()); } public static void sendEnclosureMail(String subject, String conent ,String imagePath, String filePath) throws MessagingException { Properties props = new Properties(); props.setProperty("mail.protocol", "smtp"); props.setProperty("mail.host", "smtp.qq.com"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props); //发送邮件时使用的环境配置 MimeMessage message = new MimeMessage(session); //设置邮件的头 message.setFrom(new InternetAddress("发件人邮箱地址@foxmail.com")); message.setRecipients(Message.RecipientType.TO, "收件人邮箱地址@foxmail.com"); message.setSubject("【人脸识别】-【主题】-【" + subject + "】"); //设置正文 //搞出文本部分 MimeBodyPart textPart = new MimeBodyPart(); MimeBodyPart imagePart = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("")); if ("" != imagePath || null != imagePath) { textPart.setContent("图片<img src='cid:mm'/>", "text/html;charset=UTF-8"); //搞图片部分 imagePart.setContentID("mm"); //把磁盘上的文件加到part中使用到了JAF框架 dh = new DataHandler(new FileDataSource(imagePath)); imagePart.setDataHandler(dh); } MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(imagePart); mp.setSubType("related"); MimeBodyPart textImagePart = new MimeBodyPart(); textImagePart.setContent(mp); //创建附件部分 MimeBodyPart attachmentPart = new MimeBodyPart(); if ("" != filePath || null != filePath){ dh = new DataHandler(new FileDataSource(filePath)); } String filename = dh.getName(); attachmentPart.setDataHandler(dh); //手工设置文件名 防止乱码使用 javaMail里的 MimeUtility进行编码 try { attachmentPart.setFileName(MimeUtility.encodeText(filename)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //最终的 MimeMultipart MimeMultipart finalMp = new MimeMultipart(); finalMp.addBodyPart(attachmentPart); finalMp.addBodyPart(textImagePart); finalMp.setSubType("mixed"); message.setContent(finalMp); message.saveChanges(); //发送邮件 Transport ts = session.getTransport(); ts.connect("开启了smtp的邮箱地址@foxmail.com", "授权码"); ts.sendMessage(message, message.getAllRecipients()); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。