使用JavaMail将邮件发送到多个接收

时间:2011-08-03 09:14:35

标签: java javamail

    try
    {    
        String s1 = "example@gmail.com"; //sender (from)
        String s2 = request.getParameter("email");// (from jsp i am taking)


        String s3 = "testing mail"; (subject)
        String s4 = "hi.."; (message)

        Properties props=new Properties();

        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("sender ID","password");
                    }
                });


        Message message =new MimeMessage(session);

        message.setFrom(new InternetAddress(s1));
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(s2));
        message.setSubject(s3);
        message.setText(s4);

        Transport.send(message);
    }
    catch(Exception ex)
    {
        System.out.println("ERROR....."+ex);
    }

在此代码中,我从JSP获取的请求参数的电子邮件可能不止一个,因为电子邮件地址来自数据库。

如何使用JavaMail向多个收件人发送相同的电子邮件?

1 个答案:

答案 0 :(得分:3)

没有什么特别的,要将它发送给多个用户,您需要在属性InternetAddress中传递Message.RecipientType.TO数组。