gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:23:09 26 4
gpt4 key购买 nike

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

0x255044462D312E330A25AAABAC

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

更新:

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

<小时/>
  • 在查看代码之前,请阅读此处:

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

<小时/>

更新:

Entity.class

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

//getter()/setter();

发送电子邮件的代码

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

谁能指导我。

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.

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

最佳答案

这个

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

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

我相信您正在寻找的是

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

尝试一下。

关于java - 通过java邮件发送带有包含byte[]附件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24011942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com