Javamail问题: cannot send mails through SMTP after checking mails with POP3

标签 java smtp jakarta-mail pop3

所以,我的问题如下:我有一个用 Java 编写的邮件客户端,在使用 POP3 检查邮件后,无法通过 SMTP 发送邮件。

我捕获的异常表明传输协议(protocol) = null。

代码工作正常,因为在 POP3 连接之前没有任何问题。我确定我关闭了该连接,并且它们都是私有(private)函数,因此变量彼此无效。

希望我告诉了一切。

感谢您的任何想法。

代码:

pop3 连接

  // Connect to the POP3 server
  Session session = Session.getDefaultInstance(props, null);
  Store store = session.getStore("pop3");
  store.connect(host, username, password);

  // Open the folder
  Folder inbox = store.getFolder("INBOX");

  inbox.open(Folder.READ_ONLY);

  // Get the messages from the server
  Message[] messages = inbox.getMessages();


  fromMailAddress.setText(userAccount);

  // Close the connection
  // but don't remove the messages from the server
  inbox.close(false);
  store.close();
  props.clear();
    }
catch (Exception ex) {
     JOptionPane.showMessageDialog(null,"user input error", "error", JOptionPane.ERROR_MESSAGE);


    }

smtp - 邮件发送

    Properties property = new Properties();
    property.setProperty("mail.transport.protocol", "smtp");
    property.setProperty("mail.host", "mymailserver");
    property.setProperty("mail.user", "myusername");
    property.setProperty("mail.password", "mypassword");
    Session mailSession = Session.getDefaultInstance(property, null);
    mailSession.setDebug(true);
try{
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("HTML  mail with images");
    message.setFrom(new InternetAddress("myaddress@gmail.com"));
    message.setContent("<h1>Hello world</h1>", "text/html");
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress("xyz@gmail.com"));

    transport.connect();
    transport.sendMessage(message,
        message.getRecipients(Message.RecipientType.TO));
    transport.close();
    property.clear();
    }
    catch(Exception ex)
    {

            JOptionPane.showMessageDialog(null,"e-mail sending failed", "Error", JOptionPane.ERROR_MESSAGE);
    }

最佳答案

您的 pop 和 smtp 模块不是独立的:它们共享默认 session 。您最好创建自己的 session ,一个用于 pop,一个用于 smtp,而不是依赖 javamail 的默认 session (Session.getDefaultInstance)。

关于Javamail问题: cannot send mails through SMTP after checking mails with POP3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1897633/

相关文章:

Java Mail 身份验证和连接

java - Camel 路线未在 xml 文件中解析

java - 发件人地址不正确

email - 我应该用什么方法发送带有 Airflow 的电子邮件?

python - 如何将 smtp 调试信息记录到文件中?

JavaMail InputStream 附件需要很长时间

java - 如何在 Joda Time/Java 8 中列出时区偏移量、时区 ID 和长名称?

java - 链表返回值

java - 从命令行向 java 程序传递值,它是如何工作的?

java - 错误 : Warnings found during shrinking, 请使用 -dontwarn 或 -ignorewarnings 来抑制它们