【问题标题】:How to send any type of attachment using java mail api?如何使用 java mail api 发送任何类型的附件?
【发布时间】:2020-02-12 11:17:34
【问题描述】:

我能够发送仅附有文本文件的邮件,并且我正在使用文件路径。我想要一个代码来使用文件输入流发送任何类型的附件

我可以发送仅附有文本文件的邮件,并且我正在使用文件。

messageBodyPart = new MimeBodyPart();
         String filename = "/home/manisha/file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

我希望代码使用 java api 发送任何类型的附件。

【问题讨论】:

标签: java email email-attachments


【解决方案1】:

事实证明,ByteArrayDataSource 可用于发送任何类型的流。除了流之外,您还需要指定 mime 类型,因为没有它就无法知道类型。如果 InputStream 表示 jpeg 图像,您将使用“image/jpeg”作为传递给 ByteArrayDataSource 的类型。

要知道 ByteArrayDataSource 会将 InputStream 完全读入一个字节数组进行处理。如果 InputStream 非常大,可能会消耗大量内存。再说一次,大多数电子邮件系统都会限制附件大小。

请注意,此代码尚未准备好用于生产,需要进行错误/异常处理。

    messageBodyPart = new MimeBodyPart();
    String filename = "/home/manisha/file.txt";
    //
    // FileInputStream is just for the example. You can use other InputStreams as well.
    //
    InputStream inputStream = new FileInputStream(filename);

    DataSource source;
    try (InputStream inputStream = new FileInputStream(filename)) {
        source = new ByteArrayDataSource(inputStream, "text/plain;charset=UTF-8");
    }
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    // Send the complete message parts
    message.setContent(multipart);

[EDIT] 下面是一些代码来测试您的 InputStream 是否有数据。您可以使用上面的源调用它来打印输入流中的字节数。

private static void printDataSourceByteCount(DataSource source) throws IOException {
    try (InputStream is = source.getInputStream()) {

        long totalBytesRead = 0;
        byte [] buffer = new byte[2048];
        int bytesRead = is.read(buffer);
        while(bytesRead > 0) {
            totalBytesRead += bytesRead;
            bytesRead = is.read(buffer);
        }
        System.out.println(String.format("Read %d bytes", totalBytesRead));
    }
}

[编辑] 这是我使用测试 pdf 的功能齐全的示例。只要您将 mime 类型更改为“text/plain”,文本文件就可以正常工作。

public static void main(String[] args) {

    // Recipient's email ID needs to be mentioned.
    String to = "<to email>";

    // Sender's email ID needs to be mentioned
    String from = "<from email>";

    final String username = "<email server username>";// change accordingly
    final String password = "<email server password>";// change accordingly

    // Set to your email server
    String host = "mail.acme.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "false");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Testing Subject");

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Hello. Attached is a very important PDF.");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "/Users/rick/Tmp/test.pdf";

        DataSource source;
        try (InputStream inputStream = new FileInputStream(filename)) {
            source = new ByteArrayDataSource(inputStream, "application/pdf");
        }

        printDataSourceByteCount(source);

        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("SecretsOfTheUniverse.pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        // TODO handle the error
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO handle the error
        e.printStackTrace();
    } catch (IOException e) {
        // TODO handle the error
        e.printStackTrace();
    }
}

【讨论】:

  • 是的,我用过这个方法,但是收到的邮件中没有文件。
  • 数据源源 = new ByteArrayDataSource(inputStream, contentType);这是我用的线
  • 现在我正在接收文件,但文件是空的
  • 检查您的输入流是否有数据。我添加了一种方法来提供帮助。我还清理了原始代码以更好地处理 InputStream 的关闭。如果这不能让您获得工作代码,我将需要查看更多您的代码。
猜你喜欢
  • 2011-09-03
  • 2019-10-28
  • 2017-08-08
  • 2013-04-13
相关资源
最近更新 更多