Aoren
Aoren

Reputation: 105

How to attach a PDF in a mail using Java Mail?

public static String sendMail(
                    String destino,
                    String texto,
                    String asunto,
                    byte[] formulario,
                    String nombre) {

            Properties properties = new Properties();

            try{
            Session session = Session.getInstance(properties);

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            //Cargo el destino
            if(destino!= null && destino.length > 0 && destino[0].length() > 0 ){
                for (int i = 0; i < destino.length; i++) {
                    message.addRecipient(Message.RecipientType.TO,new InternetAddress(destino[i]));
                }
            }
            //message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(asunto);
            //I load the text and replace all the '&' for 'Enters' and the '#' for tabs
            message.setText(texto.replaceAll("&","\n").replaceAll("#","\t"));

            Transport.send(message);

            return "Mensaje enviado con éxito";

        }catch(Exception mex){

            return mex.toString();
        }

   }

Hello everyone.

I was trying to figure out how can I attach the PDF sent by parameters as formulario in the code previously shown.

The company used to do the following trick for this matter but they need to change it for the one previously shown:

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(
            texto.replaceAll("&", "\n").replaceAll("#", "\t"));
        //msg.setText(texto.replaceAll("&","\n").replaceAll("#","\t"));
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        messageBodyPart.setDataHandler(
            new DataHandler(
                (DataSource) new InputStreamDataSource(formulario,
                "EDD",
                "application/pdf")));

        messageBodyPart.setFileName(nombre + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);
        msg.saveChanges();

        Transport transport = session.getTransport("smtp");
        transport.connect(
            "smtp.gmail.com",
            "[email protected]",
            "companypassword");
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        return "Mensaje enviado con éxito";
    } catch (Exception mex) {
        return mex.toString();

Upvotes: 1

Views: 4947

Answers (3)

Du-Lacoste
Du-Lacoste

Reputation: 12767

The sending email with attachment is similar to sending email but here the additional functionality is with message sending a file or document by making use of MimeBodyPart, BodyPart classes.

The process for sending mail with attachment involves session object, MimeBody, MultiPart objects. Here the MimeBody is used to set the text message and it is carried by MultiPart object. Because of MultiPart object here sending attachment.

       try {
            // Create a default MimeMessage object.
            Message message = new MimeMessage(session);
            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));
            // Set To: header field of the header.
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            // Set Subject: header field
            message.setSubject("Attachment");
            // Create the message part
            BodyPart messageBodyPart = new MimeBodyPart();
            // Now set the actual message
            messageBodyPart.setText("Please find the attachment below");
            // Create a multipar message
            Multipart multipart = new MimeMultipart();
            // Set text message part
            multipart.addBodyPart(messageBodyPart);
            // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            String filename = "D:/test.PDF";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            // Send the complete message parts
            message.setContent(multipart);
            // Send message
            Transport.send(message);
            System.out.println("Email Sent Successfully !!");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

Upvotes: 0

Bill Shannon
Bill Shannon

Reputation: 29971

Is formulario a byte array in both cases? If so, just rewrite the first block of code to construct the message using the technique in the second block of code. Or replace InputStreamDataSource with ByteArrayDataSource in the new version.

Upvotes: 1

Since you already can send emails, the adjust your code and add the following part to your code

// Create a default MimeMessage object.
 Message message = new MimeMessage(session);

 // Set From: header field of the header.
 message.setFrom(new InternetAddress(from));

 // Set To: header field of the header.
 message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));

 // Set Subject: header field
 message.setSubject("Testing Subject");

 // Create the message part
 BodyPart messageBodyPart = new MimeBodyPart();

 // Now set the actual message
 messageBodyPart.setText("This is message body");

// Create a multipar message
 Multipart multipart = new MimeMultipart();

 // Set text message part
 multipart.addBodyPart(messageBodyPart);

 // Part two is attachment
 messageBodyPart = new MimeBodyPart();
 String filename = "/home/file.pdf";
 DataSource source = new FileDataSource(filename);
 messageBodyPart.setDataHandler(new DataHandler(source));
 messageBodyPart.setFileName(filename);
 multipart.addBodyPart(messageBodyPart);

 // Send the complete message parts
 message.setContent(multipart);

 // Send message
 Transport.send(message);

 System.out.println("Sent message successfully....");

original code taken from here

Upvotes: 3

Related Questions