java maven通过SMTP发送QQ邮件的完全步骤

1、首先打开QQ邮箱的SMTP服务,因为QQ邮箱对于一般的用户都是默认关闭SMTP服务的。

找到SMTP服务的选项,可以看到此处默认是关闭的,点击开启,然后腾讯会进行一些身份验证,身份验证通过以后,腾讯会给出一个用于使用SMTP的16位口令,此处这个口令一定牢记,因为后面要使用SMTP功能必须要用到这个口令,没有这个口令即使知道QQ邮箱密码也没有用,此处未给出口令的截图,毕竟为了隐私保密,不然大家都可以登录使用我的QQ邮箱SMTP服务了。后面我们将该口令记为SMTP口令。 

生成授权码。

首先,要使用Java的邮箱功能需要javax.mail这个jar包:

依赖:

<!-- email start -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <!-- email end -->

发送邮件代码:

// 创建Properties 类用于记录邮箱的一些属性
        Properties props = new Properties();
        // 表示SMTP发送邮件,必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", "smtp.qq.com");
        //端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587
        props.put("mail.smtp.port", "587");
        // 此处填写你的账号
        props.put("mail.user", "xxxxxxx@qq.com");
        // 此处的密码就是前面说的16位STMP口令
        props.put("mail.password", "xxxxxxxxxxxxxxxxxxx");

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
        message.setFrom(form);

        // 设置收件人的邮箱
        InternetAddress to = new InternetAddress("xxxxxxxx@qq.com");
        message.setRecipient(RecipientType.TO, to);

        // 设置邮件标题
        message.setSubject("测试邮件");

        // 设置邮件的内容体
        message.setContent("这是一封测试邮件", "text/html;charset=UTF-8");

        // 最后当然就是发送邮件啦
        Transport.send(message);

好了,以上就可以了。

如果生产环境不能发送邮件,则要绑定host。

原文地址:https://www.cnblogs.com/gmq-sh/p/6944751.html