Search code examples
javajakarta-mailemail-attachments

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("reminder@companyname.com.ar"));
            //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",
            "reminder@companyname.com.ar",
            "companypassword");
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        return "Mensaje enviado con éxito";
    } catch (Exception mex) {
        return mex.toString();

Solution

  • 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.