邮件发送
需要导入两个jar包 ,直接去meven里面拿
mail.jar activation.jar
问题
不知道为啥用maven项目再pom里面导入对应的jar包还是显示未导入jar包的问题
对此只能再项目的根目录下创建一个lib包,然后把下载好的jar包导入lib目录下,点击lib包 右键Add as Library… 添加到库 就可以使用运行了
用web项目实现邮件发送
1、简单的邮件发送
//简单邮件发送,正常邮箱这样发送就可以了,QQ例外
//简单邮箱:没有附件和图片,纯文本邮件
//复杂邮箱:有附件和图片
//要发送邮件:需要获得协议和支持!开启POP3/SMTP服务(再邮箱那里点击设置就看到了)
//然后在下面点击生成授权码,把授权码记好
public class Email_Send {
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
Properties properties = new Properties();
//把属性封装进properties 前面的key值是固定的,后面的value是可以变的
properties.setProperty("mail.host", "smtp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol", "smtp");//邮箱发送协议
properties.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码
//关于qq邮箱,还需要设置SSL加密,加上以下代码即可(大厂) 不用QQ邮箱可以不加 这是QQ邮箱固定的,其他邮箱没有
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//使用javaMail发送邮箱的五个步骤
//1.创建定义整个应用程序所需额环境信息的Session 对象
//QQ才有 其他邮箱不用
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//发件人邮箱用户名、授权码
return new PasswordAuthentication("发件人邮箱", "授权码");
}
});
//开启Session的debug模式,这样就可以看到程序发送Email的运行状态 可开可不开
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport(); //用来连接发送邮件的
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com", "邮箱的用户名", "授权码");
//4.创建邮箱
//创建邮箱对象
MimeMessage message = new MimeMessage(session);
//指名邮箱的 发 件人, 发 件人跟上面一样
message.setFrom(new InternetAddress("发 件人"));
//指名邮箱的 收 件人, 也可以自己给自己发送邮件
message.setRecipient(Message.RecipientType.TO, new InternetAddress("收 件人"));
//邮件的标题
message.setSubject("你好呀");
//邮件的文本内容,可以嵌入html
message.setContent("<h1 style='color: red'> I love you </h1>", "text/html;charset=UTF-8");
message.saveChanges(); //保存修改
//5.发送邮件 需要message 和一个地址
ts.sendMessage(message, message.getAllRecipients());
//6.关闭连接
ts.close();
}
}
2、带有图片的邮件
public class Email_Send2 {
public static void main(String[]args) throws GeneralSecurityException, MessagingException {
Properties properties = new Properties();
//把属性封装进properties 前面的key值是固定的,后面的value是可以变的
properties.setProperty("mail.host","smtp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");//邮箱发送协议
properties.setProperty("mail.smtp.auth","true"); //需要验证用户名密码
//关于qq邮箱,还需要设置SSL加密,加上以下代码即可(大厂) 不用QQ邮箱可以不加 这是QQ邮箱固定的,其他邮箱没有
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//使用javaMail发送邮箱的五个步骤
//1.创建定义整个应用程序所需额环境信息的Session 对象
//QQ才有 其他邮箱不用
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication(){
//发件人邮箱用户名、授权码
return new PasswordAuthentication("发件人邮箱用户名","授权码");
}
});
//开启Session的debug模式,这样就可以看到程序发送Email的运行状态 可开可不开
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport(); //用来连接发送邮件的
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","邮箱的用户名","授权码");
//4.创建邮箱
//创建邮箱对象
MimeMessage message = new MimeMessage(session);
//指名邮箱的 发 件人
message.setFrom(new InternetAddress("发 件人"));
//指名邮箱的 收 件人, 也可以自己给自己发送邮件
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收 件人"));
//邮件的标题
message.setSubject("你好呀");
//***********************************************************
//就除了下面这些不一样,其他都差不多一样
//准备图片数据
MimeBodyPart image = new MimeBodyPart();
//图片需要经过数据处理 ... DataHandler:数据处理 FileDataSource加载图片资源
DataHandler dh = new DataHandler(new FileDataSource("D:/idea2020/xiangMu/文件上传/邮箱发送/src/main/java/00.jpg"));
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.发送邮件 需要message 和一个地址
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}
}
3、带有图跟附件的邮件
public class Email_Send3 {
public static void main(String[]args) throws GeneralSecurityException, MessagingException {
Properties properties = new Properties();
//把属性封装进properties 前面的key值是固定的,后面的value是可以变的
properties.setProperty("mail.host","smtp.qq.com");//设置QQ邮箱服务器
properties.setProperty("mail.transport.protocol","smtp");//邮箱发送协议
properties.setProperty("mail.smtp.auth","true"); //需要验证用户名密码
//关于qq邮箱,还需要设置SSL加密,加上以下代码即可(大厂) 不用QQ邮箱可以不加 这是QQ邮箱固定的,其他邮箱没有
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.ssl.socketFactory",sf);
//使用javaMail发送邮箱的五个步骤
//1.创建定义整个应用程序所需额环境信息的Session 对象
//QQ才有 其他邮箱不用
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication(){
//发件人邮箱用户名、授权码
return new PasswordAuthentication("发件人邮箱用户名","授权码");
}
});
//开启Session的debug模式,这样就可以看到程序发送Email的运行状态 可开可不开
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport(); //用来连接发送邮件的
//3.使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com","邮箱的用户名","授权码");
//4.创建邮箱
//创建邮箱对象 (调用下面写好的类)
MimeMessage message = mime(session);
//5.发送邮件 需要message 和一个地址
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}
public static MimeMessage mime(Session session) throws MessagingException {
//固定消息
//创建邮箱对象
MimeMessage message = new MimeMessage(session);
//指名邮箱的 发 件人
message.setFrom(new InternetAddress("发 件人"));
//指名邮箱的 收 件人, 也可以自己给自己发送邮件
message.setRecipient(Message.RecipientType.TO,new InternetAddress("收 件人"));
//邮件的标题
message.setSubject("你好呀");
/*
编写邮件内容
1.图片
2.附件
3.文本
*/
//图片
MimeBodyPart image = new MimeBodyPart();
image.setDataHandler(new DataHandler(new FileDataSource("D:/idea2020/xiangMu/文件上传/邮箱发送/src/main/java/00.jpg")));
image.setContentID("bz.jpg"); //给图片设置一个ID,我们在后面可以使用
//准备正文数据
MimeBodyPart text = new MimeBodyPart();
text.setContent("<img src='cid:bz.jpg'>的邮件","text/html;charset=UTF-8");
//附件1 放的附件需要去网上查资料转格式,要不然打开不得
MimeBodyPart body = new MimeBodyPart();
body.setDataHandler(new DataHandler(new FileDataSource("D:/idea2020/xiangMu/文件上传/邮箱发送/src/main/java/pz.docx")));
body.setFileName("fj1");//设置附件名字
//附件2
MimeBodyPart body2 = new MimeBodyPart();
body2.setDataHandler(new DataHandler(new FileDataSource("D:/idea2020/xiangMu/文件上传/邮箱发送/src/main/java/pz.docx")));
body2.setFileName("fj2");//设置附件名字
//拼接邮件正文内容
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(image);
mimeMultipart.addBodyPart(text);
mimeMultipart.setSubType("related"); //文本和图片内嵌成功
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(mimeMultipart);
//拼接附件
MimeMultipart mimeMultipart1 = new MimeMultipart();
mimeMultipart1.addBodyPart(body); //附件
mimeMultipart1.addBodyPart(body2); //附件
mimeMultipart1.addBodyPart(mimeBodyPart); //正文
mimeMultipart1.setSubType("mixed"); //正文和附件都放入邮件中,所有类型设置为mixed
//放到message消息中
message.setContent(mimeMultipart1);
message.saveChanges();//保存修改
return message;
}
}
使用Maven实现邮件发送
1、给用户一个页面
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
用户名:<input type="text" name="username"> <br>
密码:<input type="password" name="password"> <br>
Email:<input type="text" name="email"> <br>
<input type="submit" value="注册">
</form>
</body>
2、写好pojo实体类
package 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、写util工具类
//3秒原则,用户体验。 多线程实现用户体验(异步处理)
public class Sendmail extends Thread{
//用于给用户发送邮件的邮箱
private String from = "邮箱号";
//邮箱的用户名
private String username = "邮箱的用户名";
//邮箱的密码(授权码)
private String password = "授权码";
//发送邮箱的服务器地址
private String host = "smtp.qq.com";
//调用pojo实体类
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加密,加上以下代码即可(大厂) 不用QQ邮箱可以不加 这是QQ邮箱固定的,其他邮箱没有
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//使用javaMail发送邮箱的五个步骤
//1.创建定义整个应用程序所需额环境信息的Session 对象
//QQ才有 其他邮箱不用
Session session = Session.getDefaultInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//发件人邮箱用户名、授权码
return new PasswordAuthentication(from, password);
}
});
//开启Session的debug模式,这样就可以看到程序发送Email的运行状态 可开可不开
session.setDebug(true);
//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");
message.saveChanges(); //保存修改
//5.发送邮件 需要message 和一个地址
ts.sendMessage(message, message.getAllRecipients());
//6.关闭连接
ts.close();
}catch (Exception e){
}
}
}
4、编写Servlet
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(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 sendmail = new Sendmail(user);
//启动线程,启动之后,会执行run方法发送一封邮件
sendmail.start();
//注册用户
req.setAttribute("message","注册成功,我们已给您发送一封邮件,如果网络不稳定的话可能过会儿才收到");
req.getRequestDispatcher("info.jsp").forward(req,resp); //重定向到一个页面,并提示用户
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
5、Servlet注册
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet.do</url-pattern>
</servlet-mapping>
6、用户重定向页面
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册成功</h1>
${message}
</body>
</html>