java如何捕捉邮件发送不存在的邮箱
时间: 2023-10-18 10:09:13 浏览: 191
Java可以使用JavaMail API来发送电子邮件,同时也可以通过该API捕获邮件发送时出现的异常。如果尝试发送邮件到不存在的电子邮箱,JavaMail会抛出SendFailedException
异常。可以通过捕获该异常来处理这种情况。
下面是一个示例代码:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class EmailSender {
public static void main(String[] args) {
String to = "example@example.com"; // 不存在的邮箱
String from = "sender@example.com";
String host = "smtp.example.com";
// 设置邮件发送属性
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
// 获取默认会话对象
Session session = Session.getDefaultInstance(properties);
try {
// 创建消息对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(from));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置主题
message.setSubject("Test Email");
// 设置消息内容
message.setText("This is a test email.");
// 发送消息
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (SendFailedException e) {
System.out.println("Failed to send email: " + e.getMessage());
Address[] invalidAddresses = e.getInvalidAddresses();
if (invalidAddresses != null) {
for (Address address : invalidAddresses) {
System.out.println("Invalid address: " + address.toString());
}
}
} catch (MessagingException e) {
System.out.println("Failed to send email: " + e.getMessage());
}
}
}
在上面的代码中,如果发送到不存在的电子邮箱,Transport.send()
方法会抛出SendFailedException
异常。在捕获该异常后,可以通过调用getInvalidAddresses()
方法来获取无效的电子邮件地址,并进行处理。
相关推荐


















