发送带图片及附件的邮件
核心代码:
package com.gongyi;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
//发送一封带图片的邮件
public class MailDemo02 {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com");//设置QQ邮箱服务器
prop.setProperty("mail.transport.protocol", "smtp");//邮件发送协议
prop.setProperty("mail.smtp.auth", "true");//需要验证用户名和密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,大厂,其他邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
//QQ才有,其他邮箱就不用
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名,授权码
return new PasswordAuthentication("1072805311@qq.com", "sdfsdf");
}
});
//开启session的debug模式,这样就可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过Session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com", "1072805311@qq.com", "sdfsdf");
//4.创建邮件:写邮件
//注意:需要传递session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("1072805311@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("15518987725@163.com"));
//邮件的标题
message.setSubject("欢迎来到工一说Java");
//===============================================================
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理... DataHandler:数据处理
DataHandler dh = new DataHandler(new FileDataSource("C:\\Users\\Administrator\\Desktop\\学习笔记\\javaweb\\codes\\功能扩展\\mail-java\\src\\1.jpg"));
image.setDataHandler(dh);//在我们的body中放入这个处理的图片数据
image.setContentID("bz.jpg");//给图片设置一个ID,我们在后面可以使用
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:bz.jpg'>的附件", "text/html;charset=UTF-8 ");
//描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(image);
mm.addBodyPart(text);
mm.setSubType("related");
//设置到消息中,保存修改
message.setContent(mm);//把最后编辑好的邮件放到消息当中
message.saveChanges();//保存修改
//===============================================================
//5.发送邮件
ts.sendMessage(message, message.getAllRecipients());
//6.关闭连接
ts.close();
}
}
邮箱注册后发送邮件
1.在empty工程下新建子module
2.普通maven工程(不用模板)
3.添加web支持
4.配置tomcat
核心代码:
pojo/User.java
package com.gongyi.pojo;
import java.io.Serializable;
public class User implements Serializable {
private String username;
private String password;
private String email;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
//方便调试
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
pojo/User1.java
package com.gongyi.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User1 {
private String username;
private String password;
private String email;
}
utils/SendEmail.java
package com.gongyi.utils;
import com.gongyi.pojo.User;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
//网站三秒原则:用户体验
//多线程实现用户体验!(异步处理)
public class SendEmail extends Thread {
//用于给用户发送邮件的邮箱
private String from = "1072805311@qq.com";
//邮箱的用户名
private String username = "1072805311@qq.com";
//邮箱的密码
private String password = "sdfsdf";
//发送邮件的服务器地址
private String host = "smtp.qq.com";
private User user;
public SendEmail(User user) {
this.user = user;
}
//重写run方法的实现,在run方法中发送邮件给指定用户
@Override
public void run() {
try {
Properties prop = new Properties();
prop.setProperty("mail.host", host);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名,授权码
return new PasswordAuthentication("1072805311@qq.com", "sdfsd");
}
});
//开启session的debug模式,这样就可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过Session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect(host, username, password);
//4.创建邮件:写邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));//发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));//收件人
message.setSubject("用户注册邮件");//邮件的标题
String info = "恭喜您注册成功,您的用户名:" + user.getUsername() + ",您的密码:" + user.getPassword() + ",请妥善保管,如有问题,请联系网站客服";
message.setContent(info, "text/html;charset=UTF-8");
message.saveChanges();
//5.发送邮件
ts.sendMessage(message, message.getAllRecipients());
//6.关闭连接
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
servlet/RegisterServlet.java
package com.gongyi.servlet;
import com.gongyi.pojo.User;
import com.gongyi.utils.SendEmail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
//接收用户请求,封装对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username, password, email);
//用户注册成功之后,给用户发送一封邮件
//我们使用线程来专门发送邮件,防止出现耗时,和网站注册人数过多的情况
SendEmail send = new SendEmail(user);
//启动线程,线程启动之后,就会执行run()方法来发送邮件
send.start();
//send.run();//换成run体验注册时用户体验问题
//注册用户
req.setAttribute("message", "注册成功了,我们已经发了一封带了注册信息的电子邮件,请查收!如网络不稳定,可能过会儿才能收到!");
req.getRequestDispatcher("info.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.gongyi.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
邮箱:<input type="text" name="email"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
info.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>xxx网站温馨提示:</h1>
${message}
</body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gongyi</groupId>
<artifactId>WebMail</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
</project>
springboot搭建项目发送邮件【更快,更简单开发,底层做了好多封装,需要了解底层原理】
删除无用目录:
虽然就直接引入了两个包,但是间接依赖的包很多
代码结构:
核心代码:
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
application.properties
server.port=8081
spring.mail.username=1072805311@qq.com
spring.mail.password=sdfsdfdsf
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
DemoApplicationTests.java
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class DemoApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
//发送邮件
//收件人
//内容
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("工一说Java");
message.setText("Hello World");
message.setFrom("1072805311@qq.com");
message.setTo("1072805311@qq.com");
mailSender.send(message);
}
@Test
void test2() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("工一说Java");
helper.setText("<h1>Hello,World</h1>", true);
//附件
helper.addAttachment("1.jpg", new File("C:\\Users\\Administrator\\Desktop\\学习笔记\\javaweb\\codes\\demo\\src\\main\\resources\\1.jpg"));
helper.addAttachment("2.jpg", new File("C:\\Users\\Administrator\\Desktop\\学习笔记\\javaweb\\codes\\demo\\src\\main\\resources\\2.jpg"));
helper.addAttachment("3.jpg", new File("C:\\Users\\Administrator\\Desktop\\学习笔记\\javaweb\\codes\\demo\\src\\main\\resources\\3.jpg"));
helper.addAttachment("4.jpg", new File("C:\\Users\\Administrator\\Desktop\\学习笔记\\javaweb\\codes\\demo\\src\\main\\resources\\4.jpg"));
helper.setFrom("1072805311@qq.com");
helper.setTo("1072805311@qq.com");
mailSender.send(mimeMessage);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
效果图:
彩蛋
1.发送附件,fileName设置为中文乱码
老代码:
attach.setFileName("附件.jpg");//附件和正文图片的区别是需要设置fileName
新代码:
attach.setFileName(MimeUtility.encodeText("附件.jpg"));//附件和正文图片的区别是需要设置fileName
效果图:
2.maven工程快速导包
3.脚手架
是一个基本框架,是成型的,可以不断添加小功能【扩展】
4.lombok
5.普通maven工程不通过修改pom文件也可以实现导包效果
6.web服务发布后将依赖包放入到lib下
7…start()是多线程方法,.run()是普通方法
8.注册信息时发送邮件遇到问题
1)java.lang.ClassNotFoundException: javax.mail.Authenticator
发现target目录下无web资源及相关依赖包
无 WEB-INF是因为,pom文件中的无【对比了正常的web项目看出来的】
<packaging>war</packaging>
加上就行,默认是jar包
启动后,首页404,看输出的文件也无index.jsp
修复这里就行
改成如下就行:【是因为这不是一个标准的web工程,是普通maven工程添加了web支持】
2)邮箱收到中文乱码:
debug发现前端传过来就乱码了:
解决:
在 RegisterServlet.java中加入如下代码:
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
9.阿里特别注重底层
看《深入JVM》
10.springboot的spring-boot-starter-mail底层还是javamail