java 通过QQ邮箱发邮件

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

        Properties props = System.getProperties();

        props.setProperty("mail.smtp.host", "smtp.qq.com");

        props.setProperty("mail.smtp.socketFactory.fallback", "false");

        props.setProperty("mail.smtp.port", "465");

        props.setProperty("mail.smtp.socketFactory.port", "465");

        props.put("mail.smtp.auth", "true");

    
        // 使用ssl加密传输,解决ssl证书报错问题
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);

        props.put("mail.smtp.ssl.enable", "true");

        props.put("mail.smtp.ssl.socketFactory", sf);
        final String username = "[email protected]";//发件人邮箱

        final String password = "xcvbgtrejpouhl";//开启QQ邮箱smtp功能给的授权码,当qq邮箱密码使用

        Session session = Session.getDefaultInstance(props, new Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(username, password);

            }
        });

        session.setDebug(true);//在控制台打印发送邮件日志信息

        // -- Create a new message --

        Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --

        msg.setFrom(new InternetAddress(username));

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]", false));//收件人邮箱

        msg.setSubject("验证码");//邮件标题(邮件标题尽量别用test,避免被QQ邮箱当垃圾扔进垃圾桶)

        msg.setText("184698");//邮件文本内容

        msg.setSentDate(new Date());

        Transport.send(msg);

        System.out.println("Message sent successful");

    }

猜你喜欢

转载自blog.csdn.net/Boxzhang/article/details/84495648