Email邮件发送与激活
1.导包
<!--发送邮件 https://mvnrepository.com/artifact/com.sun.mail/javax.mail --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
2.配置文件
mail.propertiex
#服务器主机名 smtp.xx.com
mail.host=smtp.qq.com
mail.username=XXXXXX@qq.com
#密码/客户端授权码
mail.password=XXXXXXXXXX
#编码字符
mail.defaultEncoding=utf-8
#是否进行用户名密码校验
mail.auth=true
#设置超时时间
mail.timeout=20000
3.配置到容器中
<!-- 读取邮件配置文件, 其中ignore-unresolvable="true"属性是配置文件中存在 多个property-placeholder时出现解析不了的占位符进行忽略掉, --> <context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true"/>
<!--配置邮件接口--> <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${mail.host}"/> <property name="username" value="${mail.username}"/> <property name="password" value="${mail.password}"/> <property name="defaultEncoding" value="${mail.defaultEncoding}"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">${mail.auth}</prop> <prop key="mail.smtp.timeout">${mail.timeout}</prop> </props> </property> </bean>
4.工具类
import freemarker.cache.FileTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import lombok.Data; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ByteArrayResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.multipart.MultipartFile; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.InputStream; import java.util.Map; @Data @SuppressWarnings("all") public class SendEmail { //发送标题 private String title = null; //邮件内容,可以是html标签 "<h2 style='color=red'>你好</h2>" private String emailContext = null; //默认开启HTML标签 private Boolean flag = true; //附件名 private String fileName = null; //附件路径 new File("E:\\Pixiv PE\\36933.png") private File filePath = null; //发送邮件的人 private String sendName = "dlb@qq.com"; //获取spring中的bean JavaMailSenderImpl public JavaMailSenderImpl getJavaMailSenderImpl() throws MessagingException { AbstractApplicationContext as = new ClassPathXmlApplicationContext("applicationContext.xml"); return as.getBean("javaMailSender",JavaMailSenderImpl.class); } /** * 发送前先准备上面的参数 * @param recipients 收件人 * @throws MessagingException 发送失败 */ public void sendEmailTo(String recipients) throws MessagingException { JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl(); //创建消息对象 MimeMessage mimeMessage =javaMailSender.createMimeMessage(); //返回组装次对象 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8"); helper.setSubject(title);//发送标题 helper.setText(emailContext,flag);//富文本 //抄送 // helper.setCc(""); //密送 //helper.setBcc(""); //回复邮件 //simpleMailMessage.setReplyTo(); //设置发送日期 //simpleMailMessage.setSentDate(); //普通附件.bin文件 //helper.addInline("myLogo", new File("E:\\Pixiv PE\\36933.png")); //附件 if (fileName != null && filePath != null) helper.addAttachment(fileName,filePath); //发送 helper.setTo(recipients);//接收人 helper.setFrom("大萝北"+'<'+sendName+'>');//发送人 javaMailSender.send(mimeMessage); } /** * 以上传的形式发送邮件 * @param multipartFile 要上传的文件 * @param recipients 接收人 * @throws Exception 上传的文件或发送失败 */ public void uploadEmailTo(MultipartFile multipartFile, String recipients) throws Exception { InputStream inputStream = multipartFile.getInputStream(); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer);//读到内存 JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl(); //创建消息对象 MimeMessage mimeMessage =javaMailSender.createMimeMessage(); //返回组装次对象 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8"); helper.setSubject(title);//发送标题 helper.setText(emailContext,flag);//富文本 helper.addAttachment(multipartFile.getOriginalFilename(),new ByteArrayResource(buffer)); helper.setTo(recipients);//接收人 helper.setFrom("坑人网"+'<'+sendName+'>');//发送人 javaMailSender.send(mimeMessage); } /** * 激活邮件用 * @param recipients 接收人 * @throws MessagingException 邮件发送失败 */ public void activateEmailTo(String recipients) throws MessagingException { JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl(); //创建消息对象 MimeMessage mimeMessage =javaMailSender.createMimeMessage(); //返回组装次对象 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8"); helper.setSubject(title);//发送标题 helper.setText(emailContext,flag);//富文本 helper.setTo(recipients);//接收人 helper.setFrom("坑人网"+'<'+sendName+'>');//发送人 javaMailSender.send(mimeMessage); } /** * 获取模板字符串 * @param templateName 模板名字 * @param data 模板中要添加的数据 * @return 模板的字符串 出异常(只会出获取模板异常)有返回空的字符串 */ public String setTemplateString(String templateName, Map map){ Configuration configurer = new Configuration(); try { //Template template = configurer.getTemplate(templateName, "utf-8"); //使用FileTemplateLoader TemplateLoader templateLoader = new FileTemplateLoader(new File("C:\\Code\\Car_ssm\\")); String path = "web\\WEB-INF\\temp\\"+templateName; configurer.setTemplateLoader(templateLoader); Template template = configurer.getTemplate(path, "UTF-8"); //写入 String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); return s; } catch (Exception e){ e.printStackTrace(); } return ""; } }
5.测试服务
@Autowired private JavaMailSenderImpl javaMailSender; @Test public void aa(){ SendEmail sendEmail = new SendEmail(); sendEmail.setTitle("大萝北学java"); sendEmail.setEmailContext("滴答滴答~~咕咕咕"); try { sendEmail.sendEmailTo("279080122@qq.com"); } catch (MessagingException e) { e.printStackTrace(); } } //测试激活邮件 @Test public void bb(){ String s = VerifyCodeUtils.generateVerifyCode(4); System.err.println(s); SendEmail sendEmail = new SendEmail(); sendEmail.setTitle("送你的好东西!你懂得"); sendEmail.setEmailContext("<h3><a href=\"www.gonogo.cn?code="+s+"\">点击我,夜晚带你探索自己"+s+"</a></h3>"); try { sendEmail.sendEmailTo("279080122@qq.com"); } catch (MessagingException e) { e.printStackTrace(); } } //页面模板激活 @Test public void cc() throws Exception { String s = VerifyCodeUtils.generateVerifyCode(4); System.err.println(s); //准备页面模板的内容值 Map<String, String> map = new HashMap<>(); map.put("adminName", "xxxxxxx马宝国"); map.put("activeUrl", "http://www.gonogo.cn/"+s); //装载邮件内容 SendEmail sendEmail = new SendEmail(); String htmlText = sendEmail.setTemplateString("active.ftl", map); sendEmail.setTitle("送你的好东西!你懂得"); sendEmail.setEmailContext(htmlText); try { //发送 sendEmail.sendEmailTo("279080122@qq.com"); } catch (MessagingException e) { e.printStackTrace(); } } @Test public void c() { SimpleMailMessage simpleMailMessage = new SimpleMailMessage();// 创建消息对象 simpleMailMessage.setSubject("你好"); simpleMailMessage.setText("dada"); simpleMailMessage.setTo("279080122@qq.com");//接收人 simpleMailMessage.setFrom("1216180134@qq.com");//发送人 javaMailSender.send(simpleMailMessage); } @Test public void a2() throws MessagingException { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); //组装 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8"); helper.setSubject("主题1");//发送标题 helper.setText("<h2 style='color=red'>你好</h2>",true);// //附件 helper.addAttachment("2.jpg",new File("E:\\Pixiv PE\\36933.png")); helper.setTo("279080122@qq.com");//接收人 helper.setFrom("1216180134@qq.com");//发送人 javaMailSender.send(mimeMessage); } //暂且不用 @Test public void testMail(){ ////测试不用注入bean方式 try { //读取配置文件 InputStream is = Test.class.getClassLoader().getResourceAsStream("util/mail.properties"); Properties properties = new Properties(); properties.load(is); System.out.println(properties.getProperty("mail.smtp.host")); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } //////////////////////////////////////////////////////// AbstractApplicationContext as = new ClassPathXmlApplicationContext("applicationContext.xml"); JavaMailSenderImpl javaMailSender = as.getBean("javaMailSender",JavaMailSenderImpl.class); MimeMessage mailMessage = javaMailSender.createMimeMessage();//创建邮件对象 MimeMessageHelper mimeMessageHelper; Properties prop = new Properties(); String from; try { // 从配置文件读取发件人邮箱地址 prop.load(this.getClass().getResourceAsStream("util/mail.properties")); from = prop.getProperty("mail.smtp.username"); mimeMessageHelper = new MimeMessageHelper(mailMessage,true); mimeMessageHelper.setFrom(from); //发件人地址 mimeMessageHelper.setTo("546279462@qq.com"); //收件人邮箱 mimeMessageHelper.setSubject("邮件主题"); //邮件主题 mimeMessageHelper.setText("<p style='color: red'>邮件内容123345</p>" + "<img src='cid:06'/>",true); //true表示以html方式发送 File file = new File("C:\\Users\\54627\\Pictures\\06.jpg"); //导入其他资源 FileSystemResource resource = new FileSystemResource(file); mimeMessageHelper.addInline("06",resource); //可以指定id,在内容中引用(cid:id) mimeMessageHelper.addAttachment("06.jsp",resource); //附件 javaMailSender.send(mailMessage); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } System.out.println("发送成功"); } @Test public void sendMsg(){ TencentMsg tencentMsg = new TencentMsg(); String userInfo = "amanda"; String msgCode = tencentMsg.getMsgCode(); System.err.println("msgCode = " + msgCode); String msg = tencentMsg.sendLogin(msgCode,"1762136xxxx",userInfo); System.err.println("msg = " + msg); }