使用javax.mail向BCC收件人发送电子邮件

时间:2014-01-09 08:04:48

标签: java javax.mail

我有以下代码,但我无法弄清楚如何将BCC收件人添加到sendMessage。

有什么想法吗?

           MimeMessage message = new MimeMessage(mailSession);

      String today = new SimpleDateFormat("yyyy-MM-dd").format(Calendar
              .getInstance().getTime());

      message.setSubject("This is my email for:" + today);
      message.setFrom(new InternetAddress("thesender@gmail.com"));
      String []to = new String []{"therecipient1@gmail.com"};
      String []bcc = new String[]{"therecipient2@gmail.com","therecipient3@gmail.com","therecipient4@gmail.com"};
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[0]));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[0]));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[1]));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[2]));
      String body = theBody;
      message.setContent(body,"text/html");
      transport.connect();

        transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
        transport.close();

2 个答案:

答案 0 :(得分:4)

您需要使用以下方法添加多个收件人

public void  addRecipients(Message.RecipientType type, Address[] addresses)

也代替以下行

transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));

试试这个

transport.sendMessage(message,message.getAllRecipients());

答案 1 :(得分:0)

        String [] to=new String[3];
        to[0]="adfsdf@gmail.com";
        to[1]="dffff@gmail.com";
        to[2]="ddddddddddsssssss@outlook.com";
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);

        }


        message.setSubject("Testing ");
        message.setText("dddd,"
            + "\n\n No spam to my email, please!");

        Transport.send(message);