前言
本文为JavaWeb基础邮件收发相关知识介绍~,Java全栈学习路线可参考: 【Java全栈学习路线】最全的Java学习路线及知识清单,Java自学方向指引,内含最全Java全栈学习技术清单~
一、邮件的发送与接收原理
要在Internet上提供电子邮件功能,必须有专门的电子邮件服务器。电子邮箱(E-Mail地址)的获得需要在邮件服务器上进行申请。以QQ邮箱为例,需要从账户设置中开启POP3/SMTP服务。
用户连接上邮件服务器之后,要想给它发送一封电子邮件,需要遵循一定的通讯规则,SMTP协议就是用来定义这种通讯规则的。
用户若想从邮件服务器管理的电子邮箱当中接收一封电子邮件话,它连上邮件服务器后,也要遵循一定的通讯格式,POP3协议就是用来定义这种通讯格式的。
邮件的发送与接收过程:
场景假设xxx.@qq.com想给xxx.@sina.com发送邮件
首先,xxx.@qq.com通过smtp协议连接到qq邮箱的smtp服务器,并将邮件发送给smtp服务器,紧接着,QQ邮箱的smtp服务器将邮件转投给sina的smtp服务器
sina的smtp服务器将接收到的邮件存储到xxx.@sina.com的存储空间中,xxx.@sina.com通过POP3协议连接到sina的POP3服务器上收取邮件,POP3服务器从xxx.@sina.com账号的存储空间中取出邮件并将该邮件回送给xxx.@sina.com账户
二、发送简单文本邮件
使用Java发送 E-mail 需要通过JavaMail API和Java Activation Framework得到两个jar包:mail.jar,activation.jar。
代码实现:
public class SendMail { public static void main(String[] args) throws MessagingException, GeneralSecurityException { //1 准备步骤 //1.1 创建一个配置文件保存并读取信息 Properties properties = new Properties(); //1.2 设置邮件服务器(这里使用了QQ邮箱) properties.setProperty("mail.host","smtp.qq.com"); //1.3 设置发送使用的协议 properties.setProperty("mail.transport.protocol","smtp"); //1.4 设置用户是否需要验证 properties.setProperty("mail.smtp.auth","true"); //1.5 关于QQ邮箱,还要设置SSL加密,加上以下代码即可 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); //2 连接服务器 //2.1 创建session会话对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("553401298@qq.com", "jyyylkflmkyybcif"); } }); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //2.2 通过session对象获取Transport对象(需要抛出异常) Transport transport = session.getTransport(); //2.3 连接服务器(需要抛出异常) transport.connect("smtp.qq.com","553401298@qq.com","jyyylkflmkyybcif"); //3 发送邮件 //3.1 创建用来发送邮件的对象(需要传入session) MimeMessage mimeMessage = new MimeMessage(session); //3.2 创建邮件发送人 mimeMessage.setFrom(new InternetAddress("553401298@qq.com")); //3.3 创建邮件接收人(可以同时发送给很多人(添加抄送)) mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("553401298@qq.com")}); //3.4 创建邮件主题 mimeMessage.setSubject("LUCK"); //3.5 创建邮件正文 mimeMessage.setContent("GOOD LUCK","text/html;charset=utf-8"); //3.6 发送邮件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //=================================================================== //4 关闭连接 transport.close(); } }
运行结果:
三、发送文本嵌入图片的邮件
代码实现:
public class SendImageEmail { public static void main(String[] args) throws GeneralSecurityException, MessagingException { //1.准备 Properties properties = new Properties(); properties.setProperty("mail.host","smtp.qq.com"); properties.setProperty("mail.transport.protocol","smtp"); properties.setProperty("mail.smtp.auth","true"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); //2.连接服务器 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("553401298@11.com", "jyyylkflmkyybcif"); } }); session.setDebug(true); Transport transport = session.getTransport(); //连接服务器 transport.connect("smtp.qq.com","553401298@qq.com","jyyylkflmkyybcif"); //通过方法获取一个MimeMessage MimeMessage mimeMessage = setImgEmail(session); //设置发件人和收件人 mimeMessage.setFrom(new InternetAddress("553401298@qq.com")); mimeMessage.setRecipients(Message.RecipientType.TO,new InternetAddress[]{new InternetAddress("553401298@qq.com")}); //发送邮件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //关闭连接 transport.close(); } public static MimeMessage setImgEmail(Session session) throws MessagingException { //编写邮件内容 //1.准备图片 MimeBodyPart bodyPart = new MimeBodyPart(); //2.将图片变为数据流 //获取图片数据 FileDataSource fileDataSource = new FileDataSource("src/resources/timg.jpg"); //需要一个处理数据流的处理器来处理 DataHandler dataHandler = new DataHandler(fileDataSource); //把图片数据放到邮件的正文中 bodyPart.setDataHandler(dataHandler); //给图片设置一个名字 bodyPart.setContentID("timg.jpg"); //设置文本内容 MimeBodyPart bodyPart2 = new MimeBodyPart(); //给第二个邮件内容插入图片 通过图片ID插入 bodyPart2.setContent("I need more space"+"<img src='cid:timg.jpg'>","text/html;charset=utf-8"); //拼接邮件,描述关系 MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); multipart.addBodyPart(bodyPart2); //描述邮件类型:related表示邮件为内嵌类型 mixed表示邮件为附件类型 multipart.setSubType("related"); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setContent(multipart); //保存设置 mimeMessage.setSubject("内嵌式邮件"); mimeMessage.saveChanges(); return mimeMessage; } }
运行结果:
四、发送复杂邮件(文本嵌入图片,添加附件)
代码实现:
public class SendMail { public static void main(String[] args) throws MessagingException, GeneralSecurityException { //1 准备步骤 //1.1 创建一个配置文件保存并读取信息 Properties properties = new Properties(); //1.2 设置邮件服务器(这里使用了QQ邮箱) properties.setProperty("mail.host","smtp.qq.com"); //1.3 设置发送使用的协议 properties.setProperty("mail.transport.protocol","smtp"); //1.4 设置用户是否需要验证 properties.setProperty("mail.smtp.auth","true"); //1.5 关于QQ邮箱,还要设置SSL加密,加上以下代码即可 MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); //2 连接服务器 //2.1 创建session会话对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("553401298@qq.com", "jyyylkflmkyybcif"); } }); //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(true); //2.2 通过session对象获取Transport对象(需要抛出异常) Transport transport = session.getTransport(); //2.3 连接服务器(需要抛出异常) transport.connect("smtp.qq.com","553401298@qq.com","jyyylkflmkyybcif"); //3 发送邮件 //3.1 创建用来发送邮件的对象(需要传入session) MimeMessage mimeMessage = new MimeMessage(session); //3.2 创建邮件发送人 mimeMessage.setFrom(new InternetAddress("553401298@qq.com")); //3.3 创建邮件接收人(可以同时发送给很多人(添加抄送)) mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("553401298@qq.com")}); //3.4 创建邮件主题 mimeMessage.setSubject("LUCK"); //3.5 创建邮件正文 mimeMessage.setContent("GOOD LUCK","text/html;charset=utf-8"); //3.6 发送邮件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); //=================================================================== //4 关闭连接 transport.close(); } }
运行结果:
五、发送注册提示邮件
实体类:
public class User { //实体类,用来封装用户信息 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 + '\'' + '}'; } }
发送邮件工具类:
public class SendEmail extends Thread{ //工具类,用来发送邮件 //发件邮箱 private String from = "553401298@qq.com"; //邮箱的用户名 private String username= "553401298@qq.com"; //邮箱的授权码 private String password = "jyyylkflmkyybcif"; //邮箱服务器地址 private String host = "smtp.qq.com"; private User user; public SendEmail(User user){ this.user=user; } @Override public void run() { try { Properties properties = new Properties(); properties.setProperty("mail.host",host); properties.setProperty("mail.transport.protocol","smtp"); properties.setProperty("mail.smtp.auth","true"); MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Transport transport = session.getTransport(); transport.connect(host,username,password); //通过MimeMessage设置邮件详情 MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[]{ new InternetAddress(user.getEmail())}); mimeMessage.setSubject("注册成功回执"); mimeMessage.setContent("您已成功注册,您的用户名为:"+user.getUsername() +",密码为:"+user.getPassword() +",请您妥善保管。" ,"text/html;charset=utf-8"); //通过transport对象传输邮件 transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); transport.close(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
servlet类:
public class RegisterServlet extends javax.servlet.http.HttpServlet{ //servlet类用来获取前端数据,处理转发请求 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @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); //用户注册成功之后,给用户回执邮件 //使用线程发送邮件,可以防止出现耗时,和网站注册人数过多的情况 SendEmail sendEmail = new SendEmail(user); sendEmail.start(); //提示用户查收注册回执邮件 req.setAttribute("msg","注册成功,请查收回执邮件"); req.getRequestDispatcher("info.jsp").forward(req,resp); } }
web.xml:
<?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.hooi.servlet.RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/rgs.do</url-pattern> </servlet-mapping> </web-app>
运行结果:
后记
Java全栈学习路线可参考:【Java全栈学习路线】最全的Java学习路线及知识清单,Java自学方向指引,内含最全Java全栈学习技术清单~