Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send mail to multiple receptions using JavaMail

    try
    {    
        String s1 = "[email protected]"; //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);
    }

In this code, the email which I am taking as request parameter from JSP can be more than one, because the email address is coming from database.

How can I send the same email to multiple recipients using JavaMail?


1 Answers

Nothing special, to send it to multiple users you need to pass array of InternetAddress in the property Message.RecipientType.TO.

like image 132
Parth Avatar answered Mar 19 '26 09:03

Parth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!