首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用javax.mail发送给多个收件人

,可以通过以下步骤实现:

  1. 导入javax.mail库:在项目中导入javax.mail库,以便使用相关的类和方法。
  2. 创建邮件会话:使用javax.mail.Session类创建一个邮件会话对象。可以通过设置SMTP服务器地址、端口号、认证信息等来配置会话。
  3. 创建邮件消息:使用javax.mail.Message类创建一个邮件消息对象。设置邮件的发送者、收件人、主题、内容等信息。
  4. 设置收件人:使用javax.mail.Message类的addRecipient()方法,将多个收件人添加到邮件消息中。可以通过设置Message.RecipientType.TO来指定收件人类型为主要收件人。
  5. 设置邮件内容:使用javax.mail.Message类的setText()方法,设置邮件的内容。
  6. 发送邮件:使用javax.mail.Transport类的send()方法,将邮件消息发送出去。

以下是一个示例代码:

代码语言:java
复制
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {
    public static void main(String[] args) {
        // 邮件服务器配置
        String host = "smtp.example.com";
        String username = "your_username";
        String password = "your_password";

        // 收件人列表
        List<String> recipients = new ArrayList<>();
        recipients.add("recipient1@example.com");
        recipients.add("recipient2@example.com");
        recipients.add("recipient3@example.com");

        // 邮件内容
        String subject = "Hello";
        String content = "This is a test email.";

        // 创建邮件会话
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            for (String recipient : recipients) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            }
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            System.out.println("Email sent successfully.");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

在上述示例代码中,需要替换以下内容:

  • host: SMTP服务器地址。
  • username: 发件人的邮箱用户名。
  • password: 发件人的邮箱密码。
  • recipients: 收件人的邮箱地址列表。
  • subject: 邮件主题。
  • content: 邮件内容。

推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses

请注意,以上示例代码仅为演示如何使用javax.mail发送给多个收件人,实际应用中可能需要根据具体情况进行适当的修改和调整。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券