邮件发送原理
邮件发送
一、邮件发送需要的jar包?
mail(主包)
activation(依赖包)
文本发送原理
附件发送原理
二、图片、文本、附件一起发送
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 demo {
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 sslSocketFactory=new MailSSLSocketFactory();
sslSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sslSocketFactory);
//使用javaMail发送邮件的五个步骤
//1.创建定义整个应用程序所需的环境信息的session对象
//只有qq才有的过程,其他邮箱没有
Session session=Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//发送邮件用户名,授权码
return new PasswordAuthentication("你die","eqryfrbmvgvrfaeh");
}
});
//开启session的debug模式,这样就可以查看程序发送的email的运行状态
session.setDebug(true);
//2.通过session对象得到transport
Transport transport=session.getTransport();
//3.使用邮箱的用户名和授权码连上邮箱服务器
transport.connect("smtp.qq.com","2020637917@qq.com","eqryfrbmvgvrfaeh");
//4.创建邮件
//需要传递session
MimeMessage message=new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("2020637917@qq.com"));
//指明邮件的收件人,
message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("收件人邮箱")});
//邮件的标题
message.setSubject("欢迎");
//================================================================
//准备图片数据
MimeBodyPart image=new MimeBodyPart();
//图片需要经过数据处理 datahandler :数据处理
DataHandler dh=new DataHandler(new FileDataSource("图片地址"));
image.setDataHandler(dh);
image.setContentID("lye.jpg");//给图片设置一个id
//准备正文数据 cid:
MimeBodyPart text=new MimeBodyPart();
text.setContent("贺江傻逼,<img src='cid:lye.jpg'","text/html;charset=UTF-8");
//=================================准备附件数据
MimeBodyPart body1= new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("附件地址")));
body1.setFileName("db.txt");
//描述数据关系
MimeMultipart mm=new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
//设置到信息中,保存修改
MimeMultipart Mimesum=new MimeMultipart();
Mimesum.addBodyPart(body1);
Mimesum.addBodyPart(text);
Mimesum.addBodyPart(image);
Mimesum.setSubType("mixed");
message.setContent(Mimesum);
message.saveChanges();//保存修改
//================================================================
//邮件的内容
// message.setContent("hello,。","text/html;charset=UTF-8");
//5.发送邮件
transport.sendMessage(message,message.getAllRecipients());
//6.关闭连接
transport.close();
System.out.println("发送成功......");
}
}
三、操作步骤(qq有所不同)
1.创建定义整个应用程序所需要的环境信息的session对象
2.通过session得到transport对象
3.使用邮箱的用户名和授权码连上邮件服务器
4.创建邮件:写文件
5.发送邮件
实例操作,基于qq服务器
smtp.qq.com
QQ特有:
//关于qq邮箱,还要设置SSL加密,加上以下代码即可
MailSSLSocketFactory sslSocketFactory=new MailSSLSocketFactory();
sslSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sslSocketFactory);
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.xiang.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
</web-app>
工具类:Sendmail
import com.sun.mail.util.MailSSLSocketFactory;
import com.xiang.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="2020637917@qq.com";
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(from,"eqryfrbmvgvrfaeh");
}
});
//开启session的debug模式,这样可以查看到程序发送Email的运行状态
session.setDebug(true);
//2.通过session得到transport对象
Transport ts=session.getTransport();
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect(host,from,"eqryfrbmvgvrfaeh");
//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);
}
}
}
Servlet代码块
import com.xiang.pojo.User;
import com.xiang.util.Sendmail;
import java.io.IOException;
//脚手架
public class RegisterServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//接收用户请求,封装成对象
String username=request.getParameter("username");
String password=request.getParameter("pwd");
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(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doPost(request,response);
}
}
实体类User
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 + '\'' +
'}';
}
}