![](/img/trans.png)
[英]Java mail - No such user exception while sending email to Group email ID
[英]Java Mail: Exception when sending email
第一次使用 java 郵件。 我正在按照本教程進行操作,但我已經無法發送基本消息,並且收到一個非常奇怪的錯誤:
java.util.ServiceConfigurationError: javax.mail.Provider: Provider com.sun.mail.imap.IMAPProvider not a subtype
奇怪,因為我沒有在我的代碼中的任何地方使用 IMAP:
Properties mailProps = new Properties();
mailProps.put("mail.transport.protocol", "smtp");
mailProps.put("mail.host", "smtp.mydomain.com");
mailProps.put("mail.from", "me@mydomain.com");
mailProps.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(mailProps);
SMTPMessage m = new SMTPMessage(session);
MimeMultipart content = new MimeMultipart();
MimeBodyPart mainPart = new MimeBodyPart();
mainPart.setText("test");
content.addBodyPart(mainPart);
m.setContent(content);
m.setSubject("Demo message");
m.setRecipient(RecipientType.TO, new InternetAddress("john@example.com"));
Transport.send(m);
錯誤發生在最后一行(發送)。 我知道 smtp 服務器是正確的並且可以正常工作。
有什么建議為什么會發生以及我該如何解決?
編輯:顯然地址/主機在這里發生了變化,我使用的是在實際代碼中工作的真實地址/主機。
事實證明我遇到了多個問題:
它使用com.sun.mail.smtp.SMTPMessage
但在我的情況下它不起作用但使用javax.mail.internet.MimeMessage
工作正常。
以上代碼在基於 3rd 方 eclipse 的應用程序中運行,它們似乎相互干擾。 可以在此處找到解決方案:
Thread t = Thread.currentThread();
ClassLoader ccl = t.getContextClassLoader();
t.setContextClassLoader(session.getClass().getClassLoader());
try {
Transport.send(m);
} finally {
t.setContextClassLoader(ccl);
}
相應地調整代碼使其工作。
這是發送帶附件的多部分消息的示例:
String from = "from@example.com";
String to = "to@example.com";
File file = new File("/file/to/attach");
Properties mailProps = new Properties();
// put your properties here
Session session = Session.getInstance(mailProps, null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from) );
InternetAddress[] toAddress = { new InternetAddress(to) };
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("Demo Message");
message.setSentDate(new Date());
MimeBodyPart part1 = new MimeBodyPart();
part1.setText("Test");
MimeBodyPart part2 = new MimeBodyPart();
part2.attachFile(file);
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(part1);
multiPart.addBodyPart(part2);
message.setContent(multiPart);
Transport.send(message);
} catch( MessagingException e ) {
// handle the exception properly
e.printStackTrace();
}
希望能幫助到你。
我在libertyCore服務器上遇到了同樣的問題我在server.xml中添加了這個功能,它對我有用
<feature>javaMail-1.6</feature>
java.util.ServiceConfigurationError: jakarta.mail.Provider: com.sun.mail.imap.IMAPProvider not a subtype
我遇到了類似的問題,因為該項目正在使用jakarta.mail
; 其中一個依賴項將javax.mail
作為傳遞依賴項帶來。
排除舊的javax.mail
應該可以解決問題。
<dependency>
<groupId>org.abc</groupId>
<artifactId>xyz</artifactId>
<version>0.0.0</version>
<exclusions>
<exclusion>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</exclusion>
</exclusions>
</dependency>
mvn dependency:tree
查看所有依賴項及其依賴項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.