java - 使用 javax.mail 读取本地 POP3 收件箱

标签 java email jakarta-mail postfix-mta dovecot

什么是 Java 类似物:

thufir@dur:~$ 
thufir@dur:~$ 
thufir@dur:~$ telnet localhost 110
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Dovecot ready.
user thufir
+OK
pass password
+OK Logged in.
stat
+OK 16 84695
retr 1
+OK 4978 octets
Return-Path: <thufir@dur.bounceme.net>
X-Original-To: thufir@dur
Delivered-To: thufir@dur
Received: from dur.bounceme.net (localhost [127.0.0.1])
    (using TLSv1 with cipher DHE-RSA-AES128-SHA (128/128 bits))
    (No client certificate requested)
    by dur.bounceme.net (Postfix) with ESMTPS id E6A58180508
    for <thufir@dur>; Sun, 26 Aug 2012 06:48:47 -0700 (PDT)
Message-Id: <1027505969.1345988926766.JavaMail.thufir@dur.bounceme.net>
To: thufir@dur
Subject: Google Developers Expert: recognizing and rewarding top developers
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_0_2465937.1345988926695"
Date: Sun, 26 Aug 2012 06:48:47 -0700 (PDT)
From: thufir@dur.bounceme.net

------=_Part_0_2465937.1345988926695
Content-Type: text/html
Content-Transfer-Encoding: 7bit

<img height="80" src="http://2.bp.blogspot.com/-vC8YT1LrWbw/UAW2oUAlvXI/AAAAAAAABt8/Xp5ZDiHi6JQ/s1600/
...
------=_Part_0_2465937.1345988926695--

.
quit
+OK Logging out.
Connection closed by foreign host.
thufir@dur:~$ 

我得到:

init:
Deleting: /home/thufir/NetBeansProjects/leafnode_postfix/build/built-jar.properties
deps-jar:
Updating property file: /home/thufir/NetBeansProjects/leafnode_postfix/build/built-jar.properties
Compiling 1 source file to /home/thufir/NetBeansProjects/leafnode_postfix/build/classes
compile:
run:
DEBUG: nntp: newsrc loading /home/thufir/.newsrc
DEBUG: nntp: newsrc load: 1 groups in 27ms
Show INBOX for thufir@localhost
Exception in thread "main" javax.mail.NoSuchProviderException: Invalid protocol: null
    at javax.mail.Session.getProvider(Session.java:468)
    at javax.mail.Session.getStore(Session.java:546)
    at javax.mail.Session.getStore(Session.java:531)
    at javax.mail.Session.getStore(Session.java:520)
    at net.bounceme.dur.leafnode_postfix.MailClient.checkInbox(Unknown Source)
    at net.bounceme.dur.leafnode_postfix.Main.readMail(Unknown Source)
    at net.bounceme.dur.leafnode_postfix.Main.<init>(Unknown Source)
    at net.bounceme.dur.leafnode_postfix.Main.main(Unknown Source)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

大概问题是我没有正确登录到 dovecot POP3 服务器?如何传递登录凭据?

package net.bounceme.dur.leafnode_postfix;

import java.io.IOException;
import static java.lang.System.out;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailClient extends Authenticator {

    public static final int SHOW_MESSAGES = 1;
    public static final int CLEAR_MESSAGES = 2;
    public static final int SHOW_AND_CLEAR =
            SHOW_MESSAGES + CLEAR_MESSAGES;
    protected String from;
    protected Session session;
    protected PasswordAuthentication authentication;

    public MailClient(UserHost userHost) {
        String user = userHost.getUser();
        String host = userHost.getHost();
        boolean debug = userHost.isDebug();
        from = user + '@' + host;
        authentication = new PasswordAuthentication(user, user);
        Properties props = new Properties();
        props.put("mail.user", user);
        props.put("mail.host", host);
        props.put("mail.debug", debug ? "true" : "false");
        props.put("mail.store.protocol", "pop3");
        props.put("mail.transport.protocol", "smtp");
        session = Session.getDefaultInstance(props);
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return authentication;
    }

    public void sendMessage(Message post) throws MessagingException, IOException {
        Message message = new MimeMessage(session);
        InternetAddress address = new InternetAddress("thufir@dur");
        message.setRecipient(Message.RecipientType.TO, address);
        message.setSubject(post.getSubject());
        Multipart mp = new MimeMultipart();
        BodyPart part = new MimeBodyPart();
        part.setContent(post.getContent(), "text/html");
        mp.addBodyPart(part);
        message.setContent(mp);
        Transport.send(message);
    }

    public void checkInbox(int mode)
            throws MessagingException, IOException {
        if (mode == 0) {
            return;
        }
        boolean show = (mode & SHOW_MESSAGES) > 0;
        boolean clear = (mode & CLEAR_MESSAGES) > 0;
        String action =
                (show ? "Show" : "")
                + (show && clear ? " and " : "")
                + (clear ? "Clear" : "");
        out.println(action + " INBOX for " + from);
        Store store = session.getStore();
        store.connect();
        out.println(store.getDefaultFolder());
        Folder root = store.getDefaultFolder();
        Folder inbox = root.getFolder("inbox");
        inbox.open(Folder.READ_WRITE);
        Message[] msgs = inbox.getMessages();
        if (msgs.length == 0 && show) {
            System.out.println("No messages in inbox");
        }
        for (int i = 0; i < msgs.length; i++) {
            MimeMessage msg = (MimeMessage) msgs[i];
            if (show) {
                System.out.println("    From: " + msg.getFrom()[0]);
                System.out.println(" Subject: " + msg.getSubject());
                System.out.println(" Content: " + msg.getContent());
            }
            if (clear) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }
        }
        inbox.close(true);
        store.close();
        System.out.println();
    }
}

顺便说一句,向本地主机或 dur 发送消息工作正常。完整FQDN是 dur.bounceme.net,尽管在许多情况下 dur 似乎就足够了。我只是在一个盒子上做所有事情,没有在插管上做任何事情。

最佳答案

首先,您发送的电子邮件似乎无效。你有 thufir@dur,你的意思是不是类似于 thufir@dur.com

其次,您需要向 Session 传递适当的信息。您需要进行以下更改:

    authentication = new PasswordAuthentication(user, *pass*);//You must hand it username and pass, not two usernames like before
    Properties props = new Properties();
    props.put("mail.user", user);
    props.put("mail.host", host);
    props.put("mail.debug", debug ? "true" : "false");
    props.put("mail.store.protocol", pop3Provider);//an example provider is pop.gmail.com, or I think aol is pop.aol.com, many follow that pattern, this is used for reading inbox/incoming messages (hence the store)
    props.put("mail.transport.protocol", smtpProvider);//follows same as above, but smtp not pop, this is used for outgoing messages (hence the transport)
    session = Session.getDefaultInstance(props);

我认为这是你的主要问题,告诉我它是如何工作的

关于java - 使用 javax.mail 读取本地 POP3 收件箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131166/

相关文章:

java - 如何使用 EasyMock 模拟从抽象类继承的方法?

PHPMailer 错误调用未定义的方法 PHPMailer::SetFrom()

Java Mail 无法远程工作

java - 将 JavaMail 与自签名证书一起使用

java - 测试已发送的电子邮件 - Dumbster 和 greenmail 未捕获已发送的 JavaMail

java - 使用导入的库运行 jar 文件时出现问题?

java - Java中相同代码的不同输出

java使用相同的 key 加密解密密码md5

PHP 自定义 SMTP 邮件函数返回错误 fputs 发送字节失败 errno=32 Broken pipe

objective-c - MFMailComposeViewController : cancel doesn't exit to my app?