邮箱发送验证码工具类

1.邮箱支持引入到pom

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
      <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-core</artifactId>
            <version>5.4.0</version>
        </dependency>

 

2.验证码生成,随机数

 String verifCode = RandomUtil.randomNumbers(6);

3.邮箱发送验证码工具类

 

package com.mp.common.core.utils;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;

/**
 * @author Ling
 * @description: TODO 发送邮件工具类
 * @date 2020/3/19 15:11
 */
public class EmailSendUtils {

    /**
     * gmail邮箱
     */
    static String username = "邮箱";
    /**
     * 密码
     */
    static String password = "密码";

    /**
     * 反馈邮件邮箱
     */
    static String contactUsEmail = "contact@kiri-innov.com";

    /*
     * gmail邮箱SSL方式
     */
    private static void gmailssl(Properties props) {
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        props.put("mail.debug", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
    }


    //gmail邮箱的TLS方式
    private static void gmailtls(Properties props) {
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
    }


    /**
     * 通过gmail邮箱发送邮件
     *
     * @param email 邮箱
     */
    public static void gmailSenderEnglish(String email, String content) {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("pet App");
            String tips = "respected user: \n" +
                    "Hello and welcome xiaoming, thank you for your registration.We are happy to start to get to know you better, Your login \n" +
                    "email is " + email + ". Please fill in the following 6-digit verification code:\n"
                    + content + "\n" +
                    "The verification code is valid within 30 minutes, please do not reply to this email, thank you!";
            msg.setText(tips);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过gmail邮箱发送邮件
     *
     * @param email 邮箱
     */
    public static void gmailSenderChina(String email, String content) {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("pet App");
            String tips = "尊敬的用户: \n" +
                    "你好,欢迎使用, 我们很高兴开始更好地了解您,您的登录 \n" +
                    "邮箱为 " + email + ". 请回填如下6位验证码:\n"
                    + content + "\n" +
                    "验证码在30分钟内有效,请勿回复此电子邮件,谢谢!";
            msg.setText(tips);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过gmail邮箱发送邮件
     *
     * @param email 邮箱
     */
    public static void gmailSenderSpain(String email, String content) {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("pet App");
            String tips = "usuario respetado: \n" +
                    "Hola y bienvenido,  gracias por tu registro. Estamos felices de empezar a conocerte mejor\n" +
                    "Su correo electrónico de inicio de sesión es " + email + ". Complete el siguiente código de verificación de 6 dígitos:\n"
                    + content + "\n" +
                    "El código de verificación es válido en 30 minutos, no responda a este correo electrónico, ¡gracias! ";
            msg.setText(tips);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过gmail邮箱发送邮件
     *
     * @param email 邮箱
     */
    public static void gmailSenderFrench(String email, String content) {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("pet App");
            String tips = "utilisateur respecté: \n" +
                    "Bonjour et bienvenue, merci pour votre inscription. Nous sommes heureux de commencer à mieux vous connaître" +
                    "Votre email de connexion est  " + email + ". Veuillez remplir le code de vérification à 6 chiffres suivant:\n"
                    + content + "\n" +
                    "Le code de vérification est valable dans les 30 minutes, merci de ne pas répondre à cet e-mail, merci ! ";
            msg.setText(tips);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过gmail邮箱发送邮件
     *
     * @param email 邮箱
     */
    public static void gmailSenderTurkey(String email, String content) {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("pet App");
            String tips = "saygıdeğer kullanıcı: \n" +
                    "Merhaba ve hoşgeldiniz, kaydınız için teşekkür ederiz. Sizi daha yakından tanımaya başladığımız için mutluyuz" +
                    " Giriş e-postanız  " + email + "'dur. Lütfen aşağıdaki 6 haneli doğrulama kodunu doldurun:\n"
                    + content + "\n" +
                    "Doğrulama kodu 30 dakika içinde geçerlidir, lütfen bu e-postayı yanıtlamayın, teşekkür ederiz!";
            msg.setText(tips);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过gmail邮箱发送注册邮件
     *
     * @param email 邮箱
     */
    public static void gMailRegisterSender(String email, String content) {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("Phiz App");
            String tips = "Thank you for using Phiz App. Please click below link to complete your request.\n\n\n" +
                    "Thank you for using Phiz App. Please click below link to complete your request. this link expires in 15 minutes.\n\n\n";
            msg.setText(tips + content);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过gmail邮箱发送邮件
     *
     * @param email 邮箱
     */
    public static void gmailSenderHtml(String email, String content) throws MessagingException {
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(content, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setSubject("Phiz App");
//            msg.setText(content);
            msg.setContent(mainPart);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * gmail发送用户反馈邮件
     *
     * @param feedBackEmail 用户名
     * @param type          类型
     * @param time          时间
     * @param content       内容
     */
    public static void gmailSendConstUs(String name, String feedBackEmail, String type, String time, String content) {
//        反馈用户:XXX
//        反馈类型:XXX
//        反馈时间:XXX
//        反馈内容:XXX
        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailssl(props);
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(contactUsEmail));
            msg.setSubject("Contact us");
            name = "反馈用户:" + name + "\n\n";
            feedBackEmail = "反馈用户邮箱:" + feedBackEmail + "\n\n";
            type = "反馈类型:" + type + "\n\n";
            time = "反馈时间:" + time + "\n\n";
            msg.setText(name + feedBackEmail + type + time + content);
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

posted @   码海兴辰  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示