开发者社区 问答 正文

Java编码Base64,MimeBodyPart附件

我有一个用Base64编码的PDF文件,现在我想发送PDF并允许从邮件打开。

我正在阅读此问题,但不适用于我```js https://stackoverflow.com/a/9124625/811293

Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setSentDate(new Date()); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo)); message.setSubject("Subject - " + new Date()); Multipart multipart = new MimeMultipart();

MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("contentMessage", "text/html"); // YES FOR NOW SIMPLE MESSAGE multipart.addBodyPart(mimeBodyPart);

MimeBodyPart attachmentOnFly = new MimeBodyPart();

/* //In the future the PDF will be created on Fly (Will not be stored) InputStream inputStream = new FileInputStream("/path/to/encoded/Base64/file.pdf");//new ByteArrayInputStream("Bytes from source".getBytes()); ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(inputStream, "application/pdf"); attachmentOnFly.setDataHandler(new DataHandler(byteArrayDataSource)); */

attachmentOnFly.attachFile(new File("/path/to/encoded/Base64/file.pdf")); attachmentOnFly.setHeader("Content-Type", "application/pdf"); attachmentOnFly.setHeader("Content-Transfer-Encoding", "base64"); attachmentOnFly.setDisposition(Part.ATTACHMENT); attachmentOnFly.setFileName("myFileName.pdf"); multipart.addBodyPart(attachmentOnFly);

message.setContent(multipart); Transport.send(message);

我的问题是,当收到邮件时,我无法打开PDF,但是使用Telnet替代方法却可行。

如何发送Enconded Base64 PDF,并且可以从邮件中打开它?

展开
收起
垚tutu 2019-12-04 16:57:57 1227 分享 版权
阿里云 AI 助理回答

要通过电子邮件发送Base64编码的PDF文件,并确保收件人能够直接从邮件中打开它,您需要将Base64字符串解码回字节流,然后将其作为附件添加到MimeMessage中。以下是一个使用JavaMail API实现此操作的示例代码片段:

import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.util.Base64;

public class EmailWithBase64PDFAttachment {
    public static void main(String[] args) throws MessagingException, IOException {
        String from = "your_email@example.com";
        String sendTo = "recipient_email@example.com";
        String host = "smtp.example.com"; // SMTP服务器地址
        String password = "your_password";

        Properties properties = System.getProperties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", "587"); // 或者是其他端口,如465
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
        message.setSubject("Subject - " + new Date());

        Multipart multipart = new MimeMultipart();

        // 假设你有一个Base64编码的PDF字符串
        String base64PDF = "your_base64_encoded_string_here";
        byte[] pdfBytes = Base64.getDecoder().decode(base64PDF);

        MimeBodyPart attachment = new MimeBodyPart();
        DataSource dataSource = new ByteArrayDataSource(pdfBytes, "application/pdf");
        attachment.setDataHandler(new DataHandler(dataSource));
        attachment.setFileName("myFileName.pdf");
        multipart.addBodyPart(attachment);

        message.setContent(multipart);
        
        Transport.send(message);
        System.out.println("Email Sent Successfully.");
    }
}

// 注意:ByteArrayDataSource 类可能需要导入额外的库或自行定义。
class ByteArrayDataSource implements DataSource {
    private byte[] data;
    private String type;

    public ByteArrayDataSource(byte[] data, String type) {
        super();
        this.data = data;
        this.type = type;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(data);
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new IOException("Not Supported");
    }

    @Override
    public String getContentType() {
        return type;
    }

    @Override
    public String getName() {
        return "Generated PDF";
    }
}

这段代码首先设置邮件的基本信息和SMTP服务器配置,然后创建一个MimeMessage实例。关键在于,我们不再直接处理Base64编码的文件路径,而是将Base64字符串解码为字节数组,然后使用ByteArrayDataSource包装这个字节数组,最后设置到MimeBodyPart中作为邮件的附件。

请确保替换your_email@example.comrecipient_email@example.comsmtp.example.com以及your_password等占位符为实际的发件人邮箱地址、收件人邮箱地址、SMTP服务器地址和密码。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答