JavaWeb邮件发送功能
发送邮件的简单理解
每一个邮箱都有专门的邮箱服务器
接收用POP3协议,发送用SMTP协议
概述
下载小知识:有时候jar下载不下来 可以如下操作:
打开浏览器的F12 ,选择network
,再点击要下载文件,这时候会发送一个request请求
可以直接复制该网址,如果下载不了,换成HTTP而不是用HTTPS
Jar包的应用概述
代码 实现纯文本邮件发送
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class SendEamil {
public static void main(String[] args) throws MessagingException, GeneralSecurityException {
//创建一个配置文件并保存
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");
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);
//创建一个session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("619046217@qq.com","16位授权码");
}
});
//开启debug模式
session.setDebug(true);
//获取连接对象
Transport transport = session.getTransport();
//连接服务器
transport.connect("smtp.qq.com","619046217@qq.com","16位授权码");
//创建邮件对象
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发送人
mimeMessage.setFrom(new InternetAddress("619046217@qq.com"));
//邮件接收人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("875203654@qq.com"));
//邮件标题
mimeMessage.setSubject("Hello Mail");
//邮件内容
mimeMessage.setContent("我的想法是把代码放进一个循环里","text/html;charset=UTF-8");
//发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//关闭连接
transport.close();
}
}
Java实现文本图片附件复杂的邮件发送
MIME(多用途互联网邮件扩展类型)
MimeBodyPart类
javax.mail.internet.MimeBodyPart类 表示的是一个MIME消息,它和MimeMessage类一样都是从Part接口继承过来。
MimeMultipart类
javax.mail.internet.MimeMultipart是抽象类 Multipart的实现子类,它用来组合多个MIME消息。一个MimeMultipart对象可以包含多个代表MIME消息的MimeBodyPart对象
import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class SendComplexEmail {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
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);
//1、创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//传入发件人的姓名和授权码
return new PasswordAuthentication("619046217@qq.com","16位授权码");
}
});
//2、通过session获取transport对象
Transport transport = session.getTransport();
//3、通过transport对象邮箱用户名和授权码连接邮箱服务器
transport.connect("smtp.qq.com","619046217@qq.com","16位授权码");
//4、创建邮件,传入session对象
MimeMessage mimeMessage = complexEmail(session);
//5、发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//6、关闭连接
transport.close();
}
public static MimeMessage complexEmail(Session session) throws MessagingException {
//消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
//发件人
mimeMessage.setFrom(new InternetAddress("619046217@qq.com"));
//收件人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("619046217@qq.com"));
//邮件标题
mimeMessage.setSubject("带图片和附件的邮件");
//邮件内容
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler handler = new DataHandler(new FileDataSource("E:\\IdeaProjects\\WebEmail\\resources\\测试图片.png"));
image.setDataHandler(handler);
image.setContentID("test.png"); //设置图片id
//准备文本
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一段文本<img src='cid:test.png'>","text/html;charset=utf-8");
//附件
MimeBodyPart appendix = new MimeBodyPart();
appendix.setDataHandler(new DataHandler(new FileDataSource("E:\\IdeaProjects\\WebEmail\\resources\\测试文件.txt")));
appendix.setFileName("test.txt");
//拼装邮件正文
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(image);
mimeMultipart.addBodyPart(text);
mimeMultipart.setSubType("related");//文本和图片内嵌成功
//将拼装好的正文内容设置为主体
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(mimeMultipart);
//拼接附件
MimeMultipart allFile = new MimeMultipart();
allFile.addBodyPart(appendix);//附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed
//放到Message消息中
mimeMessage.setContent(allFile);
mimeMessage.saveChanges();//保存修改
return mimeMessage;
}
}
JavaWeb发送邮件(网站注册成功发送提示邮件)
1.User 类
public class User {
private String name;
private String password;
private String mail;
public User() {
}
public User(String name, String password, String mail) {
this.name = name;
this.password = password;
this.mail = mail;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", mail='" + mail + '\'' +
'}';
}
}
2.servlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Servlet extends javax.servlet.http.HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
//处理前端请求
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
//将信息封装进user对象
User user = new User(username, password, email);
SendMail sendMail = new SendMail(user);
sendMail.start(); //开启线程
request.setAttribute("msg","发送成功");
try {
request.getRequestDispatcher("msg.jsp").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.SendMail
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.util.Properties;
public class SendMail extends Thread {
//发件人信息
private String From = "xxx@qq.com";
//发件人邮箱
private String recipient = "xxx@qq.com";
//邮箱密码
private String password = "16位授权码";
//邮件发送的服务器
private String host = "smtp.qq.com";
//收件人信息
private User user;
public SendMail(User user){
this.user = user;
}
@Override
public void run() {
try {
Properties properties = new Properties();
properties.setProperty("mail.host","smtp.qq.com");
properties.setProperty("mail.transport.protocol","smtp");
properties.setProperty("mail.smtp.auth","true");
//QQ存在一个特性设置SSL加密
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//创建一个session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(recipient,password);
}
});
//开启debug模式
session.setDebug(true);
//获取连接对象
Transport transport = null;
try {
transport = session.getTransport();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
//连接服务器
transport.connect(host,From,password);
//创建一个邮件发送对象
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发送人
mimeMessage.setFrom(new InternetAddress(recipient));
//邮件接收人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getMail()));
//邮件标题
mimeMessage.setSubject("网站注册成功");
//邮件内容
mimeMessage.setContent("网站注册成功,密码为"+user.getPassword()+",请妥善保管密码","text/html;charset=UTF-8");
//发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
transport.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
4.register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/a.do" method="post">
<p>用户名:<input type="text" name="username" required></p>
<p>密码:<input type="password" name="password" required></p>
<p>邮箱:<input type="email" name="email" required></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
5.msg.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>