发送的邮件有三种:
1.纯文本的邮件(最简单)
2.正文内容文本加图片(较为复杂)
3.正文有图片和文本,另外有附件内容
事先需要了解的知识点:
邮件发送的整体流程图
发件人张三是网易的邮箱,收件人李四是QQ邮箱;如果张三给李四发一封邮件,那么这个邮件数据首先会通过各种基站发送到网易的服务器上,然后再由网易的服务器统一发送给QQ邮箱的服务器,中间会经过若干基站,最后统一由QQ邮箱服务器接收,如果李四登录了自己的邮箱那么会从QQ邮箱服务器中发现一个来自张三的邮件。这样就实现了邮件发送。
邮件发送和接收过程中涉及的协议:SMTP和POP3
在服务器中,当接收到邮件时,会通过SMTP协议地址获取收到的邮件,再放入对应的用户地址中,而发送邮件是先放入SMTP协议的内存空间,发送到对应的服务器中。
SMTP服务器地址:一般是smtp.XXX.com,例如163的服务器地址是smtp.163.com;QQ的服务器地址是smtp.qq.com
电子邮箱(Email)的获得需要在邮件服务器上申请。
准备
首先要准备好JavaMail API和Java Activation Framework。
发邮件的四个步骤:
1、准备包含邮件服务器的网络连接信息的Session对象
2、创建代表邮件信息内容的Message对象
3、创建Transport对象,连接服务器,发送Message,关闭连接
中间涉及的四个核心类
样例的项目结构
纯文本的邮件
import com.sun.mail.util.MailSSLSocketFactory;
import com.sun.source.doctree.TextTree;
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 MailDemo01 {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host", "smtp.qq.com"); //设置QQ邮件服务器
properties.setProperty("mail.transport.protocol", "smtp"); //设置邮件发送协议
properties.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码
//QQ邮箱需要设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//用Java发送邮件
//1.创建定义整个应用程序所需要的环境信息的Session对象
//QQ才有
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发送人邮件用户名,授权码
return new PasswordAuthentication("发件人邮箱地址", "授权码");
}
});
//开启Session的Debug模式,可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
transport.connect("smtp.qq.com", "发件人邮箱地址", "授权码");
//4.创建邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//设置邮件发件人
message.setFrom(new InternetAddress("发件人邮箱地址"));
//设置邮件收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱地址"));
//设置邮件主题
message.setSubject("邮件的主题");
message.setContent("<h1 style='color: red'>Hello</h1>", "text/html;charset=UTF-8");
//5.发送邮件
transport.sendMessage(message, message.getAllRecipients());
//6.关闭连接
transport.close();
}
}
正文内容文本加图片
package com.fj;
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 properties = new Properties();
properties.setProperty("mail.host", "smtp.qq.com"); //设置QQ邮件服务器
properties.setProperty("mail.transport.protocol", "smtp"); //设置邮件发送协议
properties.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码
//QQ邮箱需要设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//用Java发送邮件
//1.创建定义整个应用程序所需要的环境信息的Session对象
//QQ才有
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发送人邮件用户名,授权码
return new PasswordAuthentication("发件人邮箱地址", "授权码");
}
});
//开启Session的Debug模式,可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
transport.connect("smtp.qq.com", "发件人邮箱地址", "授权码");
//4.创建邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//设置邮件发件人
message.setFrom(new InternetAddress("发件人邮箱地址"));
//设置邮件收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱地址"));
//设置邮件主题
message.setSubject("邮件的主题");
//图片数据准备
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("图片文件路径"));
image.setDataHandler(dh); //在Body中放入图片数据处理
image.setContentID("1.png");//给图片设置一个ID,便于调用
//设置邮件正文内容
MimeBodyPart text = new MimeBodyPart();
//cid就是ContentID的缩写,即这里调用的就是之前给图片设置的ID
text.setContent("<h1 style='color: red'>Hello</h1><img src='cid:1.png'>", "text/html;charset=UTF-8");
//描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(image);
mm.addBodyPart(text);
mm.setSubType("related");
//设置到消息中,保存修改
message.setContent(mm);//将编辑好的数据关系放入message中
message.saveChanges();
//5.发送邮件
transport.sendMessage(message, message.getAllRecipients());
//6.关闭连接
transport.close();
}
}
正文有图片和文本,另外有附件内容
package com.fj;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
//发送带有附件的邮件,正文中有图片
public class MailDemo03 {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.host", "smtp.qq.com"); //设置QQ邮件服务器
properties.setProperty("mail.transport.protocol", "smtp"); //设置邮件发送协议
properties.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码
//QQ邮箱需要设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//用Java发送邮件
//1.创建定义整个应用程序所需要的环境信息的Session对象
//QQ才有
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发送人邮件用户名,授权码
return new PasswordAuthentication("发件人邮箱地址", "授权码");
}
});
//开启Session的Debug模式,可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
transport.connect("smtp.qq.com", "发件人邮箱地址", "授权码");
//4.创建邮件
MimeMessage mimeMessage = imageMail(session);
//5.发送邮件
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
//6.关闭连接
transport.close();
}
public static MimeMessage imageMail(Session session) throws MessagingException {
//消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发件人
mimeMessage.setFrom(new InternetAddress("发件人邮箱地址"));
//邮件接收人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱地址"));
//邮件主题
mimeMessage.setSubject("邮件的主题");
/*
编写邮件内容
1.图片
2.附件
3.文本
*/
//图片
MimeBodyPart image = new MimeBodyPart();
image.setDataHandler(new DataHandler(new FileDataSource("图片文件路径")));
image.setContentID("1.png");//给图片设置一个ID,便于调用
//文本
MimeBodyPart text = new MimeBodyPart();
//cid就是ContentID的缩写,即这里调用的就是之前给图片设置的ID
text.setContent("<h1 style='color: red'>Hello</h1><img src='cid:1.png'>", "text/html;charset=UTF-8");
//附件
MimeBodyPart prop = new MimeBodyPart();
prop.setDataHandler(new DataHandler(new FileDataSource("附件文件路径")));
prop.setFileName("data.properties"); //附件设置名字
MimeBodyPart txt = new MimeBodyPart();
txt.setDataHandler(new DataHandler(new FileDataSource("附件文件路径")));
txt.setFileName(""); //附件设置名字
//拼装文件正文内容
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(image);
multipart1.addBodyPart(text);
multipart1.setSubType("related");
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
//拼接附件
MimeMultipart allFile = new MimeMultipart();
allFile.addBodyPart(contentText);
allFile.addBodyPart(prop);
allFile.addBodyPart(txt);
allFile.setSubType("mixed");//正文和附件拼接,用mixed
//放到Message消息中,保存修改
mimeMessage.setContent(allFile);//将编辑好的数据关系放入message中
mimeMessage.saveChanges();
return mimeMessage;
}
}
在网站中实现发送邮件
maven项目结构
User.java类
package com.fj.pojo;
import java.io.Serializable;
public class User implements Serializable {
private String username;
private String password;
private String email;
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;
}
}
RegisterServlet.java类
package com.fj.servlet;
import com.fj.pojo.User;
import com.fj.utils.Sendmail;
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 {
try {
//接收用户请求,封装成对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username, password, email);
System.out.println(username);
System.out.println(password);
System.out.println(email);
//用户注册成功后,给用户发送一封邮件
//使用多线程发送邮件,防止出现耗时,和网站注册人数过多的情况
Sendmail sendmail = new Sendmail(user);
//启动线程
sendmail.start();
//注册用户
req.setAttribute("message", "注册成功,邮件已发送至您的邮箱!");
req.getRequestDispatcher("info.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Sendmail.java类
package com.fj.utils;
import com.fj.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 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 properties = new Properties();
properties.setProperty("mail.host", host); //设置QQ邮件服务器
properties.setProperty("mail.transport.protocol", "smtp"); //设置邮件发送协议
properties.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码
//QQ邮箱需要设置SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//用Java发送邮件
//1.创建定义整个应用程序所需要的环境信息的Session对象
//QQ才有
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
//发送人邮件用户名,授权码
return new PasswordAuthentication(username, password);
}
});
//开启Session的Debug模式,可以查看程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport transport = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
transport.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();
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
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>温馨提示</h1>
${message}
</body>
</html>
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"
metadata-complete="true">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.fj.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
</web-app>