包含图片
package com.dyq;
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.security.GeneralSecurityException;
import java.util.Properties;
/**
* 发送一封简单的邮件
*/
public class MailDemo01 {
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.socketFactory", sf);
//使用JavaMail发送邮箱的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
//QQ才有,其他邮箱不用
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("504561395@qq.com", "xkmwtqwlqsbgbgfb");
}
});
// 开启Session的debug模式:可以看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com", "504561395@qq.com", "xkmwtqwlqsbgbgfb");
//4.创建邮箱:写邮件
//注意需要传递Session
Message message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("504561395@qq.com"));
//指明收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("504561395@qq.com"));
//设置邮箱标题
message.setSubject("秃头小分队Demo");
//邮件的文本内容
//========================================================================
//准备图片数据
MimeBodyPart image=new MimeBodyPart();
//图片需要经过数据化的处理 DataHandler数据处理
DataHandler dh=new DataHandler(new FileDataSource("C:\\Users\\DYQ\\IdeaProjects\\javaweb-mail\\src\\0.png"));
//在我们的的body中放入这个处理的图片数据
image.setDataHandler(dh);
//给这个图片设置一个ID名字,我们在后面可以使用 (76行cid
image.setContentID("bz.jpg");
//准备正文的数据
MimeBodyPart text=new MimeBodyPart();
// cid:setContentID
text.setContent("这是一张正文<img src='cid:bz.jpg'>","text/html;charset=UTF-8");
//描述数据关系
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");//mm.setSubType("mixed");
//设置到消息中,保存修改
message.setContent(mm); //把最后编辑好的邮件放到消息当中
message.saveChanges(); //保存修改
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭
ts.close();
}
}
包含附件
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 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对象
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("1192XXXX@qq.com","授权码");
}
});
//开启session的debug模式,这样可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts=session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","1192XXXX@qq.com","授权码");
//4.创建邮件:写文件
//注意需要传递session
MimeMessage message=new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("1192XXXX@qq.com"));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("1192XXXX@qq.com"));
//邮件标题
message.setSubject("java发出");
//邮件的文本内容
//=================================准备图片数据
MimeBodyPart image=new MimeBodyPart();
//图片需要经过数据化的处理
DataHandler dh=new DataHandler(new FileDataSource("D:\\Bert\\1594126632(1).jpg"));
//在part中放入这个处理过图片的数据
image.setDataHandler(dh);
//给这个part设置一个ID名字
image.setContentID("bz.jpg");
//=================================准备正文数据
MimeBodyPart text=new MimeBodyPart();
text.setContent("这是一张正文<img src='cid:bz.jpg'>","text/html;charset=UTF-8");
//=================================准备附件数据
MimeBodyPart body1= new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("D:\\Bert\\cmd.txt")));
body1.setFileName("1.txt");
//描述数据关系
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(body1);
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("mixed");
//设置到消息中,保存修改
message.setContent(mm);
message.saveChanges();
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}
}
实战:注册通知邮件
index.JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="text" name="pwd"><br>
邮箱:<input type="text" name="email"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
实体类
package com.dyq.pojo;
public class User {
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;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", 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;
}
}
绑定路径
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>cn.csn.MailDemo01.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
servlet
package com.dyq.servlet;
import com.dyq.pojo.User;
import com.dyq.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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接受用户请求,封装成对象
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);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
发送邮件核心类
package com.dyq.utils;
import com.dyq.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="504561395@qq.com";
//邮箱的用户名
private String username="504561395.qq.com";
//邮箱的密码
private String password="xkmwtqwlqsbgbgfb";
//发送邮箱的地址
private String host = "smtp.qq.com";
private User user;
public Sendmail(User user){
this.user=user;
}
@Override
public void run() {
try {
Properties prop = new Properties();
prop.setProperty("mail.host", host);///设置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对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("504561395@qq.com", "xkmwtqwlqsbgbgfb");
}
});
//开启session的debug模式,这样可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect(host, username, "xkmwtqwlqsbgbgfb");
//4.创建邮件:写文件
//注意需要传递session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(from));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
//邮件标题
message.setSubject("注册通知");
//邮件的文本内容
message.setContent("恭喜你(" + user.getUsername() + ")成功注册!" + "密码:" + user.getPassword()
, "text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message, message.getAllRecipients());
//6.关闭连接
ts.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
这里引入多线程的目的是为了提高用户的体验,防止因发送文件时间过长,导致前端响应过久,因此这里采用异步响应。