如何使用Java Mail在邮件中附加PDF?

时间:2016-02-03 21:08:54

标签: java javamail email-attachments

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();
        }

   }

大家好。

我试图找出如何将参数发送的PDF作为formulario附加到之前显示的代码中。

该公司曾经为此事做过以下技巧,但他们需要为之前显示的那个改变它:

        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();

3 个答案:

答案 0 :(得分:2)

由于您已经可以发送电子邮件,因此请调整代码并将以下部分添加到代码中

// 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....");

原始代码取自here

答案 1 :(得分:1)

两种情况下formulario都是字节数组吗?如果是这样,只需重写第一个代码块,使用第二个代码块中的技术构造消息。或者在新版本中将InputStreamDataSource替换为ByteArrayDataSource

答案 2 :(得分:0)

带有附件的发送电子邮件类似于发送电子邮件,但此处的附加功能是通过使用MimeBodyPartBodyPart类来发送消息来发送文件或文档。

发送带有附件的邮件的过程涉及会话对象MimeBodyMultiPart对象。这里的MimeBody用于设置文本消息,并由MultiPart对象携带。由于此处有MultiPart个对象正在发送附件。

       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);
        }