java捕捉邮件是否发送成功
时间: 2023-08-25 21:11:08 浏览: 41
在Java中,可以使用JavaMail API来发送邮件,并捕获邮件是否发送成功。以下是一个示例代码段,其中包括如何发送邮件,并捕获任何异常以确定是否成功发送邮件。
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmail {
public static void main(String[] args) {
final String username = "your_email_address";
final String password = "your_email_password";
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");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from_email_address"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to_email_address"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
在上面的代码中,如果邮件成功发送,则会打印“Email sent successfully!”。如果出现任何异常,这些异常将被捕获并抛出RuntimeException。您可以根据需要修改此代码以适应您的要求。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)