简体   繁体   中英

Send HTML email along with multiple file attachments?

I am trying to send an HTML email in the body of an email along with few file attachments as well. I came up with below code:

public void sendEmail(final String to, final String from, final String cc, final String subject, final String body,
        final String baseDirectory, final List<String> listOfFileNames) {
    for (int i = 1; i <= 3; i++) { // retrying
        try {
            Session session = Session.getInstance(mailProperties, null);

            Multipart multipart = new MimeMultipart();
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));

            InternetAddress[] toAddress = InternetAddress.parse(to);
            InternetAddress[] ccAddress = InternetAddress.parse(cc);

            message.addRecipients(RecipientType.TO, toAddress);
            message.addRecipients(RecipientType.CC, ccAddress);
            message.setSubject(subject);
            message.setContent(body, "text/html;charset=utf8");

            for (String file : listOfFileNames) {
                String fileLocation = baseDirectory + "/" + file;
                addAttachment(multipart, fileLocation);
            }
            message.setContent(multipart);
            Transport.send(message, toAddress);
            break;
        } catch (Exception ex) {
            // log exception
        }
    }
}

// this is used for attachment
private void addAttachment(final Multipart multipart, final String filename) throws MessagingException {
    DataSource source = new FileDataSource(filename);
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
}

I need to have body String as part of my HTML email and have all the files attach in the same email. I am running like this as in my home directory, I have two files: abc.csv and tree.txt .

EmailTest.getInstance().sendEmail("hello@host.com", "hello@host.com", "hello@host.com",
                "Test Subject (" + dateFormat.format(new Date()) + ")", content, "/export/home/david/",
                Arrays.asList("abc.csv", "tree.txt"));

After I get an email, I don't see my text in the body of an email at all? And second thing is file attachment name is coming as /export/home/david/abc.csv and /export/home/david/tree.txt ?

Is anything wrong I am doing? One thing I see wrong as I am calling setContent method twice with different parameters?

First you need to add the text as an own BodyPart . Next your MimeMultipart needs to be set to the type r elated so you can have both, HTML-Text and some attachements. Then it should work to have both, attachements and text.

And the filename you pass to messageBodyPart.setFileName(filename) is the filename you see in the attachment name. So just leave out the path and you should just see abc.csv and tree.txt

public void sendEmail(final String to, final String from, final String cc, final String subject, final String body,
        final String baseDirectory, final List<String> listOfFileNames) {
    for (int i = 1; i <= 3; i++) { // retrying
        try {
            Session session = Session.getInstance(mailProperties, null);

            Multipart multipart = new MimeMultipart("related");
            MimeBodyPart bodyPart= new MimeBodyPart();

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));

            InternetAddress[] toAddress = InternetAddress.parse(to);
            InternetAddress[] ccAddress = InternetAddress.parse(cc);

            message.addRecipients(RecipientType.TO, toAddress);
            message.addRecipients(RecipientType.CC, ccAddress);
            message.setSubject(subject);

            bodyPart.setText(body, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);

            for (String file : listOfFileNames) {
                String fileLocation = baseDirectory + "/" + file;
                addAttachment(multipart, fileLocation, file);
            }
            message.setContent(multipart);
            Transport.send(message, toAddress);
            break;
        } catch (Exception ex) {
            // log exception
        }
    }
}

// this is used for attachment
private void addAttachment(final Multipart multipart, final String filepath, final String filename) throws MessagingException {
    DataSource source = new FileDataSource(filepath);
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM