0

I'm reading messages from an Outlook webmail and getting a list of Messages('javax.mail.Message'). Now I want to forward these Messages to another email address using a java program.

    private void sendTestMail(String from, String subject, String sentDate, Object object, Message message)
            throws EmailException, Exception {

        MultiPartEmail email = new MultiPartEmail();
        email.setHostName(forwardHost);

        email.addTo(mailRecipients(to));
        email.setFrom(emailFrom);
        email.setSubject(subject);
        email.setMsg("Testing email by sahil.");

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath("c:\\sahil\\test.jpg");
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Picture_of_John");
        attachment.setName("John.jpg");
        email.attach(attachment);  


        MimeMultipart multiPart = getMimeMultipart(message);
        email.addPart(multiPart);

        email.send();
    }   

If I comment below two lines in above code then it works fine.

MimeMultipart multiPart = getMimeMultipart(message);
email.addPart(multiPart);

But with these two line I'm getting exception.

2020-04-20 15:41:44,271 ERROR com.st.ict.ols.service.impl.ReplyToMessageServiceImpl [main]  Inner Exception occurred while processing individual message. Error stacktrace is[org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtpapp1.sgp.st.com:25
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1421)
    at org.apache.commons.mail.Email.send(Email.java:1448)
    at com.st.ict.ols.service.impl.ReplyToMessageServiceImpl.sendTestMail(ReplyToMessageServiceImpl.java:342)
    at com.st.ict.ols.service.impl.ReplyToMessageServiceImpl.processMessage(ReplyToMessageServiceImpl.java:167)
    at com.st.ict.ols.service.impl.MessageServiceImpl.processMessage(MessageServiceImpl.java:22)
    at com.st.ict.ols.OlsMailSenderApplication.run(OlsMailSenderApplication.java:36)
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732)
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716)
    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:304)
    at com.st.ict.ols.OlsMailSenderApplication.main(OlsMailSenderApplication.java:27)
Caused by: javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    java.io.IOException: Exception writing Multipart
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1308)
    at javax.mail.Transport.send0(Transport.java:255)
    at javax.mail.Transport.send(Transport.java:124)
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1411)
    ... 10 more
Caused by: java.io.IOException: Exception writing Multipart
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:83)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:884)
    at javax.activation.DataHandler.writeTo(DataHandler.java:317)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1652)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:961)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:553)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:81)
    at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:884)
    at javax.activation.DataHandler.writeTo(DataHandler.java:317)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1652)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1850)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1259)
    ... 13 more
Caused by: javax.mail.MessagingException: Empty multipart: multipart/mixed; 
    boundary="----=_Part_1_1176580790.1587377502798"
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:548)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:81)
    ... 24 more

Code I've written to retrieve MimeMultipart from JavaMailApi's Message object to set in apache common's org.apache.commons.mail.MultiPartEmail Object using attach function.

    public MimeMultipart getMimeMultipart(Message message) throws Exception {
        Object content = message.getContent();
        if (content instanceof String)
            return null;        

        if (content instanceof MimeMultipart) {
            MimeMultipart multiPartResult = new MimeMultipart();
            MimeMultipart multiPart = (MimeMultipart) content;

            List<BodyPart> result = new ArrayList<>();
            for (int i = 0; i < multiPart.getCount(); i++) {
                BodyPart bodyPart = (BodyPart) multiPart.getBodyPart(i);
                result.addAll(getMimeMultipart(bodyPart));
            }
            for(BodyPart part:result) {
                multiPart.addBodyPart(part);
            }
            return multiPartResult;

        }
        return null;
    }

    private List<BodyPart> getMimeMultipart(BodyPart part) throws Exception{
        List<BodyPart> result = new ArrayList<>();
        Object content = part.getContent();

        if (content instanceof InputStream || content instanceof String) {
            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) {
                result.add(part);
            }
            return result;
        }

        if (content instanceof MimeMultipart) {
                MimeMultipart multipart = (MimeMultipart) content;
                for (int i = 0; i < multipart.getCount(); i++) {
                    BodyPart bodyPart =  (BodyPart) multipart.getBodyPart(i);
                    result.addAll(getMimeMultipart(bodyPart));
                }
        }
        return result;
    }

I was able to forward email excluding attachments but facing issues forwarding with attachments/inline images.
Please help me with this issue.

I'm able to forward the complete message as an attachment, how to forward the message as it is.

MultiPartEmail email = new MultiPartEmail();
MimeMultipart mp = new MimeMultipart();
MimeBodyPart fmbp = new MimeBodyPart();
fmbp.setContent(message, "message/rfc822");
fmbp.setDisposition(Part.INLINE);
mp.addBodyPart(fmbp);
email.setContent(mp);

or if I use code

MimeMultipart mp = (MimeMultipart) message.getContent();
email.setContent(mp, message.getContentType());

I'm getting forwarded email like this screenshot of forwarded encoded mail

Sahil Kumar
  • 39
  • 1
  • 3
  • 9
  • All the Apache libraries obscure what's really going on, but you might want to read this [JavaMail FAQ entry on forwarding messages](https://javaee.github.io/javamail/FAQ#forward). – Bill Shannon Apr 20 '20 at 22:56
  • @BillShannon Thanks for the link, Now I'm able to forward the message(complete message with attachments and inline images) as an attachment. But I need to forward the message as it is. What should I do to forward the message, not as an attachment? – Sahil Kumar Apr 21 '20 at 07:18
  • What do you mean by "forward"? Do you really mean "resend"? Do you want to pretend that it's a brand new message and send it to a new recipient? Just call Transport.send with the message and give it a new address to send to. You might need to copy it first using `newMsg = new MimeMessage(oldMsg);` – Bill Shannon Apr 21 '20 at 23:15
  • @BillShannon I need to read messages from one outlook client and sent those messages to another email id. by using 'email.setContent(readMessage, "message/rfc822");' I'm able to achieve it somehow. When I send the read mail to Gmail, it looks perfect but when i send the read mail to outlook. i receive that as an attachment. – Sahil Kumar Apr 22 '20 at 12:50
  • @BillShannon [check image](https://i.stack.imgur.com/p6YTr.png) Email I sent to other outlook Id looks like this. But for Gmail it is working fine. – Sahil Kumar Apr 22 '20 at 12:52
  • Right, if you just need to resend it, make a copy of the message and use that copy with Transport.send and with the new address specified. – Bill Shannon Apr 23 '20 at 02:11
  • @BillShannon Able to achieve it, Thanks! Maybe issue was because of apache common api, now i directly used Java mail API – Sahil Kumar Apr 23 '20 at 10:23

1 Answers1

0

Here the situation is reading mail from one mail server and sending the same message to another email id, within same application.

To achieve this, I used Java Mail API for both reading and sending. Make sure to update the properties if you're using different host for both steps.

    private void sendMailJavax(Message oldMessage) {
        try { 
            // creating a new message using the older message
            MimeMessage message = new MimeMessage((MimeMessage)oldMessage);
            // updating properties as per sender Mailing API
            message.getSession().getProperties().clear();
            message.getSession().getProperties().setProperty("mail.smtp.host", forwardHost);

            // setting appropriate headers. // make sure you don't append using .add methods.
            message.setFrom(new InternetAddress(emailFrom));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setReplyTo(new Address[] { new InternetAddress(replyToEmail)});

            Transport.send(message); 
            System.out.println("Email Sent  successfully...."); 
            } catch (MessagingException mex) { 
                mex.printStackTrace(); 
            } 
    }
Sahil Kumar
  • 39
  • 1
  • 3
  • 9