目录
1. 导包
导入 mail-1.4.7.jar 和 activation-1.1.1.jar
2.QQ邮箱开启POP3/SMTP服务
- 进入QQ邮箱–设置–账户
3. 普通版邮件发送
3.1 文本邮件发送
package com.lrm;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**发送一封简单邮件:没有附件和图片,纯文本邮件
*要发送邮件需要获得协议和支持。开启服务POP3/SMTP服务
*授权码(QQ邮箱):授权码
**/
public class MailTest01 {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
//设置邮件服务器
prop.setProperty("mail.host","smtp.qq.com");
//设置邮件发送协议
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
public PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("邮件用户名","授权码");
}
});
//开启session的debug模式,这样就可以查看到程序发送email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","邮箱用户名","授权码");
//4、创建邮件
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("发件人邮箱地址"));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱地址"));
//邮件的标题
message.setSubject("只包含文本的简单邮件");
//邮件的文本内容
message.setContent("<h1 style='color: red'>你好!</h1>","text/html;charset=utf-8");
//5、发送邮件
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
}
3.2 附件邮件发送
package com.lrm;
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;
/**发送一封复杂邮件:有附件和图片
*要发送邮件需要获得协议和支持。开启服务POP3/SMTP服务
*授权码(QQ邮箱):授权码
**/
public class MailTest02 {
public static void main(String[] args) throws Exception{
···与文本邮件一致···
//邮件的标题
message.setSubject("包含图片和附件的复杂邮件");
//邮件的文本内容
//=============================================
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要进行数据处理
DataHandler dh = new DataHandler(new FileDataSource("D:\\编程\\IDEA_workspace\\功能拓展\\mail-java\\src\\1.jpg"));
//在Body中放入这个处理的图片数据
image.setDataHandler(dh);
//给图片设置一个CID,在后面使用
image.setContentID("biz.jpg");
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封带有图片和附件的邮件<img src='cid:biz.jpg'>","text/html;charset=utf-8");
//准备附件数据
MimeBodyPart file = new MimeBodyPart();
file.setDataHandler(new DataHandler(new FileDataSource("D:\\编程\\IDEA_workspace\\功能拓展\\mail-java\\src\\1.txt")));
file.setFileName("1.txt");
//描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
//related:图片 mixed:附件
mm.setSubType("related");
//将图片和文本设为主体
MimeBodyPart contextText = new MimeBodyPart();
contextText.setContent(mm);
//将附件拼接进主体
MimeMultipart allFile = new MimeMultipart();
allFile.addBodyPart(file);
allFile.addBodyPart(contextText);
allFile.setSubType("mixed");
//设置到消息中,保存修改
message.setContent(allFile);
message.saveChanges();
//=============================================
//5、发送邮件
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
}
4. Web版邮件发送
4.1 前端代码编写
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>
</head>
<body>
${message}
</body>
</html>
4.2 后端代码编写
User.java
package com.lrm.pojo;
import java.io.Serializable;
public class User implements Serializable {
private String username;
private String password;
private String email;
···有参、无参、get/set、toString重写···
工具类Sendmail
package com.lrm.utils;
import com.lrm.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;
/**
* 网站3秒原则:用户体验
* 多线程实现用户体验,异步处理
*/
public class Sendmail extends Thread{
//用于给用户发送邮件的邮箱
private String from = "发件人邮箱";
//邮箱的用户名
private String username = "邮箱用户名";
//邮箱的密码(授权码)
private String password = "授权码";
//发送邮件的服务器地址
private String host = "smtp.qq.com";
private User user;
public Sendmail(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);
//使用JavaMail发送邮件的5个步骤
//1、创建定义整个应用程序所需要的环境信息的session对象
//QQ才有,其他邮箱不要
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication(username,password);
}
});
//开启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());
ts.close();
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
RegisterServlet.java
package com.lrm.servlet;
import com.lrm.pojo.User;
import com.lrm.utils.Sendmail;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name="RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//接收用户请求
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
User user = new User(username, password, email);
//用户注册成功后,给用户发一封邮件
//使用专门的线程来发邮件,防止出现耗时或网站注册人数过多的情况
Sendmail send = new Sendmail(user);
//启动线程,线程启动后会执行run方法来发送邮件
send.start();
//注册用户
request.setAttribute("message","注册成功,我们已经发了一封电子信息到您的邮箱!");
request.getRequestDispatcher("info.jsp").forward(request,response);
}catch (Exception e){
e.printStackTrace();
request.setAttribute("message","注册失败!");
request.getRequestDispatcher("info.jsp").forward(request,response);
}
}
}
4.3 web.xml配置
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.lrm.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
5. Spring Boot版邮件发送
测试类(文本、附件邮件发送):
package com.example.springbootmail;
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 SpringBootMailApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
//文本邮件发送
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("主题");
message.setText("Hello");
message.setFrom("发件人邮箱");
message.setTo("收件人邮箱");
mailSender.send(message);
}
//附件邮件发送
@Test
public void test() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("主题");
helper.setText("<h1>Hello</h1>",true);
//附件
helper.addAttachment("application.properties",new File("D:\\编程\\IDEA_workspace\\功能拓展\\SpringBootMail\\src\\main\\resources\\application.properties"));
helper.setFrom("发件人邮箱");
helper.setTo("收件人邮箱");
mailSender.send(mimeMessage);
}
}
配置类 application.properties:
spring.mail.username=邮箱用户名
spring.mail.password=授权码
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true