多个收件人只有一个不存在,其他想要发送成功怎么写代码
时间: 2024-03-21 18:43:59 浏览: 15
如果你想在 Java 中向多个收件人发送邮件,但其中某些收件人不存在,你可以通过在代码中使用 try-catch 块来处理这种情况。
以下是一个示例代码,其中包含了向三个收件人发送邮件的代码,并在 try-catch 块中处理了其中一个收件人不存在的情况:
```java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
String from = "youremail@example.com";
String password = "yourpassword";
String to1 = "recipient1@example.com";
String to2 = "recipient2@example.com";
String to3 = "nonexistentrecipient@example.com";
// Set mail properties
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
// Get session
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// Compose message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to1 + "," + to2 + "," + to3));
message.setSubject("Test Email");
message.setText("This is a test email.");
// Send message
Transport.send(message);
System.out.println("Message sent successfully.");
} catch (MessagingException e) {
// Handle exception when recipient doesn't exist
if (e instanceof SendFailedException) {
SendFailedException sfe = (SendFailedException) e;
Address[] invalid = sfe.getInvalidAddresses();
System.out.println("Invalid recipient(s):");
for (int i = 0; i < invalid.length; i++) {
System.out.println(invalid[i]);
}
} else {
e.printStackTrace();
}
}
}
}
```
在这个示例代码中,我们首先设置了发件人邮箱和密码,以及三个收件人的邮箱地址(包括一个不存在的收件人)。然后我们设置了邮件服务器的属性,获取了一个邮件会话对象,并使用 try-catch 块来发送邮件。
在 try 块中,我们首先创建了邮件消息,设置了发件人、收件人、主题和正文内容,并使用 Transport 类的 send() 方法发送了邮件。
如果所有收件人都存在,那么邮件会被成功发送,并且控制台会显示“Message sent successfully.”的消息。但如果某个收件人不存在,那么在 try 块中会抛出 MessagingException 异常,我们在 catch 块中通过判断异常类型来处理这种情况。如果是 SendFailedException 异常,那么说明有收件人不存在,我们可以通过 getInvalidAddresses() 方法获取不存在的收件人地址并输出到控制台中。否则,我们就打印出完整的异常堆栈信息以便调试。
因此,以上示例代码可以在发送邮件时处理收件人不存在的情况,并输出有问题的收件人地址,以便排查问题。