如何正确配置JavaMail以发送byte []附件

时间:2013-06-16 21:07:31

标签: java javamail attachment

出于教育目的,我试图使用Jav Mail直接发送一个byte []而不保存为File。

我有这个:

        Properties props = new Properties();
        props.put("mail.debug", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");            
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "587");                 

        Authenticator auth = new SMTPAuthenticator();

        Session mailSession = Session.getDefaultInstance(props, auth);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject (asunto, "text/plain");
        message.setContent(mensaje, "text/plain");
        message.setSentDate (new java.util.Date());
        message.setFrom(new InternetAddress(SMTP_AUTH_USER));

        InternetAddress address[] = new InternetAddress[destino.length];
        for( int i = 0; i < destino.length; i++ ) {
            address[i] = new InternetAddress ( destino[i] );
        }
        message.setRecipients (Message.RecipientType.TO, address);

        if (adjuntos){
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setFileName("AttachedFile");
            DataSource ds = new ByteArrayDataSource(archive, MIME);
            mbp.setDataHandler(new DataHandler(ds));
        }           

        transport.connect();
        transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));

        transport.close();

但是当我收到邮件时,没有任何附件。我不是专家,但我认为MimeBodyPart不会“附加”到消息上。

提前致谢!

1 个答案:

答案 0 :(得分:1)

我找到了这个,对我有用:)谢谢!

        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        message.setContent(mp);