使用Java实现给QQ邮箱发送验证码

使用Java实现给QQ邮箱发送验证码

1.给QQ邮箱发送字符串(验证码)

public class QQYte {
    public static void main(String[] args) {
        // 创建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", "[email protected]");
        // 此处填写16位STMP口令
        props.put("mail.password", "nwjvkvlikjefdb");


    // 构建授权信息,用于进行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);
    // 设置发件人
    try {
        InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
        message.setFrom(form);

        // 设置收件人的邮箱
        //InternetAddress to = new InternetAddress("[email protected]"); 有多少个邮箱,发送给多少人
        //一般数组是不能够添加元素的  刚开始初始化的时候数组就已经规定好了长度
        //String[] strings = new String[]{"[email protected]","[email protected]","[email protected]","[email protected]"};

        //使用list集合代替 数组方便又快捷   ArrayList本身是个数组(底层是用数组实现的)
        List stringList = new ArrayList<>();
        stringList.add("[email protected]");
        //stringList.add("[email protected]");
        //stringList.add("[email protected]");
        stringList.add("[email protected]");

        for (String s : stringList) {
            System.out.println("s = " + s);

            InternetAddress to2 = new InternetAddress(s);
            //message.setRecipient(RecipientType.TO, to);
            message.setRecipient(RecipientType.TO,to2);
            //使用UUID自动生成6位验证码
            String substring = UUID.randomUUID().toString();
            // 设置邮件标题
            message.setSubject("您的验证码信息如下");

            // 设置邮件的内容体
            message.setContent(substring, "text/html;charset=UTF-8");

            // 设置邮件消息内容、包含附件
            Multipart msgPart = new MimeMultipart();
            message.setContent(msgPart);

            MimeBodyPart body = new MimeBodyPart();//正文
            //MimeBodyPart attach = new MimeBodyPart();//附件
            msgPart.addBodyPart(body);
            //msgPart.addBodyPart(attach);

            //设置正文内容
            String uuid=UUID.randomUUID().toString();
            //body.setContent("记得观看哟,更多精彩视频请关注抖音:20762851861","text/html;charset=utf-8");
            body.setContent(uuid,"text/html;charset=utf-8");
            //设置附件内容
            //attach.setDataHandler(new DataHandler(new FileDataSource("C:\\Users\\17814\\Desktop\\商品表信息.xls")));
            //attach.setFileName((MimeUtility.encodeText("旅行视频合集.mp4")));

            message.saveChanges();
            //邮件的创建时间
           // message.setSentDate(new Date());

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

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

注意:以上也可实现附件的上传

2.发送Excel表格

public class Email {

private static final Logger LOGGER = LoggerFactory.getLogger(Email.class);

private static String defaultSenderName = "[email protected]";// 默认的发件人用户名,defaultEntity用得到
private static String defaultSenderPass = "eakkywepkedmehec";// 默认的发件人密码,defaultEntity用得到
private static String defaultSmtpHost = "";// 默认的邮件服务器地址,defaultEntity用得到

private String smtpHost="smtp.qq.com"; // 邮件服务器地址
private Integer port;//邮件服务器端口号
private String sendUserName; // 发件人的用户名
private String sendUserPass; // 发件人密码

private MimeMessage mimeMsg; // 邮件对象
private Session session;
private Properties props;
private Multipart mp;// 附件添加的组件
private List files = new LinkedList();// 存放附件文件

private void init() {
    if (props == null) {
        props = System.getProperties();
    }
    props.setProperty("mail.smtp.host", smtpHost);
    props.setProperty("mail.smtp.auth", "true"); // 需要身份验证
    final String smtpPort = "587";
    props.setProperty("mail.smtp.port", smtpPort);
    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.socketFactory.port", smtpPort);
    session = Session.getInstance(props);
    // 置true可以在控制台(console)上看到发送邮件的过程
    session.setDebug(true);
    // 用session对象来创建并初始化邮件对象
    mimeMsg = new MimeMessage(session);
    // 生成附件组件的实例
    mp = new MimeMultipart();
}

private Email(String smtpHost, Integer port, String sendUserName, String sendUserPass, String to, String cc, String mailSubject, String mailBody,
              List attachments) {
    this.smtpHost = smtpHost;
    this.sendUserName = sendUserName;
    this.sendUserPass = sendUserPass;
    this.port = port;

    init();
    setFrom(sendUserName);
    setTo(to);
    setCC(cc);
    setBody(mailBody);
    setSubject(mailSubject);
    if (attachments != null) {
        for (String attachment : attachments) {
            addFileAffix(attachment);
        }
    }

}

/**
 * 邮件实体
 *
 * @param smtpHost
 * 邮件服务器地址
 * @param sendUserName
 * 发件邮件地址
 * @param sendUserPass
 * 发件邮箱密码
 * @param to
 * 收件人,多个邮箱地址以半角逗号分隔
 * @param cc
 * 抄送,多个邮箱地址以半角逗号分隔
 * @param mailSubject
 * 邮件主题
 * @param mailBody
 *  邮件正文
 * @param attachments
 *  附件路径
 * @return
 */
public static Email entity(String smtpHost,Integer port, String sendUserName, String sendUserPass, String to, String cc, String mailSubject, String mailBody,
                           List attachments) {
    return new Email(smtpHost,port, sendUserName, sendUserPass, to, cc, mailSubject, mailBody, attachments);
}

/**
 * 默认邮件实体,用了默认的发送帐号和邮件服务器
 *
 * @param to
 *            收件人,多个邮箱地址以半角逗号分隔
 * @param cc
 *            抄送,多个邮箱地址以半角逗号分隔
 * @param subject
 *            邮件主题
 * @param body
 *            邮件正文
 * @param attachments
 *            附件全路径
 * @return
 */
public static Email defaultEntity(String to, String cc, String subject, String body, List attachments) {
    return new Email(defaultSmtpHost,null, defaultSenderName, defaultSenderPass, to, cc, subject, body, attachments);
}

/**
 * 设置邮件主题
 *
 * @param mailSubject
 * @return
 */
private boolean setSubject(String mailSubject) {
    try {
        mimeMsg.setSubject(mailSubject);
    } catch (Exception e) {
        return false;
    }
    return true;
}

/**
 * 设置邮件内容,并设置其为文本格式或HTML文件格式,编码方式为UTF-8
 *
 * @param mailBody
 * @return
 */
private boolean setBody(String mailBody) {
    try {
        BodyPart bp = new MimeBodyPart();
        bp.setContent("" + mailBody, "text/html;charset=UTF-8");
        // 在组件上添加邮件文本
        mp.addBodyPart(bp);
    } catch (Exception e) {
        System.err.println("设置邮件正文时发生错误!" + e);
        return false;
    }
    return true;
}

/**
 * 添加一个附件
 *
 * @param filename
 *            邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常
 * @return
 */
public boolean addFileAffix(String filename) {
    try {
        if (filename != null && filename.length() > 0) {
            BodyPart bp = new MimeBodyPart();
            FileDataSource fileds = new FileDataSource(filename);
            bp.setDataHandler(new DataHandler(fileds));
            bp.setFileName(MimeUtility.encodeText(fileds.getName(), "utf-8", null)); // 解决附件名称乱码
            mp.addBodyPart(bp);// 添加附件
            files.add(fileds);
        }
    } catch (Exception e) {
        System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
        return false;
    }
    return true;
}

/**
 * 删除所有附件
 *
 * @return
 */
public boolean delFileAffix() {
    try {
        FileDataSource fileds = null;
        for (Iterator it = files.iterator(); it.hasNext();) {
            fileds = it.next();
            if (fileds != null && fileds.getFile() != null) {
                fileds.getFile().delete();
            }
        }
    } catch (Exception e) {
        return false;
    }
    return true;
}

/**
 * 设置发件人地址
 *
 * @param from
 *            发件人地址
 * @return
 */
private boolean setFrom(String from) {
    try {
        mimeMsg.setFrom(new InternetAddress(from));
    } catch (Exception e) {
        return false;
    }
    return true;
}

/**
 * 设置收件人地址
 *
 * @param to 收件人的地址
 * @return
 */
private boolean setTo(String to) {
    if (to == null)
        return false;
    try {
        mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    } catch (Exception e) {
        return false;
    }
    return true;
}

/**
 * 设置抄送
 *
 * @param cc
 * @return
 */
private boolean setCC(String cc) {
    if (cc == null) {
        return false;
    }
    try {
        mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
    } catch (Exception e) {
        return false;
    }
    return true;
}

/**
 * 发送邮件
 *
 * @return
 */
public boolean send() throws Exception {
    mimeMsg.setContent(mp);
    //mimeMsg.saveChanges();
    System.out.println("正在发送邮件....");
    Transport transport = session.getTransport("smtp");

// 连接邮件服务器并进行身份验证
// transport.connect(smtpHost,port,sendUserName, sendUserPass);
// 发送邮件
//transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
System.out.println(“发送邮件成功!”);
transport.close();

    Transport.send(mimeMsg);
    System.out.println("发送邮件成功!");
    return true;
}


public static String buildContent(List> list) throws IOException {

    //加载邮件html模板   运行springBootApplication时才能够引用resource下的html模板
    String fileName = "pod-scale-alarm.html";

    String path = System.getProperty("user.dir")+ "\\student\\src\\main\\java\\com\\tjetc\\test01\\pod-scale-alarm.html";
    System.out.println("path = " + path);

    StringBuffer buff=new StringBuffer();

    InputStreamReader in=null;
    BufferedReader br=null;
    File file=new File(path);
    String line = "";
    try {
        //jdk中的输入输出流
        in=new InputStreamReader(new FileInputStream(file));
        br=new BufferedReader(in);
        while((line=br.readLine()) != null){
            //System.out.println(line);
            buff.append(line).append("\n");
        }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        if(in!=null){
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(br!=null){
            try {
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    //InputStream inputStream = ClassLoader.getSystemResourceAsStream(path);
    BufferedReader fileReader = new BufferedReader(in);

    try {
        /*while ((line = fileReader.readLine()) != null) {
            buff.append(line);
        }*/
    } catch (Exception e) {
        LOGGER.error("读取文件失败,fileName:{}", fileName, e);
    } finally {
        //inputStream.close();
        fileReader.close();
    }


    String contentText = "以下是分销平台产品列表信息, 敬请查看.
below is the information of product list on those distribution platforms, please check. "; //邮件表格header String header = "产品名称分销平台名称分销平台产品类别分销平台产品页URL分销平台产品推广URL推广url远程地址ip分销平台产品页页数上架时间更新时间"; StringBuilder linesBuffer = new StringBuilder(); if(list!=null&&list.size()>0) { list.forEach(map -> { linesBuffer.append("" + map.get("productName") + "" + map.get("distributionPlatformName") + "" + map.get("productType") + "" + map.getOrDefault("distributionPlatformDetailUrl","无") + ""+ map.getOrDefault("distributionPlatformProductUrl","无") + ""+ map.getOrDefault("addressIp","无") + ""+ map.getOrDefault("distributionPlatformPageNum","无") + ""+ map.getOrDefault("onShelfTime","无") + "" + map.getOrDefault("updateTime","无") + ""); }); } //颜色 String emailHeadColor = "#fa5834"; String date = DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss"); //填充html模板中的五个参数 String htmlText = MessageFormat.format(buff.toString(), emailHeadColor, contentText, date, header, linesBuffer.toString()); //改变表格样式 htmlText = htmlText.replaceAll("", ""); htmlText = htmlText.replaceAll("", ""); return htmlText; } public static String dddd(){ String userName = "[email protected]"; // 发件人邮箱 String password = "nwjvnvkvlikjefdb"; // 发件人密码(不是登录密码是授权码,需要到邮箱里设置开通授权码功能) String smtpHost = "smtp.exmail.qq.com"; // 邮件服务器 Integer port = 465; // 邮件服务器端口号 String to = "许稷荣"; // 收件人,多个收件人以半角逗号分隔 String cc = "许稷荣"; // 抄送,多个抄送以半角逗号分隔 String subject = "尊敬的自己请查看"; // 主题 List> list = new ArrayList<>(); for(int i=0;i<10;i++){ HashMap dateMap = new HashMap<>(); dateMap.put("productName","魔域"); dateMap.put("productType","页面网游"); dateMap.put("distributionPlatformName","网游社区"); dateMap.put("distributionPlatformDetailUrl","www.baidu.com"); dateMap.put("addressIp","0.0.0.0"); dateMap.put("distributionPlatformPageNum","1"); dateMap.put("onShelfTime","2019-06-28"); dateMap.put("updateTime","2019-06-28"); list.add(dateMap); } String body = null; // 正文,可以用html格式的哟 try { body = Email.buildContent(list); } catch (IOException e) { e.printStackTrace(); } // List attachments = Arrays.asList("D:\\tmp\\1.png", "D:\\tmp\\2.png"); // 附件的路径,多个附件也不怕 System.out.println("body = " + body); return body; //Email email = Email.entity(smtpHost,port, userName, password, to, cc, subject, body, null); //email.send(); // 发送! } public static void main(String[] args) { // 创建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", "[email protected]"); // 此处填写16位STMP口令 props.put("mail.password", "nwjvnvkvlikjefdb"); // 构建授权信息,用于进行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); try { // 设置发件人 InternetAddress form = new InternetAddress(props.getProperty("mail.user")); message.setFrom(form); // 设置收件人的邮箱 InternetAddress to = new InternetAddress("[email protected]"); //InternetAddress to2 = new InternetAddress("[email protected]"); // message.setRecipient(MimeMessage.RecipientType.TO, to2); message.setRecipient(Message.RecipientType.TO,to); //使用UUID自动生成6位验证码 String substring = UUID.randomUUID().toString(); // 设置邮件标题 message.setSubject("来信啦"); String str = Email.dddd(); // 设置邮件的内容体 message.setContent(str, "text/html;charset=UTF-8"); // 设置邮件消息内容、包含附件 /*Multipart msgPart = new MimeMultipart(); message.setContent(msgPart); MimeBodyPart body = new MimeBodyPart();//正文 MimeBodyPart attach = new MimeBodyPart();//附件 msgPart.addBodyPart(body); msgPart.addBodyPart(attach);*/ //设置正文内容 //body.setContent("商品信息见附件","text/html;charset=utf-8"); //设置附件内容 // attach.setDataHandler(new DataHandler(new FileDataSource("c:/Users/17814/Desktop/商品表信息.xls"))); // attach.setFileName((MimeUtility.encodeText("商品表信息.xls"))); message.saveChanges(); //邮件的创建时间 //message.setSentDate(new Date()); // 最后当然就是发送邮件啦 Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } } }

相关文件位置(仅供参考)
使用Java实现给QQ邮箱发送验证码_第1张图片

你可能感兴趣的:(java)