Java Email is sent with no content and not attachment when sending email from WSO2.

huangapple go评论107阅读模式
英文:

Java Email is sent with no content and not attachment when sending email from WSO2

问题

It seems like you're encountering an issue with sending emails with attachments using WSO2 class mediator. The exception you're seeing, "javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed," suggests a problem with handling the attachment data type.

To resolve this issue, you can try adding the following code, which you mentioned in your "EDIT" section:

  1. MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
  2. mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  3. mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  4. mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  5. mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  6. mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  7. mc.addMailcap("multipart/report;; x-java-content-handler=com.sun.mail.dsn.multipart_report");
  8. mc.addMailcap("message/delivery-status;; x-java-content-handler=com.sun.mail.dsn.message_deliverystatus");
  9. mc.addMailcap("message/disposition-notification;; x-java-content-handler=com.sun.mail.dsn.message_dispositionnotification");
  10. mc.addMailcap("text/rfc822-headers;; x-java-content-handler=com.sun.mail.dsn.text_rfc822headers");

This code configures the MailcapCommandMap to handle various MIME types correctly, which might help resolve the issue you're facing.

After adding this code, please try sending the email again and see if it resolves the problem.

英文:

I am trying to send email from WSO2 class mediator, when sending the email with no attachment it works fine but when sending with attachment I get the following exception:

  1. javax.mail.MessagingException: IOException while sending message;
  2. nested exception is:
  3. javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;

I am using micro-integrator 4.1.0

The java code to send the email with attachment is as follows:

  1. emailHostSMTPs = getConfig("email.host.smtps");
  2. emailHostSMTP = getConfig("email.host.smtp");
  3. emailProtocol = getConfig("email.protocol");
  4. senderEmail = getConfig("email.sender");
  5. senderPassword = Encryptor.decrypt(getConfig("email.password"));
  6. senderUser = getConfig("email.sender.user");
  7. emailPort = getConfig("email.port");
  8. MimeMultipart multipart = new MimeMultipart();
  9. Authenticator authenticator = new SMTPAuthenticator();
  10. MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
  11. MimeBodyPart bodyPart = new MimeBodyPart();
  12. String html = "";
  13. Properties props = System.getProperties();
  14. props.put("mail.transport.protocol", emailProtocol);
  15. props.put("mail.smtp.host", emailHostSMTP);
  16. props.put("mail." + emailProtocol + ".auth", "true");
  17. props.put("mail.smtp.port", emailPort);
  18. sslSocketFactory.setTrustAllHosts(true);
  19. props.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
  20. Session session = Session.getInstance(props, authenticator);
  21. html = "<html><body dir='rtl' style='font-size:12pt;color:#000000;background-color:#FFFFFF;font-family:Calibri,Arial,Helvetica,sans-serif;'> "
  22. + emailBody + " </body></html>";
  23. bodyPart.setContent(html, "text/html; charset=UTF-8");
  24. multipart.addBodyPart(bodyPart);
  25. MimeMessage message = new MimeMessage(session);
  26. message.setFrom(new InternetAddress(senderEmail, fromDisplayName));
  27. message.setReplyTo(new Address[] { new InternetAddress(fromEmail) });
  28. if (toList != null && toList.size() > 0) {
  29. for (String to : toList) {
  30. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
  31. }
  32. } else {
  33. throw new Exception("List of users to send email to is empty");
  34. }
  35. if (ccList != null && ccList.size() > 0) {
  36. for (String cc : ccList) {
  37. message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
  38. }
  39. }
  40. if (bccList != null && bccList.size() > 0) {
  41. for (String bcc : bccList) {
  42. message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
  43. }
  44. }
  45. MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("base64");
  46. mimeBodyPart.setContent(fileDataStrBase64, "application/*");
  47. mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, "utf-8", "B"));
  48. multipart.addBodyPart(mimeBodyPart);
  49. message.setSubject(subject, "UTF-8");
  50. message.setContent(multipart);
  51. message.setSentDate(new Date());
  52. Transport transport = session.getTransport(emailProtocol);
  53. transport.connect(senderEmail, senderPassword);
  54. transport.sendMessage(message, message.getAllRecipients());

My class mediator is deployed as jar file inside MI_HOME/lib

jars used:

  • javax.mail-1.6.2.jar
  • activation-1.1.1.jar

JDK Version : 11.0.8

EDIT:

After adding the following code (from another post) the email is sent but I get no email content and no attachment just subject !

  1. MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
  2. mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
  3. mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
  4. mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
  5. mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
  6. mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
  7. mc.addMailcap("multipart/report;; x-java-content-handler=com.sun.mail.dsn.multipart_report");
  8. mc.addMailcap("message/delivery-status;; x-java-content-handler=com.sun.mail.dsn.message_deliverystatus");
  9. mc.addMailcap("message/disposition-notification;; x-java-content-handler=com.sun.mail.dsn.message_dispositionnotification");
  10. mc.addMailcap("text/rfc822-headers;; x-java-content-handler=com.sun.mail.dsn.text_rfc822headers");

Below is the mail debug:

  1. DEBUG: failed to load any providers, using defaults
  2. DEBUG: Tables of loaded providers from javamail.providers
  3. DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle,1.6.2], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle,1.6.2], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle,1.6.2], com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle,1.6.2], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle,1.6.2], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle,1.6.2]}
  4. DEBUG: Providers Listed By Protocol: {imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle,1.6.2], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle,1.6.2], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle,1.6.2], imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle,1.6.2], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle,1.6.2], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle,1.6.2]}
  5. DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle,1.6.2]
  6. DEBUG SMTP: need username and password for authentication
  7. DEBUG SMTP: protocolConnect returning false, host=mail.mydomain.com, user=myemail, password=<null>
  8. DEBUG SMTP: useEhlo true, useAuth true
  9. DEBUG SMTP: trying to connect to host "mail.mydomain.com", port 587, isSSL false
  10. 220 MyMailServer Microsoft ESMTP MAIL Service ready at Sun, 28 May 2023 14:33:31 +0300
  11. DEBUG SMTP: connected to host "mail.mydomain.com", port: 587
  12. EHLO host.docker.internal
  13. 250-MyMailServer Hello [10.x.x.x]
  14. 250-SIZE 41943040
  15. 250-PIPELINING
  16. 250-DSN
  17. 250-ENHANCEDSTATUSCODES
  18. 250-STARTTLS
  19. 250-AUTH GSSAPI NTLM
  20. 250-8BITMIME
  21. 250-BINARYMIME
  22. 250 CHUNKING
  23. DEBUG SMTP: Found extension "SIZE", arg "41943040"
  24. DEBUG SMTP: Found extension "PIPELINING", arg ""
  25. DEBUG SMTP: Found extension "DSN", arg ""
  26. DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
  27. DEBUG SMTP: Found extension "STARTTLS", arg ""
  28. DEBUG SMTP: Found extension "AUTH", arg "GSSAPI NTLM"
  29. DEBUG SMTP: Found extension "8BITMIME", arg ""
  30. DEBUG SMTP: Found extension "BINARYMIME", arg ""
  31. DEBUG SMTP: Found extension "CHUNKING", arg ""
  32. STARTTLS
  33. 220 2.0.0 SMTP server ready
  34. EHLO host.docker.internal
  35. 250-MyMailServer Hello [10.x.x.x]
  36. 250-SIZE 41943040
  37. 250-PIPELINING
  38. 250-DSN
  39. 250-ENHANCEDSTATUSCODES
  40. 250-AUTH GSSAPI NTLM LOGIN
  41. 250-8BITMIME
  42. 250-BINARYMIME
  43. 250 CHUNKING
  44. DEBUG SMTP: Found extension "SIZE", arg "41943040"
  45. DEBUG SMTP: Found extension "PIPELINING", arg ""
  46. DEBUG SMTP: Found extension "DSN", arg ""
  47. DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
  48. DEBUG SMTP: Found extension "AUTH", arg "GSSAPI NTLM LOGIN"
  49. DEBUG SMTP: Found extension "8BITMIME", arg ""
  50. DEBUG SMTP: Found extension "BINARYMIME", arg ""
  51. DEBUG SMTP: Found extension "CHUNKING", arg ""
  52. DEBUG SMTP: protocolConnect login, host=mail.mydomain.com, user=mysenderemail, password=<non-null>
  53. DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2
  54. DEBUG SMTP: Using mechanism LOGIN
  55. DEBUG SMTP: AUTH LOGIN command trace suppressed
  56. DEBUG SMTP: AUTH LOGIN succeeded
  57. DEBUG SMTP: use8bit false
  58. MAIL FROM:<mysenderemail@mydomin.com>
  59. 250 2.1.0 Sender OK
  60. RCPT TO:<myemail@mydomin.com>
  61. 250 2.1.5 Recipient OK
  62. DEBUG SMTP: Verified Addresses
  63. DEBUG SMTP: myemail@mydomin.com
  64. DATA
  65. 354 Start mail input; end with <CRLF>.<CRLF>
  66. Date: Sun, 28 May 2023 14:33:31 +0300 (AST)
  67. From: mysenderemail@mydomin.com
  68. To: myemail@mydomin.com
  69. Message-ID: <1628804451.7.1685273611450@host.docker.internal>
  70. Subject: test attachment localhost 2.24
  71. MIME-Version: 1.0
  72. Content-Type: multipart/mixed;
  73. boundary="----=_Part_6_2147206188.1685273611445"
  74. .
  75. 250 2.6.0 <1628804451.7.1685273611450@host.docker.internal> [InternalId=91379724192809, Hostname=MyMailServer2] 1339 bytes in 0.293, 4.462 KB/sec Queued mail for delivery
  76. DEBUG SMTP: message successfully delivered to mail server
  77. QUIT
  78. 221 2.0.0 Service closing transmission channel

答案1

得分: 2

以下是您提供的Java代码的中文翻译:

  1. package org.ycr;
  2. import org.apache.synapse.MessageContext;
  3. import org.apache.synapse.mediators.AbstractMediator;
  4. import java.util.*;
  5. import javax.mail.*;
  6. import javax.mail.internet.*;
  7. public class MailSend extends AbstractMediator {
  8. public boolean mediate(MessageContext context) {
  9. log.info("开始发送邮件");
  10. // 存储当前线程的类加载器,以便稍后恢复它。
  11. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  12. try {
  13. String host = "smtp.gmail.com";
  14. int port = 587;
  15. final String username = "xxxx@gmail.com";
  16. final String password = "xxxx";
  17. final String atachmentFilePath = "/home/xx/xx/xxxx/log.txt";
  18. final String toAddress = "xxxx@gmail.com";
  19. // 设置一个新的类加载器,以便Javax能够找到Mime依赖项。
  20. Thread.currentThread().setContextClassLoader(javax.mail.Message.class.getClassLoader());
  21. Properties props = new Properties();
  22. props.put("mail.smtp.host", host);
  23. props.put("mail.smtp.port", port);
  24. props.put("mail.smtp.auth", "true");
  25. props.put("mail.smtp.starttls.enable", "true");
  26. Session session = Session.getInstance(props, new Authenticator() {
  27. protected PasswordAuthentication getPasswordAuthentication() {
  28. return new PasswordAuthentication(username, password);
  29. }
  30. });
  31. // 创建一个新消息
  32. MimeMessage message = new MimeMessage(session);
  33. message.setFrom(new InternetAddress(username));
  34. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
  35. message.setSubject("邮件示例");
  36. Multipart multipart = new MimeMultipart();
  37. // 创建HTML正文部分
  38. MimeBodyPart htmlPart = new MimeBodyPart();
  39. String htmlContent = "<h1>示例</h1>"
  40. + "<p>这是一封示例邮件</p>";
  41. htmlPart.setContent(htmlContent, "text/html");
  42. // 将HTML正文部分添加到多部分消息中
  43. multipart.addBodyPart(htmlPart);
  44. // 文件附件
  45. MimeBodyPart attachmentPart = new MimeBodyPart();
  46. attachmentPart.attachFile(atachmentFilePath);
  47. // 将附件部分添加到多部分消息中
  48. multipart.addBodyPart(attachmentPart);
  49. // 将消息的内容设置为多部分消息
  50. message.setContent(multipart);
  51. Transport.send(message);
  52. log.info("邮件发送完成");
  53. return true;
  54. }catch (Exception e){
  55. handleException("发生错误。", context);
  56. }finally {
  57. Thread.currentThread().setContextClassLoader(classLoader);
  58. }
  59. return true;
  60. }
  61. }

希望这有助于您理解代码的中文翻译。如果您有任何其他问题,请随时提出。

英文:

Here is a working Class Mediator to send Emails with a body and an attachment. I tested this on JDK 8. This should work with JavaX dependencies on JDK 11 as well.

  1. package org.ycr;
  2. import org.apache.synapse.MessageContext;
  3. import org.apache.synapse.mediators.AbstractMediator;
  4. import java.util.*;
  5. import javax.mail.*;
  6. import javax.mail.internet.*;
  7. public class MailSend extends AbstractMediator {
  8. public boolean mediate(MessageContext context) {
  9. log.info(&quot;Starting Main sending&quot;);
  10. // Storing the current class loader of the thread, so we can restore it later.
  11. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  12. try {
  13. String host = &quot;smtp.gmail.com&quot;;
  14. int port = 587;
  15. final String username = &quot;xxxx@gmail.com&quot;;
  16. final String password = &quot;xxxx&quot;;
  17. final String atachmentFilePath = &quot;/home/xx/xx/xxxx/log.txt&quot;;
  18. final String toAddress = &quot;xxxx@gmail.com&quot;;
  19. // Setting a new class loader so Javax is able to find the Mime dependencies.
  20. Thread.currentThread().setContextClassLoader(javax.mail.Message.class.getClassLoader());
  21. Properties props = new Properties();
  22. props.put(&quot;mail.smtp.host&quot;, host);
  23. props.put(&quot;mail.smtp.port&quot;, port);
  24. props.put(&quot;mail.smtp.auth&quot;, &quot;true&quot;);
  25. props.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;);
  26. Session session = Session.getInstance(props, new Authenticator() {
  27. protected PasswordAuthentication getPasswordAuthentication() {
  28. return new PasswordAuthentication(username, password);
  29. }
  30. });
  31. // Create a new message
  32. MimeMessage message = new MimeMessage(session);
  33. message.setFrom(new InternetAddress(username));
  34. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
  35. message.setSubject(&quot;Email Sample&quot;);
  36. Multipart multipart = new MimeMultipart();
  37. // Create the HTML body part
  38. MimeBodyPart htmlPart = new MimeBodyPart();
  39. String htmlContent = &quot;&lt;h1&gt;Sample&lt;/h1&gt;&quot;
  40. + &quot;&lt;p&gt;This is an Sample Mail&lt;/p&gt;&quot;;
  41. htmlPart.setContent(htmlContent, &quot;text/html&quot;);
  42. // Add the HTML body part to the multipart message
  43. multipart.addBodyPart(htmlPart);
  44. // File attaching
  45. MimeBodyPart attachmentPart = new MimeBodyPart();
  46. attachmentPart.attachFile(atachmentFilePath);
  47. // Add the attachment part to the multipart message
  48. multipart.addBodyPart(attachmentPart);
  49. // Set the content of the message to the multipart message
  50. message.setContent(multipart);
  51. Transport.send(message);
  52. log.info(&quot;Done sending Email&quot;);
  53. return true;
  54. }catch (Exception e){
  55. handleException(&quot;Error occurred.&quot;, context);
  56. }finally {
  57. Thread.currentThread().setContextClassLoader(classLoader);
  58. }
  59. return true;
  60. }
  61. }

Java Email is sent with no content and not attachment when sending email from WSO2.

On a side note, I'm not sure why you are trying this with a class mediator, but you can do the same without the class mediator as well. Either by using the Email COnnector or by using Email Transport.

huangapple
  • 本文由 发表于 2023年5月25日 15:20:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定