在Java中发送邮件时,可以使用JavaMail API来发送邮件。发送邮件后,可以通过检查发送结果来获取结果。以下是一个示例代码,演示如何发送邮件并获取发送结果:
import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class SendEmail { public static void main(String[] args) { // 配置邮件服务器 Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.example.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); // 创建Session对象 Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your-email@example.com", "your-password"); } }); try { // 创建Message对象 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your-email@example.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com")); message.setSubject("Hello, World!"); message.setText("This is a test email."); // 发送邮件 Transport.send(message); // 邮件发送成功 System.out.println("Email sent successfully!"); } catch (MessagingException e) { // 邮件发送失败 System.out.println("Email sending failed: " + e.getMessage()); } } }
在上面的代码中,使用JavaMail API配置了邮件服务器,并创建了一个Session对象。通过在Session对象中传递用户名和密码,实现了身份验证。然后,创建了一个Message对象,设置了发件人、收件人、主题和正文。最后,调用Transport.send()
方法发送邮件。
如果邮件发送成功,将打印"Email sent successfully!“。如果邮件发送失败,将打印"Email sending failed”,并附上错误信息。