通过java邮件发送带有包含字节[]的附件的电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24011942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:43:40  来源:igfitidea点击:

Send email with attachment which contains byte[] via java mail

javaemailbytearrayjavamail

提问by Yubaraj

I have following byte[]which comes from database.

我有以下byte[]来自数据库的内容。

0x255044462D312E330A25AAABAC

Note: above byte array is sample full file is not here because of length.

注意:上面的字节数组是样本完整文件,因为长度不在这里。

UPDATE:

更新:

But I am getting like [B@7ffd10faformat

但我越来越喜欢[B@7ffd10fa格式



  • Before you see code please read here:
  • 在你看到代码之前,请阅读这里:

When I send byteswhich returns getPdfByteStream()method it sends attachment in email like original file. But when I get from database and send it sends corrupted file.

当我发送bytes返回getPdfByteStream()方法时,它会像原始文件一样在电子邮件中发送附件。但是当我从数据库获取并发送时,它会发送损坏的文件。



UPDATE:

更新:

Entity.class

实体类

@Lob
@Column(name = "ATTACHED_FILE")
private byte[] attachedFile;

//getter()/setter();

Code which sends email

发送电子邮件的代码

 try {
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(content);

       //byte[] bytes = getPDFByteStream(); //Returns byte[] reading local drive file


         **UPDATE:**

        //bytes[] bytes=entity.getAttachedFile(); // It gets value from entity.

        /**
        ** It is getting like "[B@7ffd10fa" format but m storing on database like "0x255044462D312E330A25" format
        **/

        String string="0x255044462D312E330A25";
        byte[] bytes =string.getBytes(Charset.forName("UTF-8"));
        System.out.println("bytes " + bytes.toString());

        DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
        MimeBodyPart pdfBodyPart = new MimeBodyPart();
        pdfBodyPart.setDataHandler(new DataHandler(dataSource));
        pdfBodyPart.setFileName("bankAdminReport.pdf");

        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(textBodyPart);
        mimeMultipart.addBodyPart(pdfBodyPart);

        InternetAddress iaSender = new InternetAddress(sender);
        InternetAddress iaRecipient = new InternetAddress(recipient);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSender(iaSender);
        mimeMessage.setSubject(subject);
        mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
        mimeMessage.setContent(mimeMultipart);

        Transport.send(mimeMessage);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

getPDFByteStream() method

getPDFByteStream() 方法

public static byte[] getPDFByteStream() throws IOException {
    File file = new File("C:\pdf\bankAdminReport.pdf");

    byte[] b = new byte[(int) file.length()];
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(b);
    } catch (FileNotFoundException e) {
        System.out.println("File Not Found.");
        e.printStackTrace();
    } catch (IOException e1) {
        System.out.println("Error Reading The File.");
        e1.printStackTrace();
    }
    return b;
}

Can anyone guide me.

谁能指导我。

The main problem is when I send file reading from local drive it sends perfectly. but if I send getting from database or any local variable file corrupts.

主要问题是当我从本地驱动器发送文件读取它发送完美。但是如果我从数据库发送获取或任何本地变量文件损坏。

Please comment below if you have any query regarding question. Thanks.

如果您对问题有任何疑问,请在下面发表评论。谢谢。

回答by Zoltán

This

这个

byte[] bytes="0x255044462D312E330A25AAABAC".getBytes();

will also encode the leading "0x". Furthermore, it seems that you are trying to convert from hexadecimal values to a byte array, whereas this method would convert the character values to bytes.

还将对前导“0x”进行编码。此外,您似乎正在尝试将十六进制值转换为字节数组,而此方法会将字符值转换为字节。

I believe what you are looking for is

我相信你正在寻找的是

byte[] bytes = java.xml.bind.DatatypeConverter.parseHexBinary("255044462D312E330A25AAABAC");

Try that.

试试那个。

回答by OkieOth

Imo, it's a problem of String conversion ... The following example illustrates a way - maybe not the smartest :-D

Imo,这是字符串转换的问题......下面的例子说明了一种方法 - 也许不是最聪明的 :-D

public class TestString2Binary {
    public static void main(String[] args) {
        String testText="This is \n a sample";
        System.out.println("String.toString(): ");
        System.out.println(testText);
        byte[] b=testText.getBytes();
        System.out.println("byte[]-toString(): ");
        System.out.println(b);

        System.out.println("byte[] values - toString(): ");
        for (byte x:b) {
            if (x<100)
                System.out.print("0"+x);
            else
                System.out.print(x);
        }

        String s="084104105115032105115032010032097032115097109112108101";
        System.out.println("imo the back converting to String goes wrong:");
        System.out.println(s.getBytes());
        System.out.println(new String(s.getBytes()));
        System.out.println(s.getBytes(Charset.forName("UTF-8")));
        System.out.println(new String(s.getBytes(Charset.forName("UTF-8"))));

        int recoveredBLength=s.length()/3;
        byte[] recoveredB=new byte[recoveredBLength];
        for (int i=0;i<recoveredBLength;i++) {
            String part=s.substring(i*3,(i*3)+3);
            recoveredB[i]=Byte.parseByte(part);
        }

        System.out.println("the original string: ");
        System.out.println(new String(recoveredB));


    }
}