JavaMail 多个收件人

在使用 JavaMail 发送邮件时,有时我们需要将邮件发送给多个收件人。这个功能在实际开发中非常常见,比如群发邮件或者将同一封邮件发送给多个人。本文将介绍如何使用 JavaMail 实现发送邮件给多个收件人的功能。

准备工作

在使用 JavaMail 发送邮件之前,需要添加相关的依赖。可以在 Maven 中添加以下依赖:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.6.2</version>
</dependency>

示例代码

下面是一个简单的示例代码,演示如何使用 JavaMail 发送邮件给多个收件人:

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail {

    public static void main(String[] args) {
        String to = "recipient1@example.com, recipient2@example.com";
        String subject = "Test Email";
        String body = "This is a test email sent to multiple recipients.";

        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.example.com");
        properties.put("mail.smtp.auth", "true");
        
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your-email@example.com", "your-password");
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("your-email@example.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(body);

            Transport.send(message);
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

饼状图

下面是一个使用 mermaid 语法表示的饼状图,展示了邮件的收件人分布情况:

pie
    title Email Recipients
    "Recipient1": 40
    "Recipient2": 30
    "Recipient3": 20
    "Recipient4": 10

结尾

通过上述示例代码,我们可以轻松地实现将邮件发送给多个收件人的功能。在实际开发中,可以根据需求动态设置收件人列表,从而更灵活地发送邮件。希望本文对你有所帮助,祝你的邮件发送顺利!