All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lx.boot.email.EmailUtil Maven / Gradle / Ivy

Go to download

使用文档: https://a7fi97h1rc.feishu.cn/docx/X3LRdtLhkoXQ8hxgXDQc2CLOnEg?from=from_copylink

There is a newer version: 1.1
Show newest version
package com.lx.boot.email;

import com.lx.boot.OS;
import com.lx.constant.DefaultBaseConstant;
import com.lx.util.LX;
import lombok.extern.slf4j.Slf4j;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Slf4j
public class EmailUtil {

    public static void sendEmail(String subject, String content,String... toEmail){
        String smtpMember = OS.getProperty(DefaultBaseConstant.EMAIL_SEND_MEMBER);
        String smtpPassword = OS.getProperty(DefaultBaseConstant.EMAIL_SMTP_PASSWORD);
        String smtpHost = OS.getProperty(DefaultBaseConstant.EMAIL_SMTP_HOST,"smtp.exmail.qq.com");
        String smtpPort = OS.getProperty(DefaultBaseConstant.EMAIL_SMTP_PORT,"465");
        if (LX.isEmpty(smtpMember) || LX.isEmpty(smtpPassword) || LX.isEmpty(toEmail)){
            log.error("邮箱配置信息为空,无法发送!");
            return;
        }
        try{
            log.info("开始发送邮件!");

            Properties properties = new Properties();
            properties.put("mail.transport.protocol", "smtp");
            properties.put("mail.smtp.host", smtpHost);
            properties.put("mail.smtp.port", smtpPort);
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.ssl.enable", "true");
//            properties.put("mail.debug", "true");
            // 得到会话对象
            Session session = Session.getInstance(properties);
            // 获取邮件对象
            Message message = new MimeMessage(session);
            // 设置发件人邮箱地址
            message.setFrom(new InternetAddress(smtpMember));
            // 设置收件人邮箱地址
            InternetAddress[] is = new InternetAddress[toEmail.length];
            for(int i= toEmail.length-1; i>=0 ; i--){
                is[i] = new InternetAddress(toEmail[i]);
            }
            message.setRecipients(Message.RecipientType.TO, is);
            // 设置邮件标题
            message.setSubject(subject);
            // 设置邮件内容
            message.setContent(content,"text/html;charset=utf-8");

            Transport tr = session.getTransport("smtp");
            tr.connect(smtpHost,smtpMember,smtpPassword);

            message.saveChanges();
            tr.sendMessage(message,message.getAllRecipients());
            tr.close();
            log.info("邮件发送成功!");
        }catch (MessagingException e){
            log.error("邮件发送失败!",e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy