Java Mail,发送多个附件不起作用 [英] Java Mail, sending multiple attachments not working

查看:83
本文介绍了Java Mail,发送多个附件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在没有运气的情况下查看了互联网上的许多条目。

I looked at many entries on the internet without having luck.

这是我的代码:

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailTest
{

    public static void main(String[] args) throws AddressException, MessagingException, IOException
    {
        String host = "***";
        String from = "b";
        String to = "***";

        // Get system properties
        Properties props = System.getProperties();

        // Setup mail server
        props.put("mail.smtp.host", host);

        // Get session
        Session session = Session.getDefaultInstance(props, null);

        // Define message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Hello JavaMail");
        message.setText("Welcome to JavaMail");

        // Handle attachment 1
        MimeBodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.attachFile("c:/Temp/a.txt");

        // Handle attachment 2
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2.attachFile("c:/Temp/b.txt");

        MimeMultipart multipart = new MimeMultipart("related");

        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart2);

        message.setContent(multipart);

        // Send message
        Transport.send(message);
    }
}

结果是我只收到第一个文件。

The result is that i only get the first file attached.


  1. 我试过多次调用attachFile方法但是它只应用了最后一个附件

  2. 我尝试在addBodyPart上玩索引:没有帮助

我检查了简单的消息,我看到其中的另一个文件相同的标识符,由于某种原因它没有在附件中列出。

I checked the plain message and i see the other file in it with the same identifier and it is not listed in the attachments for some reason.

任何帮助将不胜感激,
戴夫

Any help would be appreciated, Dave

推荐答案

Multipart multipart = new MimeMultipart("mixed");
for (String str : attachment_PathList) {
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(str);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(source.getName());
    multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport.send(msg);

这篇关于Java Mail,发送多个附件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆