Question

I am using JavaMail to send E-mails with html content and attachments. But when sending an E-mail containing both html content and attachments, the html content is diplayed as plain text.

I have set the Content-Type headers as text/html; charset=us-ascii but in the E-mail I receive, the Content-Type is shown as text/plain. Why is this happening?

Here's my code:

if(f!=null){ // f is an array containing the attachment file objects
                Multipart mp=new MimeMultipart("mixed");
                BodyPart mbody=new MimeBodyPart();
                mbody.setHeader("Content-Type", "text/html; charset=us-ascii");
                mbody.setHeader("Content-Transfer-Encoding","7bit");
                mbody.setText(content);                               
                mp.addBodyPart(mbody);                                        
                for(File file:f){    
                    BodyPart mbody2=new MimeBodyPart();
                    DataSource ds=new FileDataSource(file.getAbsolutePath());
                    mbody2.setDataHandler(new DataHandler(ds));
                    mbody2.setFileName(ds.getName());
                    System.out.println(ds.getName());
                    mbody2.setHeader("Content-Type", "multipart/mixed");
                    mp.addBodyPart(mbody2);                        
                }
                m.setContent(mp);
                //m.setHeader("Content-Type", "multipart/mixed");
                //m.setHeader("Content-Transfer-Encoding","base64");
            }
            else{
                m.setContent(content,"text/html");
                m.setHeader("Content-Type", "text/html; charset=us-ascii");
                m.setHeader("Content-Transfer-Encoding","7bit");
            }
            m.saveChanges();

If I uncomment m.setHeader("Content-Type", "multipart/mixed");, then the attachment(s) are displayed as noname without an extension and the content isn't present at all.

If I send the E-mail without attachments, the html content is displayed properly.

Thanks for any help.

Was it helpful?

Solution

I figured it out.

Need to put mbody.setContent(content, "text/html"); instead of mbody.setText(content);.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top