image.png

包含图片

  1. package com.dyq;
  2. import com.sun.mail.util.MailSSLSocketFactory;
  3. import javax.activation.DataHandler;
  4. import javax.activation.FileDataSource;
  5. import javax.mail.*;
  6. import javax.mail.internet.InternetAddress;
  7. import javax.mail.internet.MimeBodyPart;
  8. import javax.mail.internet.MimeMessage;
  9. import javax.mail.internet.MimeMultipart;
  10. import java.security.GeneralSecurityException;
  11. import java.util.Properties;
  12. /**
  13. * 发送一封简单的邮件
  14. */
  15. public class MailDemo01 {
  16. public static void main(String[] args) throws Exception {
  17. Properties prop = new Properties();
  18. prop.setProperty("mail.host", "smtp.qq.com"); //设置QQ邮件服务区
  19. prop.setProperty("mail.transport.protocol", "smtp"); //邮件发送协议
  20. prop.setProperty("mail.smtp.auth", "true"); //需要验证用户名密码
  21. //关于QQ邮箱,还要设置SSL加密,加上以下代码即可,大厂,其他邮箱不需要
  22. MailSSLSocketFactory sf = new MailSSLSocketFactory();
  23. sf.setTrustAllHosts(true);
  24. prop.put("mail.smtp.ssl.enable", "true");
  25. prop.put("mail.smtp.socketFactory", sf);
  26. //使用JavaMail发送邮箱的5个步骤
  27. //1.创建定义整个应用程序所需的环境信息的Session对象
  28. //QQ才有,其他邮箱不用
  29. Session session = Session.getInstance(prop, new Authenticator() {
  30. @Override
  31. protected PasswordAuthentication getPasswordAuthentication() {
  32. return new PasswordAuthentication("504561395@qq.com", "xkmwtqwlqsbgbgfb");
  33. }
  34. });
  35. // 开启Session的debug模式:可以看到程序发送Email的运行状态
  36. session.setDebug(true);
  37. //2.通过session得到transport对象
  38. Transport ts = session.getTransport();
  39. //3.使用邮箱的用户名和授权码连上邮件服务器
  40. ts.connect("smtp.qq.com", "504561395@qq.com", "xkmwtqwlqsbgbgfb");
  41. //4.创建邮箱:写邮件
  42. //注意需要传递Session
  43. Message message = new MimeMessage(session);
  44. //指明邮件的发件人
  45. message.setFrom(new InternetAddress("504561395@qq.com"));
  46. //指明收件人
  47. message.setRecipient(Message.RecipientType.TO, new InternetAddress("504561395@qq.com"));
  48. //设置邮箱标题
  49. message.setSubject("秃头小分队Demo");
  50. //邮件的文本内容
  51. //========================================================================
  52. //准备图片数据
  53. MimeBodyPart image=new MimeBodyPart();
  54. //图片需要经过数据化的处理 DataHandler数据处理
  55. DataHandler dh=new DataHandler(new FileDataSource("C:\\Users\\DYQ\\IdeaProjects\\javaweb-mail\\src\\0.png"));
  56. //在我们的的body中放入这个处理的图片数据
  57. image.setDataHandler(dh);
  58. //给这个图片设置一个ID名字,我们在后面可以使用 (76行cid
  59. image.setContentID("bz.jpg");
  60. //准备正文的数据
  61. MimeBodyPart text=new MimeBodyPart();
  62. // cid:setContentID
  63. text.setContent("这是一张正文<img src='cid:bz.jpg'>","text/html;charset=UTF-8");
  64. //描述数据关系
  65. MimeMultipart mm=new MimeMultipart();
  66. mm.addBodyPart(text);
  67. mm.addBodyPart(image);
  68. mm.setSubType("related");//mm.setSubType("mixed");
  69. //设置到消息中,保存修改
  70. message.setContent(mm); //把最后编辑好的邮件放到消息当中
  71. message.saveChanges(); //保存修改
  72. //5.发送邮件
  73. ts.sendMessage(message,message.getAllRecipients());
  74. //6.关闭
  75. ts.close();
  76. }
  77. }

包含附件

  1. import com.sun.mail.util.MailSSLSocketFactory;
  2. import javax.activation.DataHandler;
  3. import javax.activation.FileDataSource;
  4. import javax.mail.*;
  5. import javax.mail.internet.*;
  6. import java.util.Properties;
  7. public class MailDemo03 {
  8. public static void main(String[] args) throws Exception {
  9. Properties prop=new Properties();
  10. prop.setProperty("mail.host","smtp.qq.com");///设置QQ邮件服务器
  11. prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议
  12. prop.setProperty("mail.smtp.auth","true");//需要验证用户密码
  13. //QQ邮箱需要设置SSL加密
  14. MailSSLSocketFactory sf=new MailSSLSocketFactory();
  15. sf.setTrustAllHosts(true);
  16. prop.put("mail.smtp.ssl.enable","true");
  17. prop.put("mail.smtp.ssl.socketFactory",sf);
  18. //使用javaMail发送邮件的5个步骤
  19. //1.创建定义整个应用程序所需要的环境信息的session对象
  20. Session session=Session.getDefaultInstance(prop, new Authenticator() {
  21. @Override
  22. protected PasswordAuthentication getPasswordAuthentication() {
  23. return new PasswordAuthentication("1192XXXX@qq.com","授权码");
  24. }
  25. });
  26. //开启session的debug模式,这样可以查看到程序发送Email的运行状态
  27. session.setDebug(true);
  28. //2.通过session得到transport对象
  29. Transport ts=session.getTransport();
  30. //3.使用邮箱的用户名和授权码连上邮件服务器
  31. ts.connect("smtp.qq.com","1192XXXX@qq.com","授权码");
  32. //4.创建邮件:写文件
  33. //注意需要传递session
  34. MimeMessage message=new MimeMessage(session);
  35. //指明邮件的发件人
  36. message.setFrom(new InternetAddress("1192XXXX@qq.com"));
  37. //指明邮件的收件人
  38. message.setRecipient(Message.RecipientType.TO,new InternetAddress("1192XXXX@qq.com"));
  39. //邮件标题
  40. message.setSubject("java发出");
  41. //邮件的文本内容
  42. //=================================准备图片数据
  43. MimeBodyPart image=new MimeBodyPart();
  44. //图片需要经过数据化的处理
  45. DataHandler dh=new DataHandler(new FileDataSource("D:\\Bert\\1594126632(1).jpg"));
  46. //在part中放入这个处理过图片的数据
  47. image.setDataHandler(dh);
  48. //给这个part设置一个ID名字
  49. image.setContentID("bz.jpg");
  50. //=================================准备正文数据
  51. MimeBodyPart text=new MimeBodyPart();
  52. text.setContent("这是一张正文<img src='cid:bz.jpg'>","text/html;charset=UTF-8");
  53. //=================================准备附件数据
  54. MimeBodyPart body1= new MimeBodyPart();
  55. body1.setDataHandler(new DataHandler(new FileDataSource("D:\\Bert\\cmd.txt")));
  56. body1.setFileName("1.txt");
  57. //描述数据关系
  58. MimeMultipart mm=new MimeMultipart();
  59. mm.addBodyPart(body1);
  60. mm.addBodyPart(text);
  61. mm.addBodyPart(image);
  62. mm.setSubType("mixed");
  63. //设置到消息中,保存修改
  64. message.setContent(mm);
  65. message.saveChanges();
  66. //5.发送邮件
  67. ts.sendMessage(message,message.getAllRecipients());
  68. //6.关闭连接
  69. ts.close();
  70. }
  71. }

实战:注册通知邮件

index.JSP

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Title</title>
  5. </head>
  6. <body>
  7. <h2>Hello World!</h2>
  8. <form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
  9. 用户名:<input type="text" name="username"><br>
  10. 密码:<input type="text" name="pwd"><br>
  11. 邮箱:<input type="text" name="email"><br>
  12. <input type="submit" value="注册">
  13. </form>
  14. </body>
  15. </html>

实体类

  1. package com.dyq.pojo;
  2. public class User {
  3. private String username;
  4. private String password;
  5. private String email;
  6. public User() {
  7. }
  8. public User(String username, String password, String email) {
  9. this.username = username;
  10. this.password = password;
  11. this.email = email;
  12. }
  13. @Override
  14. public String toString() {
  15. return "User{" +
  16. "username='" + username + '\'' +
  17. ", password='" + password + '\'' +
  18. ", email='" + email + '\'' +
  19. '}';
  20. }
  21. public String getUsername() {
  22. return username;
  23. }
  24. public void setUsername(String username) {
  25. this.username = username;
  26. }
  27. public String getPassword() {
  28. return password;
  29. }
  30. public void setPassword(String password) {
  31. this.password = password;
  32. }
  33. public String getEmail() {
  34. return email;
  35. }
  36. public void setEmail(String email) {
  37. this.email = email;
  38. }
  39. }

绑定路径

  1. <servlet>
  2. <servlet-name>RegisterServlet</servlet-name>
  3. <servlet-class>cn.csn.MailDemo01.servlet.RegisterServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>RegisterServlet</servlet-name>
  7. <url-pattern>/RegisterServlet.do</url-pattern>
  8. </servlet-mapping>

servlet

  1. package com.dyq.servlet;
  2. import com.dyq.pojo.User;
  3. import com.dyq.utils.Sendmail;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. public class RegisterServlet extends HttpServlet {
  10. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  11. //接受用户请求,封装成对象
  12. String username=request.getParameter("username");
  13. String password=request.getParameter("password");
  14. String email=request.getParameter("email");
  15. User user = new User(username, password, email);
  16. //用户注册成功之后,给用户发送一封邮件
  17. //我们使用线程来专门发送邮件,防止出现耗时,和网站注册人数过多的情况
  18. Sendmail send = new Sendmail(user);
  19. //启动线程,线程启动之后就会执行run方法来发送邮件
  20. send.start();
  21. //注册用户
  22. request.setAttribute("message","注册成功");
  23. request.getRequestDispatcher("info.jsp").forward(request,response);
  24. }
  25. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  26. }
  27. }

发送邮件核心类

  1. package com.dyq.utils;
  2. import com.dyq.pojo.User;
  3. import com.sun.mail.util.MailSSLSocketFactory;
  4. import javax.mail.*;
  5. import javax.mail.internet.InternetAddress;
  6. import javax.mail.internet.MimeMessage;
  7. import java.util.Properties;
  8. //网站3秒原则:用户体验
  9. //多线程实现用户体验 (异步处理
  10. public class Sendmail extends Thread{
  11. //用于给用户发送邮件的邮箱
  12. private String from="504561395@qq.com";
  13. //邮箱的用户名
  14. private String username="504561395.qq.com";
  15. //邮箱的密码
  16. private String password="xkmwtqwlqsbgbgfb";
  17. //发送邮箱的地址
  18. private String host = "smtp.qq.com";
  19. private User user;
  20. public Sendmail(User user){
  21. this.user=user;
  22. }
  23. @Override
  24. public void run() {
  25. try {
  26. Properties prop = new Properties();
  27. prop.setProperty("mail.host", host);///设置QQ邮件服务器
  28. prop.setProperty("mail.transport.protocol", "smtp");///邮件发送协议
  29. prop.setProperty("mail.smtp.auth", "true");//需要验证用户密码
  30. //QQ邮箱需要设置SSL加密
  31. MailSSLSocketFactory sf = new MailSSLSocketFactory();
  32. sf.setTrustAllHosts(true);
  33. prop.put("mail.smtp.ssl.enable", "true");
  34. prop.put("mail.smtp.ssl.socketFactory", sf);
  35. //使用javaMail发送邮件的5个步骤
  36. //1.创建定义整个应用程序所需要的环境信息的session对象
  37. Session session = Session.getDefaultInstance(prop, new Authenticator() {
  38. @Override
  39. protected PasswordAuthentication getPasswordAuthentication() {
  40. return new PasswordAuthentication("504561395@qq.com", "xkmwtqwlqsbgbgfb");
  41. }
  42. });
  43. //开启session的debug模式,这样可以查看到程序发送Email的运行状态
  44. session.setDebug(true);
  45. //2.通过session得到transport对象
  46. Transport ts = session.getTransport();
  47. //3.使用邮箱的用户名和授权码连上邮件服务器
  48. ts.connect(host, username, "xkmwtqwlqsbgbgfb");
  49. //4.创建邮件:写文件
  50. //注意需要传递session
  51. MimeMessage message = new MimeMessage(session);
  52. //指明邮件的发件人
  53. message.setFrom(new InternetAddress(from));
  54. //指明邮件的收件人
  55. message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
  56. //邮件标题
  57. message.setSubject("注册通知");
  58. //邮件的文本内容
  59. message.setContent("恭喜你(" + user.getUsername() + ")成功注册!" + "密码:" + user.getPassword()
  60. , "text/html;charset=UTF-8");
  61. //5.发送邮件
  62. ts.sendMessage(message, message.getAllRecipients());
  63. //6.关闭连接
  64. ts.close();
  65. } catch (Exception e) {
  66. System.out.println(e);
  67. }
  68. }
  69. }

这里引入多线程的目的是为了提高用户的体验,防止因发送文件时间过长,导致前端响应过久,因此这里采用异步响应。