所以,我的问题如下:我有一个用 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/