一、邮件收发
要在网络上实现邮件功能,必须要有专门的邮件服务器。
这些邮件服务器类似于现实生活中的邮局,它主要负责接受用户投递过来的邮件,并在邮件投递到邮件接收者的电子邮箱中。
传输协议
1.SMTP协议
发送邮件:我们通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。
2.POP3协议
接收邮件:我们通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。
二、Java发送邮件
使用代码完成邮件的发送,在实际生活中应用非常广泛,比如注册需要发送邮件进行账号激活。
准备工作
两个jar包
纯文本邮件
1.导包建立依赖
2.QQ邮箱中获取对应的权限
QQ邮箱需要验证,我们需要获取他对应的权限:
QQ邮箱——设置——账号——生成16位授权码
3.测试代码
package org.westos.demo;
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 SendEmail {
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);
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("827356@qq.coom","aukyzunwgbhubcef");
}
});
session.setDebug(true);//开启Session的debug模式,这样就可以看到程序发送Email的运行状态
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","827356@qq.com","aukyzunwgbhubcef");
//4.创建邮件
MimeMessage message = new MimeMessage(session);//创建邮件对象
message.setFrom(new InternetAddress("827356@qq.com"));//指明邮件的发件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress("m1785314@163.com"));//指明邮件的收件人
message.setSubject("简单的文本文件");//邮件的标题
message.setContent("你好啊!","text/html;charset=utf-8");//邮件的文本内容
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
ts.close();
}
}
带图片和附件的邮件
1.认识两个类一个名词
MIME:多用途互联网邮件扩展类型
MimeBodyPart类:javax.mail.internet.MimeBodyPart类表示的是一个MIME消息,它和MimeMessage类一样都是从Part接口继承过来。
MimeMultipart类:javax.mail.internet.MimeMultipart是抽象类Multipart的实现类,它用来组合多个MIME消息。一个MimeMultipart对象可以包含多个代表MIME消息的MimeBodyPart对象。
2.测试代码
package org.westos.demo;
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 SendImageEmail {
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);
//使用javaMail发送邮件的五个步骤
//1.创建定义整个应用程序所需的环境信息Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名,授权码
return new PasswordAuthentication("827356@qq.com", "pyxowwaorhecbdhi");
}
});
session.setDebug(true);//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.通过邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com", "827356@qq.com", "pyxowwaorhecbdhi");
//4.创建邮件
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("827356@qq.com"));//发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress("m1785314@163.com"));//收件人
message.setSubject("带图片的邮件");//邮件标题
//准备邮件数据
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("src/resources/1.png"));
image.setDataHandler(dh);
image.setContentID("1.png");
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:1.png'>的邮件", "text/html;charset=utf-8");
//描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
//设置到消息中,保存更改
message.setContent(mm);
message.saveChanges();
//5.发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
带图片和附件的复杂邮件发送
package org.westos.demo;
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 SendFileMail {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
//创建一个配置文件保存并读取信息
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);
//1.创建一个Session会话对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("827356@qq.com", "pyxowwaorhecbdhi");
}
});
session.setDebug(true);//开启session的debug模式,查看所有的过程
//2.获取连接对象,通过session对象获得transport
Transport ts = session.getTransport();
//3.连接服务器
ts.connect("smtp.qq.com", "827356@qq.com", "pyxowwaorhecbdhi");
//4.创建邮件
MimeMessage mimeMessage = imageMail(session);
//5.发送邮件
ts.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
//6.关闭连接
ts.close();
}
public static MimeMessage imageMail(Session session) throws MessagingException {
//消息的固定信息
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("827356@qq.com"));//发件人
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("m1785314@163.com"));//收件人
mimeMessage.setSubject("给你给你,就给你了");//邮件主题
//编写邮件内容(图片、文本、附件)
//图片
MimeBodyPart body1 = new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("src/resources/1.png")));
body1.setContentID("1.png");//图片设置ID
//文本
MimeBodyPart body2 = new MimeBodyPart();
body2.setContent("请注意我不是广告<img src='cid:1.png'>", "text/html;charset=utf-8");
//附件
MimeBodyPart body3 = new MimeBodyPart();
body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/普通的Java项目用IDEA打jar包.docx")));
body3.setFileName("properties");//附件设置名字
MimeBodyPart body4 = new MimeBodyPart();
body4.setDataHandler(new DataHandler(new FileDataSource("src/resources/1.txt")));
body4.setFileName("1.txt");
//拼接邮件正文内容
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(body1);
multipart1.addBodyPart(body2);
multipart1.setSubType("related");//文本和图片内嵌成功
//将拼接好的正文内容设置为主体
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
//拼接附件
MimeMultipart allFile = new MimeMultipart();
allFile.addBodyPart(body3);//附件
allFile.addBodyPart(body4);//附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed");//正文和附件都存在邮件中,所有类型设置为mixed
mimeMessage.setContent(allFile);//放到Message消息中
mimeMessage.saveChanges();//保存修改
return mimeMessage;
}
}
JavaWeb发送邮件
现在很多网站都提供用户注册功能,通常我们注册成功之后就会收到一封来自注册网站的邮件。邮件里面可能包含了我们注册的用户名和密码以及一个激活账户的超链接信息。
现在我们实现一个功能,用户注册成功后,就将用户的注册信息以Email的形式发送到用户的注册邮箱中,实现发送邮件功能。
1.新建一个javaWeb项目,配置tomcat,添加jar包
2.编写对应的实体类
package org.westos.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 + '\'' +
'}';
}
}
3.前端注册页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Register.do">
用户名:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
邮箱:<input type="text" name="email"/><br>
<input type="submit" value="注册">
</form>
</body>
</html>
4.邮件发送的工具类
package org.westos.utils;
import com.sun.mail.util.MailSSLSocketFactory;
import org.westos.pojo.User;
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="827356@qq.com";//用于给用户发送邮件的邮箱
private String username="827356@qq.com";//邮箱的用户名
private String password="pyxowwaorhecbdhi";//邮箱的密码,授权码
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);
//1.定义整个应用程序所需的环境信息的Session对象
Session session=Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发件人的用户名、授权码
return new PasswordAuthentication(username,password);
}
});
session.setDebug(true);//开启session的debug模式,这样就可以看到程序发送email的运行状态
//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");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.servlet处理类
package org.westos.servlet;
import org.westos.pojo.User;
import org.westos.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",value = "/Register.do")
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 {
this.doPost(request, response);
}
}
5.发送成功或失败的反馈页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${message}
</body>
</html>