共計 1310 個字符,預計需要花費 4 分鐘才能閱讀完成。
在 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”,并附上錯誤信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完