使用IDEA实现邮件发送
2、邮件发送
原理:
编写程序的四个核心类及程序流程:
需要的jar包:
简单QQ邮件(无附件)发送代码实现
//发送一封简单的邮件
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.ssl.socketFactory",sf);
//使用JavaMail发送邮件的5个步骤
//1、创建定义整个应用程序所需的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("406623380@qq.com","****************");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","406623380@qq.com","****************");
//4、创建邮件:写邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人 24736743
message.setFrom(new InternetAddress("406623380@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("m15208881@163.com"));
//邮件的标题
message.setSubject("只包含文本的简单邮件");
//邮件的文本内容
message.setContent("<h1 style='color:red'>你好啊!</h1>","text/html;charset=UTF-8");
//5、发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6、关闭连接
ts.close();
}
}
复杂QQ邮件(由附件)发送的实现
MIME(多用途互联网邮件扩展类型)
MineBodyPart类
MineMultipart类
代码实现:
public class MailDemo02 {
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() {
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("406623380@qq.com","****************");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","406623380@qq.com","****************");
//4、创建邮件:写邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人 24736743
message.setFrom(new InternetAddress("406623380@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress("406623380@qq.com"));
//邮件的标题
message.setSubject("复杂的邮件");
//===================================================================================
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理... DataHandler:数据处理
DataHandler dh = new DataHandler(new FileDataSource("C:\\Users\\wangyudong\\Desktop\\1.png"));
image.setDataHandler(dh);//在我们的body中放入这个处理的图片数据
image.setContentID("bz.jpg");//给图片设置一个ID,我们在后面可以使用
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
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");
//设置到消息中,保存修改
message.setContent(mm);//把最后编辑好的邮件放到消息当中
message.saveChanges();//保存修改!
//=================================================================
//5、发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6、关闭连接
ts.close();
}
}
====================================================================================
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() {
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("406623380@qq.com","****************");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","406623380@qq.com","****************");
//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);
//指明邮件的发件人 24736743
mimeMessage.setFrom(new InternetAddress("406623380@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("406623380@qq.com"));
//邮件的标题
mimeMessage.setSubject("我也不知道是个什么东西就发给你了");
/*
编写邮件的内容
1.图片
2.附件
3.文本
*/
//图片
MimeBodyPart body1 = new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("C:\\Users\\wangyudong\\Desktop\\1.png")));
body1.setContentID("yhbxb.png");//图片设置ID
//文本
MimeBodyPart body2 = new MimeBodyPart();
body2.setContent("请注意,我不是广告","text/html;charset=utf-8");
//附件
MimeBodyPart body3 = new MimeBodyPart();
body3.setDataHandler(new DataHandler(new FileDataSource("C:\\Users\\wangyudong\\Desktop\\1.png")));
body3.setFileName("1.png");//附件设置名字
MimeBodyPart body4 = new MimeBodyPart();
body4.setDataHandler(new DataHandler(new FileDataSource("C:\\Users\\wangyudong\\Desktop\\1.sql")));
body4.setFileName("");//附件设置名字
//拼装邮件正文内容
MimeMultipart multipart1 = new MimeMultipart();
multipart1.addBodyPart(body1);
multipart1.addBodyPart(body2);
multipart1.setSubType("related");//1.文本和图片内嵌成功
//new MimeBodyPart().setContent(multipart1); //将拼装好的正文内容设置为主体
MimeBodyPart contentText = new MimeBodyPart();
contentText.setContent(multipart1);
//拼接附件
MimeMultipart allFile = new MimeMultipart();
allFile.addBodyPart(body3);//附件
allFile.addBodyPart(body4);//附件
allFile.addBodyPart(contentText);//正文
allFile.setSubType("mixed");//正文和附件都存在邮件中,所有类型设置为mixed
//放到Message消息中
mimeMessage.setContent(allFile);
mimeMessage.saveChanges();
return mimeMessage;
}
}
3、网站注册发送邮件的代码实现
准备文件:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--Servlet 依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--JSP依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--JSTL表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--连接数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
======================================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$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>
=====================================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>xxx网站温馨提示</h1>
${message}
</body>
</html>
======================================================================================
<?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">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.kuang.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
</web-app>
代码实现:
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秒原则:用户体验
//多线程实现用户体验! 异步处理
public class SendMail extends Thread{
//用于给用户发送邮件的通知
private String from = "406623380@qq.com";
//邮箱的用户名
private String username = "406623380@qq.com";
//邮箱的密码
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 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() {
protected PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("406623380@qq.com","****************");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","406623380@qq.com","****************");
//4、创建邮件:写邮件
//注意需要传递Session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人 24736743
message.setFrom(new InternetAddress("406623380@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
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();
//5、发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6、关闭连接
ts.close();
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
==================================================================================
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接受用户请求,封装成对象
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
User user = new User(username, password, email);
//用户注册成功之后,会给用户发送一封邮件
//我们使用线程来专门发送邮件,防止出现耗时,和网络注册人数过多的情况
SendMail send = new SendMail(user);
//启动线程,线程启动之后就会执行run方法来发送邮件
//send.run();为不使用多线程,页面反应较慢
send.start();//使用多线程进行操作
//注册用户
req.setAttribute("message","注册成功,我们已经发送了一封带了注册信息的电子邮件,请查收!如网络不稳定,可能过会才能收到!!");
req.getRequestDispatcher("info.jsp").forward(req,resp);
}
}
作者:wangyudong
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。