zoukankan      html  css  js  c++  java
  • web基础---->java邮件的发送

      这里记录一下关于java邮件发送代码的编写。你在我身边也好,在天边也罢,想到世界的角落有一个你,觉得整个世界也变得温柔安定了。

    java邮件的发送

    一、直接贴出代码,如下:

    package com.chenhui.huhx.util;
    
    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Address;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    /**
     * 发送邮件的工具类
     * 
     * @author huhx
     * @date: 2016年12月19日 下午4:19:30
     */
    public class SendMailUtils {
        public final static String EMAIL_SEND_FROM = "XXX@qq.com"; // 发送方的qq邮箱
    
        // 发送短信
        public static void sendMail(String to, String message) {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.port", 465); // 这个需要
            props.put("mail.smtp.auth", "true");
            props.put("mail.from", EMAIL_SEND_FROM);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            Address address;
            try {
                address = new InternetAddress(EMAIL_SEND_FROM);
                msg.setFrom(address);
                msg.setRecipients(Message.RecipientType.TO, to);
                msg.setSubject("HelloWorld");
                msg.setSentDate(new Date());
                String html = "<html><body><span>" + message + "</span></body></html>";
                msg.setText(html, "utf-8", "html");
                Transport.send(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        // 发送邮件需要授权
        static Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EMAIL_SEND_FROM, "XXXX"); // 这里的XXXX表示授权码
            }
        };
        
        // 测试
        public static void main(String[] args) {
            sendMail("XXXX@qq.com", "我爱你!"); // XXXXX表示接收方的邮箱
        }
    }

    关于授权码的获得,如下图生成授权码 。

    二、对于qq邮箱,需要做一些设置。如下

    帐户

    友情链接

  • 相关阅读:
    面试题32_3:之字形打印二叉树
    面试题21_2:调整数组顺序使奇数位于偶数之前(各数之间的相对位置不变)
    面试题21:调整数组顺序使奇数位于偶数前面
    面试题32_2:分行从上到下打印二叉树
    面试题32:从上到下打印二叉树
    面试题31:栈的压入、弹出序列
    面试题30:包含min函数的栈
    二分图的最大匹配
    链式前向星+次短路
    次小生成树
  • 原文地址:https://www.cnblogs.com/huhx/p/basewebusesendmail.html
Copyright © 2011-2022 走看看