10

The following Java code is used to attach a file to a html email and send it. I want to send attachment with this html email. Any suggestions would be appreciated.

public void sendEmail(final String userName, final String password, final String host, final String html, final List<String> emails, String subject, String file) throws MessagingException
    {
        System.out.println("User Name: " + userName);
        System.out.println("Password: " + password);
        System.out.println("Host: " + host);

        //Get the session object  
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator()
                {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return new PasswordAuthentication(userName, password);
                    }
                });

        if (!emails.isEmpty())
        {
            //Compose the message  
            InternetAddress[] address = new InternetAddress[emails.size()];
            for (int i = 0; i < emails.size(); i++)
            {
                address[i] = new InternetAddress(emails.get(i));
            }

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(userName));
            message.setRecipients(Message.RecipientType.TO, address);
            message.setSubject(subject);

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            Multipart multipart = new MimeMultipart();

            messageBodyPart = new MimeBodyPart();
            String fileName = "attachmentName";
            DataSource source = new FileDataSource(file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(html, "text/html; charset=utf-8");
            message.setContent(multipart);
            //send the message  
            Transport.send(message);

            System.out.println("message sent successfully...");
        } else
        {
            System.out.println("No Recieptions");
        }

    }

This brings me just only the attachment . But i want to send html email with this attachment .

Terance Wijesuriya
  • 1,928
  • 9
  • 31
  • 61

2 Answers2

29

Creating a mail with an HTML body and an attachment, actually means creating a mail whose content is a "multipart entity", that contains two parts, one of them being the HTML content, et the second being the attached file.

This does not correspond to your current code:

Multipart multipart = new MimeMultipart(); // creating a multipart is OK

// Creating the first body part of the multipart, it's OK
messageBodyPart = new MimeBodyPart();
// ... bla bla
// ok, so this body part is the "attachment file"
messageBodyPart.setDataHandler(new DataHandler(source));
// ... bla bla
multipart.addBodyPart(messageBodyPart); // at this point, the multipart contains your file attachment, but only that!

// at this point, you set your mail's body to be the HTML message    
message.setContent(html, "text/html; charset=utf-8");
// and then right after that, you **reset** your mail's content to be your multipart, which does not contain the HTML
message.setContent(multipart);

At this point, your email's content is a multipart that has only 1 part, which is your attachment.

So, to reach your expected result, you should proceed differently :

  1. Create a multipart (as you did)
  2. Create a part, that has your file attachment as a content (as you did)
  3. Add this first part to the multipart (as you did)
  4. Create a second MimeBodyPart
  5. Add your html content to that second part
  6. Add this second part to your multipart
  7. Set your email's content to be the multipart (as you did)

Which roughly translates to :

Multipart multipart = new MimeMultipart(); //1
// Create the attachment part
BodyPart attachmentBodyPart = new MimeBodyPart(); //2
attachmentBodyPart.setDataHandler(new DataHandler(fileDataSource)); //2
attachmentBodyPart.setFileName(file.getName()); // 2
multipart.addBodyPart(attachmentBodyPart); //3
// Create the HTML Part
BodyPart htmlBodyPart = new MimeBodyPart(); //4
htmlBodyPart.setContent(htmlMessageAsString , "text/html"); //5
multipart.addBodyPart(htmlBodyPart); // 6
// Set the Multipart's to be the email's content
message.setContent(multipart); //7
GPI
  • 9,088
  • 2
  • 31
  • 38
  • Note that the original code also contains several [common JavaMail mistakes](http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes). – Bill Shannon Aug 05 '15 at 18:15
  • 1
    There is no email body with this. My body is in an attached file. is there any way to make body containing html tags? – Mr.Koçak Dec 12 '17 at 09:47
  • @Mr.Koçak There is, at the commented step number 5. If it does not appear in your client, I suggest you open and inspect the sent mail for any other trouble, and maybe, a different question with a minimal example for others to look at. – GPI Dec 12 '17 at 11:43
  • 1
    Ok thanks. I found solution. What made the difference is messagebody.setContent(emailMessage.getText(),"text/html; charset=UTF-8"); message.saveChanges(); right after adding message body which contained html tags. I added attachment afterwards and it worked. – Mr.Koçak Jan 12 '18 at 13:34
  • Confirming that @GPI 's code works for me as well, this does place the html string `htmlMessageAsString` into the body of the message, and attaches the document `file` as an attachment. – lolynns May 20 '20 at 18:13
1
**Send Email using html body and file attachement**

          > try {
            host = localhost;//use your host or pwd if any
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.setProperty("mail.smtp.auth", "false");

            Session session = Session.getInstance(props, null);
            MimeMessage mailer = new MimeMessage(session);

            // recipient
            mailer.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toEmail));
            // sender
            mailer.setFrom(new InternetAddress(fromEmail));
            // cc
            if (ccEmail != null) {
                for (int i = 0; i < ccEmail.size(); i++) {
                    String cc = ccEmail.get(i);
                    mailer.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(cc));
                }
            }
            Transport t = session.getTransport("smtp");
            t.connect();

            mailer.setSubject(subject);
            mailer.setFrom(new InternetAddress(fromEmail));

            // attachement
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            BodyPart attachmentBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(htmlbody, "text/html"); // 5
            multipart.addBodyPart(messageBodyPart);

            // file path
            File filename = new File(xmlurl);
            DataSource source = new FileDataSource(filename);

            attachmentBodyPart.setDataHandler(new DataHandler(source));

            attachmentBodyPart.setFileName(filename.getName());

            multipart.addBodyPart(attachmentBodyPart);

            mailer.setContent(multipart);

            Transport.send(mailer);
            System.out.println("Mail completed");
         } catch (SendFailedException e) {//errr
            }
        }
Mugeesh Husain
  • 394
  • 4
  • 13