java实现邮件发送

整体思路:

前端输入客户用户名,密码,邮箱
后端获取客户邮箱,向邮箱发送信息

第一步 创建maven项目(添加web框架),配置并测试tomcat服务器

在这里插入图片描述

第2步 添加依赖,实现邮件发送

       <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
       
       <!-- 实现邮件发送 -->
        <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>

第3步 前端编写

     <form action="${pageContext.request.contextPath}/register.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>

第4步 后端编写

servlet类

pojo

util

1.pojo

   封装前端传的参数
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 + '\'' +
                '}';
    }
}

2. util

   为了更好的用户体验(会有延时),采用多线程进行处理
public class SendEmail extends Thread{

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

    private User user;
    public SendEmail(User user){
        this.user = user;
    }

    //在run方法中发送邮件给指定的用户
    @Override
    public void run() {

        try {
            Properties prop = new Properties();//创建一封邮件
            //以下三项的Key的值都是固定的
            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);

            //java发送邮件的6个步骤

            //1、创建定义整个应用程序所需要的环境信息的Session对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication(){
                    //发件人邮箱的用户名和授权码(只有qq是授权码,其它的是密码)
                    return new PasswordAuthentication(username,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,发送邮件
            ts.sendMessage(message,message.getAllRecipients());
            //6,关闭连接
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. servlet类

 处理前端参数
public class EmailServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //接收用户请求  封装成对象
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        User user = new User(username,password,email);

        //用户注册成功之后,给用户发送一封邮件
        //使用线程来专门发送邮件,防止出现耗时,网站注册人数过多的情况
        SendEmail send = new SendEmail(user);
        //启动线程,线程启动之后就会执行run方法来发送邮件
        send.start();

        //注册用户
        request.setAttribute("msg","注册成功,已经发了一封带注册信息的电子邮件,请查收!如果网络不稳定,可能过会才能收到!!");
        request.getRequestDispatcher("info.jsp").forward(request,response);
    }
  }

总结

 遇到的bug是创建空的maven项目,添加web框架,会造成500错误,然而代码没有任何错误,只需删除文件.iml的标签 
 具体原理没有搞懂,为什么删除这个就行

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 可以使用 JavaMail API 实现邮件发送功能。以下是一个简单的代码示例: ``` import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailSender { public static void main(String[] args) { final String username = "your-email@example.com"; // 替换为你的邮箱用户名 final String password = "your-password"; // 替换为你的邮箱密码 Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.example.com"); // 替换为你的 SMTP 服务器地址 props.put("mail.smtp.port", "587"); // 替换为你的 SMTP 端口号 Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your-email@example.com")); // 替换为你的发件人邮箱地址 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient-email@example.com")); // 替换为你的收件人邮箱地址,多个邮箱地址用逗号分隔 message.setSubject("Test Email"); message.setText("This is a test email sent from Java."); Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { throw new RuntimeException(e); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值