Java邮件发送

Java邮件发送

电子邮件发送原理

我们写信给笔友:

写信—>将信放在邮筒—>当地邮局取信—>当地邮局将信传给收信人所在地的邮局—>收信人所在地邮局将信封放到收件人家的邮箱—>笔友在邮箱拿到信—>读信

同理,我们在给别人发电子邮件时,也需要一个电子邮局,也就是邮件服务器,而我们所用的qq邮箱、网易邮箱等,就像是投递信封的邮筒。

邮件服务器
  • SMTP服务器(邮件发送服务器):处理用户邮件发送(smtp)请求的服务器

    SMTP服务器的地址一般是 smtp.xxx.com,比如qq邮箱就是smtp.qq.com。

  • POP3服务器(邮件接收服务器):处理用户邮件接收(pop3)请求的服务器

例:我要通过我的qq邮箱(0000000000@qq.com)给我的网易邮箱(aaa@163.com)发送一封邮件。在这里插入图片描述

用Java发送邮件

首先我们需要准备 JavaMail API 和Java Activation Framework 。

得到两个jar包:

  • mail.jar
  • activation.jar

JavaMail是Sun公司为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包,支持常用的邮件协议,如SMTP、POP3等。

因为我用的是qq邮箱,要得到qq邮箱的权限,会得到一个授权码。
在这里插入图片描述在这里插入图片描述在这里插入图片描述

记住授权码。

导包

在这里插入图片描述

只发送文字
package priv.sehun.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import java.security.GeneralSecurityException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;


public class SendMail {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {

        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");

        //QQ邮箱要设置SSL加密,固定代码
        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() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("15********@qq.com", "你自己的授权码");
            }
        });


        //1.开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);


        Transport ts = session.getTransport();

        //使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com", "15********@qq.com", "你自己的授权码");



        //创建邮件对象
        MimeMessage message = new MimeMessage(session);

        //指明邮件的发件人
        message.setFrom(new InternetAddress("15********@qq.com"));

        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("12********@qq.com"));

        //邮件的标题
        message.setSubject("早上好,cp");

        //邮件的文本内容
        message.setContent("你要开心哟^-^", "text/html;charset=UTF-8");

        //发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        ts.close();
    }
}
发送有图片和附件的邮件
package priv.sehun.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import java.security.GeneralSecurityException;
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMail2 {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        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);



        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("15********@qq.com", "授权码");
            }
        });


        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);


        Transport ts = session.getTransport();

        //使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com", "15********@qq.com", "授权码");



        //创建邮件对象
        MimeMessage message = getMimeMessage(session);


        //发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        ts.close();
    }

    private static MimeMessage getMimeMessage(Session session) throws MessagingException {
        MimeMessage message = new MimeMessage(session);

        //指明邮件的发件人
        message.setFrom(new InternetAddress("15********@qq.com"));

        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("26********@qq.com"));

        //邮件的标题
        message.setSubject("我是一封带有图片和附件的邮件");


        //图片
        MimeBodyPart body1 = new MimeBodyPart();
        body1.setDataHandler(new DataHandler(new FileDataSource("src/resources/bjyx.png")));
        body1.setContentID("yhbxb.png"); //图片设置ID

        //文本
        MimeBodyPart body2 = new MimeBodyPart();
        body2.setContent("早上好<img src='cid:yhbxb.png'>","text/html;charset=utf-8");

        //附件
        MimeBodyPart body3 = new MimeBodyPart();
        body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/peace.properties")));
        body3.setFileName("peace.properties"); 

        MimeBodyPart body4 = new MimeBodyPart();
        body4.setDataHandler(new DataHandler(new FileDataSource("src/resources/love.txt")));
        body4.setFileName("love.txt"); 

        //拼接图片和文本
        MimeMultipart multipart1 = new MimeMultipart();
        multipart1.addBodyPart(body1);
        multipart1.addBodyPart(body2);
        multipart1.setSubType("related");

        
        MimeBodyPart mbody =  new MimeBodyPart();
        mbody.setContent(multipart1);

        //拼接附件
        MimeMultipart multipart2 =new MimeMultipart();
        multipart2.addBodyPart(body3);
        multipart2.addBodyPart(body4);
        multipart2.addBodyPart(mbody);
        multipart2.setSubType("mixed"); 


        //放到Message消息中
        message.setContent(multipart2);
        //保存修改
        message.saveChanges();

        return message;

    }

}

在这里插入图片描述

结合JavaWeb发送邮件

写一个注册页面,然后将用户注册信息发到用户的电子邮箱

运行结果如下

在这里插入图片描述在这里插入图片描述在这里插入图片描述

代码

实体类:User.java

package priv.sehun.pojo;

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;
    }
}

**前端注册:**register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <style>
        
        h1{
            color: coral;
            align-content: center;
        }
        form{
            align-content: center;
        }
        
    </style>
</head>
<body>
<h1>欢迎来到菠萝网站注册页面注册</h1>
<form action="${pageContext.request.contextPath}/send" method="post">

    用户名:<p><input type="text" name="username" required></p>
    密码:<p><input type="password" name="password" required></p>
    您的邮箱:<p><input type="text" name="email" required></p>
    <input type="submit" value="注册">

</form>

</body>
</html>

发送邮件的工具类:

package priv.sehun.utils;

import priv.sehun.pojo.User;


import java.util.Properties;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail extends Thread {
    //网站邮箱(用来给注册网站的用户发送注册信息)
    private String addresserMailbox ="1597621711@qq.com";
    //邮箱用户名
    private String username = "1597621711@qq.com";
    //网站邮箱授权码/密码
    private String addresserPassword = "lohbdcweihwvhhhb";
    //发送邮件的服务器地址
    private String host = "smtp.qq.com";


    //用户信息
    private User user;
    public SendMail(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 = null;
            sf = new MailSSLSocketFactory();
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //发件人邮件用户名、授权码
                    return new PasswordAuthentication(addresserMailbox, addresserPassword);
                }
            });

            //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);

            //通过session得到transport对象
            Transport ts = session.getTransport();

            //使用邮箱的用户名和授权码连上邮件服务器
            ts.connect(host, username, addresserPassword);

            //4、创建邮件
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(addresserMailbox)); //发件人(网站邮箱)
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail())); //收件人(用户邮箱)
            message.setSubject("用户注册邮件"); //邮件的标题

            String info = "恭喜您注册成功^-^"
                    +"\n您的用户名为:" + user.getUsername()
                    + "\n您的密码为:" + user.getPassword() + "\n请妥善保管,我们网站没办法找回注册信息";

            message.setContent(info, "text/html;charset=UTF-8");
            message.saveChanges();

            //发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

对应的Servlet:RegisterServlet.java

package priv.sehun.servlet;

import priv.sehun.pojo.User;
import priv.sehun.utils.SendMail;

import java.io.IOException;

public class RegisterServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        try {
            //接收用户请求,封装成对象
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            User user = new User(username,password,email);

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

            //注册用户
            request.setAttribute("message", "注册成功!我们给您的邮箱发了注册信息,请注意查收!");
            request.getRequestDispatcher("info.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", "注册失败!!");
            request.getRequestDispatcher("info.jsp").forward(request, response);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值