java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java邮箱SMTP协议

java实现Google邮箱SMTP协议的示例代码

作者:Lin_XXiang

这篇文章主要为大家详细介绍了如何使用java实现Google邮箱SMTP协议,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下

一、开通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);
        }
    }
}

到此这篇关于java实现Google邮箱SMTP协议的示例代码的文章就介绍到这了,更多相关java邮箱SMTP协议内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文