更新时间:2024-12-12 GMT+08:00

Email消息的SMTP调用代码示例(Java)

本章节以Java代码为例,如调用代码示例,如果不满足使用,可参见单次连接(多次发送)发送邮件带附件示例

JDK推荐1.8及以上。

前提条件

已通过Email消息的控制台获取发信地址

已同KooMessage的运营人员获取SMTP账号和密码。

支持的SMTP服务端与端口

 private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
 private static final String SMTP_PORT = "465";

调用代码示例

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
 
public class SampleMail {
    private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
    private static final String SMTP_PORT = "465";
 
    public static void main(String[] args) {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // SMTP通过SSL保证安全,如果不想导入KM证书,需要添加下行代码
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        // 如果使用ssl,则去掉使用25端口的配置,进行如下配置,
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.port", SMTP_PORT);
        // 发件人的SMTP账号,将username替换为Koomessage运营提供的SMTP账号
        props.put("mail.user", "username");
        // 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置),将password替换为Koomessage运营提供的SMTP密码
        props.put("mail.password", "password");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.starttls.enable","true");
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // mailSession.setDebug(true);
        // UUID uuid = UUID.randomUUID();
        // final String messageIDValue = "<" + uuid.toString() + ">";
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            //设置自定义Message-ID值
            //setHeader("Message-ID", messageIDValue);
            //}
        };
        try {
            // 设置发件人邮件地址和名称。填写控制台配置的发信地址,比如test@qq.com。和上面的mail.user保持一致。名称用户可以自定义填写。
            InternetAddress from = new InternetAddress("test@qq.com", "test");
            message.setFrom(from);
            //可选。设置回信地址
            //Address[] a = new Address[1];
            //a[0] = new InternetAddress("***");
            //message.setReplyTo(a);
            // 设置收件人邮件地址,比如yyy@yyy.com
            InternetAddress to = new InternetAddress("xxx@xxx.com");
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            //如果同时发给多人,才将上面两行替换为如下(因为部分收信系统的一些限制,尽量每次投递给一个人;同时我们限制单次允许发送的人数是50人):
            //InternetAddress[] adds = new InternetAddress[2];
            //adds[0] = new InternetAddress("xxx@xxx.com");
            //adds[1] = new InternetAddress("xxx@xxx.com");
            //message.setRecipients(Message.RecipientType.TO, adds);
 
            // 设置邮件标题
            message.setSubject("测试邮件");
            message.setHeader("Content-Transfer-Encoding", "base64");
            // 设置邮件的内容体 type: text/plain(纯文本)text/html(HTML 文档)
            message.setContent("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>hello world</title>\n</head>\n<body>\n " + "<h1>我的第一个标题</h1>\n    <p>我的第一个段落。</p>\n</body>\n</html>", "text/html;charset=UTF-8");
            //发送邮件
            Transport.send(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            String err = e.getMessage();
            err = new String(err.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println(err);
        }
    }
}

单次连接(多次发送)

如果使用单次连接,多次发送,可参考以下示例,提高发送性能。

import jakarta.mail.Authenticator;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
 
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
 
public class SampleMail {
    private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
 
    private static final String SMTP_PORT = "465";
 
    public static void main(String[] args) {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // SMTP通过SSL保证安全,如果不想导入KM证书,需要添加下行代码
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        // 如果使用ssl,则去掉使用25端口的配置,进行如下配置
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.port", SMTP_PORT);
        // 发件人的SMTP账号,将username替换为Koomessage运营提供的SMTP账号
        props.put("mail.user", "username");
        // 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置),将password替换为Koomessage运营提供的SMTP密码
        props.put("mail.password", "password");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.starttls.enable","true");
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // mailSession.setDebug(true);
        // UUID uuid = UUID.randomUUID();
        // final String messageIDValue = "<" + uuid.toString() + ">";
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            //设置自定义Message-ID值
            //setHeader("Message-ID", messageIDValue);
            //}
        };
        Transport transport = null;
        try {
            // 设置发件人邮件地址和名称。填写控制台配置的发信地址,比如test@qq.com。和上面的mail.user保持一致。名称用户可以自定义填写。
            transport = mailSession.getTransport();
            transport.connect(props.getProperty("mail.user"), props.getProperty("mail.password"));
            List<String> toList = Arrays.asList("xxx1@xx.com", "xxx2@xx.com", "xxx3@xx.com");
            for (String to : toList) {
                InternetAddress from = new InternetAddress("jwl6C@kmemailtest.cn", "test");
                message.setFrom(from);
                //可选。设置回信地址
                //Address[] a = new Address[1];
                //a[0] = new InternetAddress("***");
                //message.setReplyTo(a);
                // 设置收件人邮件地址,比如yyy@yyy.com
                InternetAddress toAddress = new InternetAddress(to);
                message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
                //如果同时发给多人,才将上面两行替换为如下(因为部分收信系统的一些限制,尽量每次投递给一个人;同时我们限制单次允许发送的人数是50人):
                //InternetAddress[] adds = new InternetAddress[2];
                //adds[0] = new InternetAddress("xxx@xxx.com");
                //adds[1] = new InternetAddress("xxx@xxx.com");
                //message.setRecipients(Message.RecipientType.TO, adds);
 
                // 设置邮件标题
                message.setSubject("测试邮件");
                message.setHeader("Content-Transfer-Encoding", "base64");
                // 设置邮件的内容体 type: text/plain(纯文本)text/html(HTML 文档)
                message.setContent(
                    "<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>hello world</title>\n</head>\n<body>\n "
                        + "<h1>我的第一个标题</h1>\n    <p>我的第一个段落。</p>\n</body>\n</html>",
                    "text/html;charset=UTF-8");
                //发送邮件
                transport.sendMessage(message, message.getAllRecipients());
            }
 
        } catch (MessagingException | UnsupportedEncodingException e) {
            String err = e.getMessage();
            err = new String(err.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println(err);
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    String err = e.getMessage();
                    err = new String(err.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    System.out.println(err);
                }
            }
        }
    }
}

发送邮件带附件示例

import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.FileDataSource;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
 
import java.util.Properties;
 
public class SendEmailWithAttachment {
 
    private static final String SMTP_HOST = "sg-smtp.koomessage.7k2k1.cn";
 
    private static final String SMTP_PORT = "465";
 
    public static void main(String[] args) {
 
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        // 如果使用ssl,则去掉使用25端口的配置,进行如下配置,
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.port", SMTP_PORT);
        // 发件人的SMTP账号,将username替换为Koomessage运营提供的SMTP账号
        props.put("mail.user", "username");
        // 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置),将password替换为Koomessage运营提供的SMTP密码
        props.put("mail.password", "password");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.enable", "true");
        //props.put("mail.smtp.starttls.enable","true");
        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // UUID uuid = UUID.randomUUID();
        // final String messageIDValue = "<" + uuid.toString() + ">";
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession) {
            //@Override
            //protected void updateMessageID() throws MessagingException {
            //设置自定义Message-ID值
            //setHeader("Message-ID", messageIDValue);
            //}
        };
 
        try {
            // 创建消息
            message.setFrom(new InternetAddress("xxxx@xx"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xxxx@xx"));
            message.setSubject("Subject: Test Email with Attachment");
 
            // 创建消息体
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText("This is the email body");
 
            // 创建附件部分
            MimeBodyPart attachmentPart = new MimeBodyPart();
            DataSource source = new FileDataSource("path/to/attachment.txt"); // 附件路径
            attachmentPart.setDataHandler(new DataHandler(source));
            attachmentPart.setFileName("attachment.txt"); // 附件名称
 
            // 组合消息体和附件
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            multipart.addBodyPart(attachmentPart);
 
            message.setContent(multipart);
 
            // 发送邮件
            Transport.send(message);
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}