Java下的邮件发送

文章源自于b站up主 遇见狂神说 的视频教学文档

JavaWeb下的邮件发送

1.利用qq邮箱服务器去发送一封简单的邮件【纯文本邮件】

注意点:用qq邮箱服务器去发送邮件时,需要打开qq邮箱设置里的POP3/SMTP服务,去获取发送邮件时的授权码。
在这里插入图片描述
Maven项目下发送邮件需要导入的依赖:

<!--    发送邮件的jar包依赖-->
    <dependencies>
        <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>
    </dependencies>

Java代码的具体实现如下:

package com.tangxiao.mailtest;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendMailDemo {
    public static void main(String[] args) throws Exception{

        Properties prop = new Properties();
        //设置QQ邮件服务器
        prop.setProperty("mail.host","smtp.qq.com");
        //邮件发送协议
        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 对象

        //QQ邮箱才有,其它邮箱不用
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发送邮件的用户名,授权码
                return new PasswordAuthentication("xxx@qq.com","授权码");
            }
        });
        //开启Session的Debug模式,这样可以查看程序发送Email的运行状态
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();
        //3.使用邮箱的用户名和授权码连接上qq邮箱服务器
        ts.connect("smtp.qq.com","xxx@qq.com","授权码");
        //4.创建邮件:写邮件
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("xxx@qq.com"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("yyy@qq.com"));
        //邮件的标题
        message.setSubject("这是一封简单的邮件");
        //邮件文本内容
        message.setContent("<p style='color:red'>欢迎您成为本公司的会员。</p>","text/html;charset=UTF-8");
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        ts.close();
    }
}

2.利用qq邮箱服务器去发送一封简单的邮件【纯文本带图片的邮件】

Java代码的具体实现如下

package com.tangxiao.mailtest;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class SendMailDemo02 {
    public static void main(String[] args) throws Exception{

        Properties prop = new Properties();
        //设置QQ邮件服务器
        prop.setProperty("mail.host","smtp.qq.com");
        //邮件发送协议
        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 对象

        //QQ邮箱才有,其它邮箱不用
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //发送邮件的用户名,授权码
                return new PasswordAuthentication("xxx@qq.com","授权码");
            }
        });
        //开启Session的Debug模式,这样可以查看程序发送Email的运行状态
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();
        //3.使用邮箱的用户名和授权码连接上qq邮箱服务器
        ts.connect("smtp.qq.com","xxx@qq.com","授权码");
        //4.创建邮件:写邮件
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress("xxx@qq.com"));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("yyy@qq.com"));
        //邮件的标题
        message.setSubject("这是一封简单的邮件");
        //准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("D:/ITSOFT/IDEA/workfile/javaweb/javaweb-mail/src/美女.png"));
        image.setDataHandler(dh);
        image.setContentID("meinv.png");
        //准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封邮件正文带图片<img src='cid:meinv.png'>的邮件","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();
    }
}

3.简单的用户注册网页去发送一个邮件请求

3.1 index.jsp前端页面
这里使用了 Bootstrap 的CSS样式:<linkhref=“https://cdn.staticfile.org/twitterbootstrap/3.3.7/css/bootstrap.min.css” rel=“stylesheet”>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>XX网站</title>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
  <div class="row clearfix">
    <div class="col-md-12 column">
      <div class="page-header">
        <h1>
          <small>XXX网站欢迎您!</small>
        </h1>
      </div>
    </div>
  </div>
  <div class="row clearfix">
    <div class="col-md-12 colum">
      <form  action="${pageContext.request.contextPath}/sendmail.do" method="post">
        <div class="form-group">
          <label for="exampleInputUserName">UserName</label>
          <input type="text" class="form-control" id="exampleInputUserName" name="username" placeholder="UserName">
        </div>
        <div class="form-group">
          <label for="exampleInputPassword">Password</label>
          <input type="password" class="form-control" id="exampleInputPassword" name="password" placeholder="Password">
        </div>
        <div class="form-group">
          <label for="exampleInputEmail">Email address</label>
          <input type="email" class="form-control" id="exampleInputEmail" name="email" placeholder="Email">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </div>
</div>
</body>
</html>

在这里插入图片描述
3.2 info.jsp前端页面,用来展示用户注册后的反馈信息

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>XXX网站</title><link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>XXX网站欢迎您!</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 colum">
            <h3>${message}</h3>
        </div>
    </div>
</div>
</body>
</html>

在这里插入图片描述
3.3 Java代码的具体实现如下:

邮件发送工具类:SendMailUtils

package com.tangxiao.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import com.tangxiao.pojo.User;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class SendMailUtils  extends Thread{

    //用于给用户发送邮件的邮箱
    private String from = "XXX@qq.com";
    //邮箱的用户名
    private String username = "XXX@qq,com";
    //邮箱的密码
    private String password = "授权码";
    //发送邮箱的服务器地址
    private String host = "smtp.qq.com";

    private User user;
    public SendMailUtils(User user) {
        this.user = user;
    }
    //重写run方法的实现,在run方法中发送邮件给指定的用户
    @Override
    public void run() {
        try {
            Properties prop = new Properties();
            //设置QQ邮件服务器
            prop.setProperty("mail.host",host);
            //邮件发送协议
            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 对象

            //QQ邮箱才有,其它邮箱不用
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    //发送邮件的用户名,授权码
                    //这里的两个参数不能使用 username password,否则会出错
                    return new PasswordAuthentication("XXX@qq.com","授权码");
                }
            });
            //开启Session的Debug模式,这样可以查看程序发送Email的运行状态
            session.setDebug(true);
            //2.通过session得到transport对象
            Transport ts = session.getTransport();
            //3.使用邮箱的用户名和授权码连接上qq邮箱服务器
            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("用户注册邮件","UTF-8");//邮件标题
            String info = "恭喜您注册成功,您的用户名:" + user.getUsername() + ",您的密码:" + user.getPassword() + "," +
                    "请妥善保管,如有问题请联系网站客服---->  " + "<a href='www.bilibili.com'>客服热线</a>";
            message.setContent(info,"text/html;charset=UTF-8");
            message.saveChanges();
            //5.发送邮件
            ts.sendMessage(message,message.getAllRecipients());
            //6.关闭连接
            ts.close();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Servelt类:MailServlet

package com.tangxiao.servlet;

import com.tangxiao.pojo.User;
import com.tangxiao.utils.SendMailUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MailServlet extends HttpServlet {
    @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);
        //用户注册成功后,给用户发送邮件
        //我们使用线程安全来专门发送邮件,防止出现耗时,和网站注册人数过多的情况
        SendMailUtils sendMail = new SendMailUtils(user);
        //启动线程,线程启动之后就会执行run方法来发送邮件
        sendMail.start();

        //注册用户
        req.setAttribute("message","注册成功,我们已经发送了一封带注册信息的电子邮件,请查收!如有网络不稳定,可能稍后才能收到!!");
        req.getRequestDispatcher("info.jsp").forward(req,resp);

    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值