实例代码
package sendEmail;
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 SendEmailPlus {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host","smtp.qq.com");//设置邮箱服务
prop.setProperty("mail.transport.protocol","smtp");//邮件发送协议
prop.setProperty("mail.smtp.auth","ture");//需验证用户名密码
//关于QQ邮箱还需设置SSL加密,加上以下代码即可(QQ才有)
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.socketFactory",sf);
//使用java邮箱发送邮件的五个步骤
//1.创建整个应用程序需要的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
//设置发件人邮箱账户和密码 //QQ才用授权码
return new PasswordAuthentication("发件人邮箱","授权码或者密码");
}
});
//开启session的debug模式
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和密码/授权码连接上邮箱服务器(发送端)
//qq邮箱服务器地址smtp.qq.com
ts.connect("收件人邮箱服务器","发件人邮箱","授权码或者密码");
//4.创建邮件
//创建邮件对象
MimeMessage msg = createMail(session);
//5.发送邮件
ts.sendMessage(msg,msg.getAllRecipients());
//发送完成,关闭发送流
ts.close();
}
public static MimeMessage createMail(Session session) throws MessagingException {
MimeMessage msg = new MimeMessage(session);
//指明发件人
msg.setFrom(new InternetAddress("发件人邮箱"));
//指明邮箱的收件人(可以放收件人数组)
msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress("收件人邮箱"));
//=========================================复杂邮件内容区别线=======================
//设置邮件的标题
msg.setSubject("带图片和附件的邮件");
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要数据处理 DataHandler:数据处理
DataHandler dh = new DataHandler(new FileDataSource("src/main/java/source/niu.jpg"));
image.setDataHandler(dh);//添加处理后的数据
image.setContentID("niu.jpg");//给图片设置一个ID,可以在后面内容中引用
//准备附件
MimeBodyPart other1 = new MimeBodyPart();
//附件需要数据处理
DataHandler dh1 = new DataHandler(new FileDataSource("src/main/java/source/yingyu.mp3"));
other1.setDataHandler(dh1);
other1.setFileName("English.mp3");
//准备邮件的正文内容
MimeBodyPart text = new MimeBodyPart();
//cid:ContentID
text.setContent("这是带有这个<img src='cid:niu.jpg'>图片和一些附件的邮件","text/html;charset=UTF-8");
//将文本和图片包装起来
MimeMultipart mix = new MimeMultipart();
mix.addBodyPart(text);
mix.addBodyPart(image);
//SubType:alternative<related <mixed
/*
* alternative:只含有文本
*related:含有文本和图片
* mixed:带有文本,图片和附件
* */
mix.setSubType("related");
//将文本和图片设置为主题
MimeBodyPart a = new MimeBodyPart();
a.setContent(mix);
//将附件拼接得到最终的邮件
MimeMultipart target = new MimeMultipart();
//根据需要创建,添加附件和图片,可以是多个,也可以没有
target.addBodyPart(other1);
target.addBodyPart(a);
target.setSubType("mixed");
//=========================================复杂邮件内容区别线=======================
//简单邮件(只含有文本)只需要修改下面这行代码为
//msg.setContent("邮件内容","text/html;charset=UTF-8");
msg.setContent(target);//把编辑好的邮件放到消息中
msg.saveChanges();
return msg;
}
}
需要导入的jar包
导入activation和mail两个jar包
注意:使用javaweb进行邮件发送时,Tomcat的lib目录也需要导入这两个包
对应的maven依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
补充
邮件发送建议提取成多线程工具类,使用多线程节约发送时间
javaweb使用案例(用户注册)
jsp:
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login.do" method="get">
<p>用户名:<input type="text" name="userName"></p>
<p>密码:<input type="password" name="userPassword"></p>
<p>邮箱:<input type="text" name="userEmail"></p>
<p><input type="submit" value="提交"></p>
</form>
</body>
</html>
servlet:
package com.email;
import User.User;
import utils.SendEmail;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class SendEmailServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
request.setCharacterEncoding("UTF-8");
//获取用户信息
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
String userEmail = request.getParameter("userEmail");
User user = new User(userName,userPassword,userEmail);
//启动线程给用户发送一条消息,使程序在后台运行,避免耗时
SendEmail sendEmail = new SendEmail(user);
sendEmail.start();
//跳转页面
request.setAttribute("message","注册成功");
request.getRequestDispatcher("info.jsp").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
try {
request.setAttribute("message","注册失败");
request.getRequestDispatcher("info.jsp").forward(request,response);
} catch (ServletException servletException) {
servletException.printStackTrace();
}
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
pojo:
自己的邮箱信息
package User;
public class My {
//发件人邮箱地址
private String from;
//发件人邮箱密码/授权码
private String password;
//收件人主机
private String host;
public My() {
}
public My(String from, String password, String host) {
this.from = from;
this.password = password;
this.host = host;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
对方的邮箱信息
package User;
import java.io.Serializable;
public class User implements Serializable {
private String userName;
private String userPassword;
private String Email;
public User(String userName, String userPassword, String email) {
this.userName = userName;
this.userPassword = userPassword;
Email = email;
}
public User() {
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
}
邮件发送工具类:
package utils;
import User.User;
import User.My;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.ResourceBundle;
public class SendEmail extends Thread{
private My my ;
private User user;
public SendEmail(User user){
this.user=user;
ResourceBundle bundle = ResourceBundle.getBundle("sendEmail");
this.my=new My(bundle.getString("from"),bundle.getString("password"),bundle.getString("host") );
}
public void run() {
try {
Properties prop = new Properties();
prop.setProperty("mail.host", my.getHost());//设置邮箱服务
prop.setProperty("mail.transport.protocol", "smtp");//邮件发送协议
prop.setProperty("mail.smtp.auth", "ture");//需验证用户名密码
//关于QQ邮箱还需设置SSL加密,加上以下代码即可(QQ才有)
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.socketFactory", sf);
//使用java邮箱发送邮件的五个步骤
//1.创建整个应用程序需要的环境信息的Session对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//设置发件人邮箱账户和密码 //QQ才用授权码
return new PasswordAuthentication(my.getFrom(), my.getPassword());
}
});
//开启session的debug模式
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和密码/授权码连接上邮箱服务器(发送端)
ts.connect(my.getHost(), my.getFrom(), my.getPassword());
//4.创建邮件
//创建邮件对象
MimeMessage msg = new MimeMessage(session);
//指明发件人
msg.setFrom(new InternetAddress(my.getFrom()));
//指明邮箱的收件人(可以放收件人数组)
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(user.getEmail()));
//设置邮件的标题
msg.setSubject("注册成功");
//设置邮件的文本内容
msg.setContent("注册成功!您的账号是"+user.getUserName()+"您的密码是"+user.getUserPassword(), "text/html;charset=UTF-8");
//5.发送邮件
//这里可以使用ts发送多个
ts.sendMessage(msg, msg.getAllRecipients());
//发送完成,关闭发送流
ts.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
配置文件:
# 收件人邮箱的服务器地址
host = smtp.qq.com
#发送人的邮箱地址
from = 1617511878@qq.com
# 密码/授权码
password =