send email java example

java发邮箱实例   ,可以开发邮箱验证码系统 


/**
 * Copyright (C), 2018-2019, XXX有限公司
 * FileName: SendMailText
 * Author:   1543057945
 * Date:     2019/1/7 21:45
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 张良敏         修改时间           版本号              描述
 */
package RegistAndLogin.Utils;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author 1543057945
 * @create 2019/1/7
 * @since 1.0.0
 */


import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.util.*;

public class SendMailText {
    public static void main(String[] args){
        sendMail("[email protected]");
        InputStream resourceAsStream = SendMailText.class.getClassLoader().getResourceAsStream("mail.properties");
        Properties properties=new Properties();
        try {
            properties.load(resourceAsStream);
            OutputStream outputStream = new FileOutputStream("1.xml");
            properties.storeToXML(outputStream,"","utf-8");
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //发件人地址
    public static String senderAddress = "[email protected]";
    //收件人地址
    //public static String recipientAddress = "[email protected]";
    //发件人账户名
    public static String senderAccount = "1543057945";
    //发件人账户密码
    public static String senderPassword = "avtbhedhsfjciehe";

    public static String sendMail (String recipientAddress){
        //1、连接邮件服务器的参数配置
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //设置调试信息在控制台打印出来
        //session.setDebug(true);
        Transport transport = null;
        String code=null;
        try {
            code=getCode();
            //3、创建邮件的实例对象
            Message msg = getMimeMessage(session,code,recipientAddress);
            //4、根据session对象获取邮件传输对象Transport
            transport = session.getTransport();
            //设置发件人的账户名和密码
            transport.connect(senderAccount, senderPassword);
            //发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(msg,msg.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //如果只想发送给指定的人,可以如下写法
            //transport.sendMessage(msg, new Address[]{new InternetAddress("[email protected]")});
            try {
                //5、关闭邮件连接
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        return code;
    }

    /**
     * 获得创建一封邮件的实例对象
     * @param session 发送一次相当于与服务器建立一次会话
     *         code 获得生成的验证码
     *         recipientAddress  接收人的邮箱地址
     * @return 验证码
     * @throws MessagingException
     * @throws AddressException
     */
    public static MimeMessage getMimeMessage(Session session,String code,String recipientAddress) throws Exception{
        //创建一封邮件的实例对象
        MimeMessage msg = new MimeMessage(session);
        //设置发件人地址
        msg.setFrom(new InternetAddress(senderAddress));
        /**
         * 设置收件人地址(可以增加多个收件人、抄送、密送),即下面这一行代码书写多行
         * MimeMessage.RecipientType.TO:发送
         * MimeMessage.RecipientType.CC:抄送
         * MimeMessage.RecipientType.BCC:密送
         */
        msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(recipientAddress));
        //设置邮件主题
        msg.setSubject("系统验证码","UTF-8");
        //设置邮件正文
        msg.setContent("你本次验证码为:<font style=\"color:red;background:yellow\">"+code+"</font>", "text/html;charset=UTF-8");
        //设置邮件的发送时间,默认立即发送
        msg.setSentDate(new Date());
        return msg;
    }
    public static String getCode(){
        Random rd=new Random();
        String code = "";
        for (int i = 0; i <6 ; i++) {
            code+=rd.nextInt(9)+"";
        }
        return code;
    }

}
```
Published 34 original articles · won praise 6 · views 3664

Guess you like

Origin blog.csdn.net/qq_35986709/article/details/86375758