向 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 是一个糟糕的选择。
  • 没有尝试正确处理资源