java实现Google邮箱SMTP协议

发布于:2025-06-12 ⋅ 阅读:(16) ⋅ 点赞:(0)

一、开通Google的SMTP协议

  • 在谷歌邮箱中开启IMAP访问

  •  到google的设置中开启两步验证功能

二、java中实现 

  • 引入maven 
        <!--邮件-->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>
  •  工具类
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * @author LKX
 * @version 1.0
 * @Description
 * @date 2025-06-11 14:10
 */
public class MailUtils {

    public static String USERNAME = "kexianglin261@gmail.com"; //	邮箱发送账号
    public static String PASSWORD = "hrnj tyoi mnie rodo"; //邮箱平台的授权码
    public static String HOST = "smtp.gmail.com"; // SMTP服务器地址
    public static String PORT = "587"; //SMTP服务器端口
    public static Session session = null;

    /**
     * 创建Sesssion
     */
    public static void createSession() {

        if (session != null) return;

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST); //SMTP主机名
        props.put("mail.smtp.port", PORT);

        session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(USERNAME, PASSWORD);
                    }
                });
    }

    /**
     * 发送纯文本邮件,单人发送
     *
     * @param title
     * @param content
     * @param toMail
     */
    public static void postMessage(String title, String content, String toMail) {
        try {
            createSession();
            //构造邮件主体
            MimeMessage message = new MimeMessage(session);
            message.setSubject(title);
            message.setText(content);
            message.setFrom(new InternetAddress(USERNAME));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toMail));
            //发送
            Transport.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param title
     * @param content
     * @param fileName
     * @param filePath
     * @param toMail
     */
    public void postMessageWithFile(String title, String content, String fileName, String filePath, String toMail) {

        try {
            createSession();
            //构造邮件主体
            MimeMessage message = new MimeMessage(session);
            message.setSubject(title);
            //邮件主体
            BodyPart textPart = new MimeBodyPart();
            textPart.setContent(content, "text/html;charset=utf-8");
            //邮件附件
            BodyPart filePart = new MimeBodyPart();
            filePart.setFileName(fileName);
            filePart.setDataHandler(new DataHandler(new ByteArrayDataSource(Files.readAllBytes(Paths.get(filePath)), "application/octet-stream")));

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(filePart);
            message.setContent(multipart);

            message.setFrom(new InternetAddress(USERNAME));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toMail));

            //发送
            Transport.send(message);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}