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

通过java mail发送包含字节[]的附件电子邮件,java,email,bytearray,jakarta-mail,Java,Email,Bytearray,Jakarta Mail,我有以下来自数据库的字节[] 0x255044462D312E330A25AAABAC 注意:由于长度原因,上面的字节数组是示例完整文件。 更新: 但我越来越喜欢[B@7ffd10fa格式 在看到代码之前,请阅读以下内容: 当我发送返回getPdfByteStream()方法的bytes时,它会像原始文件一样在电子邮件中发送附件。但当我从数据库获取并发送时,它会发送损坏的文件 更新: 实体类 发送电子邮件的代码 try { MimeBodyPart textBodyP

我有以下来自数据库的
字节[]

0x255044462D312E330A25AAABAC
注意:由于长度原因,上面的字节数组是示例完整文件。

更新:

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


  • 在看到代码之前,请阅读以下内容:
当我发送返回
getPdfByteStream()
方法的
bytes
时,它会像原始文件一样在电子邮件中发送附件。但当我从数据库获取并发送时,它会发送损坏的文件


更新:

实体类

发送电子邮件的代码

 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()方法

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;
}
谁能指引我

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

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

这个

byte[] bytes="0x255044462D312E330A25AAABAC".getBytes();
还将对前导的“0x”进行编码。此外,您似乎正在尝试将十六进制值转换为字节数组,而此方法将字符值转换为字节

我相信你要找的是

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

试试看。

在我看来,这是字符串转换的问题。。。 下面的示例说明了一种可能不是最聪明的方法:-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));


    }
}
公共类TestString2Binary{
公共静态void main(字符串[]args){
String testText=“这是一个示例”;
System.out.println(“String.toString():”;
System.out.println(testText);
字节[]b=testText.getBytes();
System.out.println(“字节[]-toString():”;
系统输出打印ln(b);
System.out.println(“字节[]值-toString():”;
用于(字节x:b){

if(xstring.getBytes(Charset.forName(“UTF-8”))找错了我-我稍后会测试它谢谢@OkieOth我看到了这一点。你也可以参考。这个想法很傻,但“0x”不应该-可以从字符串中删除前缀吗?您的意思是
25504462D312E330A25
而不是
0x25504462D312E330A25
。@injecteer可以执行
Arrays.equals(bytesFromDb,bytesFromPdf)
以确保从数据库和PDF中实际获得相同的字节数组吗?此外,还可以使用
Arrays.toString(bytesFromDb)
数组.toString(bytesFromPdf)
手动比较。我得到异常:
java.lang.IllegalArgumentException:hexBinary需要偶数长度:
。它没有偶数长度尝试在开头加一个零。能否显示用于从数据库获取数据的代码?您确定不能将其作为字节数组而不是字符串和字符串获取然后把它转换回来?
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));


    }
}