向 POP3 電子郵件伺服器傳送電子郵件

此示例顯示如何建立與啟用 SSL 的 POP3 電子郵件伺服器的連線併傳送簡單(僅文字)電子郵件。

    // Configure mail provider
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.mymailprovider.com");
    props.put("mail.pop3.host", "pop3.mymailprovider.com");
    // Enable SSL
    props.put("mail.pop3.ssl.enable", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // Enable SMTP Authentication
    props.put("mail.smtp.auth","true");

    Authenticator auth = new PasswordAuthentication("user", "password");
    Session session = Session.getDefaultInstance(props, auth);

    // Get the store for authentication
    final Store store;
    try {
        store = session.getStore("pop3");
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException(e);
    }

    try {
        store.connect();
    } catch (AuthenticationFailedException | MessagingException e) {
        throw new IllegalStateException(e);
    }
    
    try {
      // Setting up the mail
      InternetAddress from = new InternetAddress("sender@example.com");
      InternetAddress to = new InternetAddress("receiver@example.com");

      MimeMessage message = new MimeMessage(session);
      message.setFrom(from);
      message.addRecipient(Message.RecipientType.TO, to);

      message.setSubject("Test Subject");
      message.setText("Hi, I'm a Mail sent with Java Mail API.");

      // Send the mail
      Transport.send(message);
    } catch (AddressException | MessagingException e)
        throw new IllegalStateException(e);
    } 

注意事項:

  • 出於說明目的,已將各種細節硬連線到上面的程式碼中。
  • 異常處理不是示例性的。一開始,IllegalStateException 是一個糟糕的選擇。
  • 沒有嘗試正確處理資源