Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Body message does not appear when sending attachments

When I send attachments, I don't see the body message (message.setText(this.getEmailBody());) in the email. Without attachments, the email appears with the body message. Emails are sent to a gmail account. Any clue why is this happening?

        MimeMessage message = new MimeMessage(session_m);    
        message.setFrom(new InternetAddress(this.getEmailSender()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.getEmailRecipient()));
        message.setSubject(this.getEmailSubject());
        message.setText(this.getEmailBody()); //This won't be displayed if set attachments

        Multipart multipart = new MimeMultipart();

        for(String file: getAttachmentNameList()){
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.attachFile(this.attachmentsDir.concat(file.trim()));
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);
        }


        Transport.send(message);
        System.out.println("Email has been sent");
like image 699
nidis Avatar asked Jan 27 '13 12:01

nidis


2 Answers

You need to use the following:

         // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
         //Add the bodypart for the attachment(s)
        // Send the complete message parts
        message.setContent(multipart); //message is of type - MimeMessage
like image 114
Srinivas Avatar answered Nov 11 '22 20:11

Srinivas


You need to separate into 2 parts to do this:

        Multipart multipart = new MimeMultipart();

        // content part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(content);
        messageBodyPart.setContent(content, "text/html");
        multipart.addBodyPart(messageBodyPart);

        BodyPart attachmentPart = new MimeBodyPart();
        DataSource source = new FileDataSource(file);
        attachmentPart.setDataHandler(new DataHandler(source));
        attachmentPart.setFileName(file.getName());
        multipart.addBodyPart(attachmentPart);
like image 40
Anh Ta Avatar answered Nov 11 '22 21:11

Anh Ta