简体   繁体   中英

How to configure correctly JavaMail to send byte[] attachments

For educational purposes I'm trying to send directly ,using Jav Mail, a byte[] without save before as File.

I have this:

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

But when I receive the mail, dont have any attachment. I'm not a expert, but i think MimeBodyPart aren't "attached" to message.

Thanks in advance!

I find this, and works for me :) Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM