簡體   English   中英

如何使用 JavaMail 將多個文件附加到 email?

[英]How to attach multiple files to an email using JavaMail?

以下 Java 代碼用於將文件附加到 email。 我想通過 email 發送多個文件附件。 任何建議,將不勝感激。

public class SendMail {

    public SendMail() throws MessagingException {
        String host = "smtp.gmail.com";
        String Password = "mnmnn";
        String from = "xyz@gmail.com";
        String toAddress = "abc@gmail.com";
        String filename = "C:/Users/hp/Desktop/Write.txt";
        // Get system properties
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, toAddress);
        message.setSubject("JavaMail Attachment");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("Here's the file");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        try {
            Transport tr = session.getTransport("smtps");
            tr.connect(host, from, Password);
            tr.sendMessage(message, message.getAllRecipients());
            System.out.println("Mail Sent Successfully");
            tr.close();
        } catch (SendFailedException sfe) {
            System.out.println(sfe);
        }
    }
}` 

好吧,我已經有一段時間沒有完成 JavaMail 工作了,但看起來您可以多次重復此代碼:

DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);

例如,您可以編寫一個方法來執行此操作:

private static void addAttachment(Multipart multipart, String filename)
{
    DataSource source = new FileDataSource(filename);
    BodyPart messageBodyPart = new MimeBodyPart();        
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
}

然后從您的主代碼中,只需調用:

addAttachment(multipart, "file1.txt");
addAttachment(multipart, "file2.txt");

等等

更新(2020 年 3 月)

使用最新的JavaMail™ API (目前為1.6 版JSR 919 ),事情就簡單多了:


有用的閱讀

這是一個帶有完整示例的不錯且中肯的教程:

    Multipart mp = new MimeMultipart();

        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body,"text/html");
        mp.addBodyPart(mbp1);

        if(filename!=null)
        {
            MimeBodyPart mbp2 = null;
            FileDataSource fds =null;
            for(int counter=0;counter<filename.length;counter++)
            {
                mbp2 = null;
                fds =null;
                mbp2=new MimeBodyPart();
                fds = new FileDataSource(filename[counter]);
                mbp2.setDataHandler(new DataHandler(fds));
                mbp2.setFileName(fds.getName());
                mp.addBodyPart(mbp2);
            }
        }
        msg.setContent(mp);
        msg.setSentDate(new Date());
        Transport.send(msg);

只需使用要附加的第二個文件的文件名添加另一個塊並將其插入到 message.setContent(multipart) 命令之前

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(filename);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(filename);

    multipart.addBodyPart(messageBodyPart);

擁有 Array list al,其中包含您需要郵寄的附件列表,並使用下面給出的代碼

for(int i=0;i<al.size();i++)
            {
                System.out.println(al.get(i));

                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource((String)al.get(i));

                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName((String)al.get(i));
                multipart.addBodyPart(messageBodyPart);
                message.setContent(multipart);
            }
File f = new File(filepath);
File[] attachments = f.listFiles();
// Part two is attachment
for( int i = 0; i < attachments.length; i++ ) {
    if (attachments[i].isFile() && attachments[i].getName().startsWith("error"))  {
        messageBodyPart = new MimeBodyPart();
        FileDataSource fileDataSource =new FileDataSource(attachments[i]);
        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
        messageBodyPart.setFileName(attachments[i].getName());
        messageBodyPart.setContentID("<ARTHOS>");
        messageBodyPart.setDisposition(MimeBodyPart.INLINE);
        multipart.addBodyPart(messageBodyPart);
    }
}

只需將更多文件添加到multipart

這在 Spring 4+ 中 100% 有效。 您必須在您的 Gmail 帳戶上啟用安全性較低的選項。 您還需要 apache commons 包:

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
@GetMapping("/some-mapping")
public void mailMethod(@RequestParam CommonsMultipartFile attachFile, @RequestParam CommonsMultipartFile attachFile2) {

    Properties mailProperties = new Properties();
    mailProperties.put("mail.smtp.auth", true);
    mailProperties.put("mail.smtp.starttls.enable", true);
    mailProperties.put("mail.smtp.ssl.enable", true);
    mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    mailProperties.put("mail.smtp.socketFactory.fallback", false);

    JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
    javaMailSenderImpl.setJavaMailProperties(mailProperties);
    javaMailSenderImpl.setHost("smtp.gmail.com");
    javaMailSenderImpl.setPort(465);
    javaMailSenderImpl.setProtocol("smtp");
    javaMailSenderImpl.setUsername("*********@gmail.com");
    javaMailSenderImpl.setPassword("*******");
    javaMailSenderImpl.setDefaultEncoding("UTF-8");

    List<CommonsMultipartFile> attachments = new ArrayList<>();
    attachments.add(attachFile);
    attachments.add(attachFile2);

    javaMailSenderImpl.send(mimeMessage -> {

        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setTo(emailTo);
        messageHelper.setSubject(subject);
        messageHelper.setText(message);

        if (!attachments.equals("")) {
            for (CommonsMultipartFile file : attachments) {
                messageHelper.addAttachment(file.getOriginalFilename(), file);
            }
        }
    });
}
 Multipart multipart = new MimeMultipart("mixed");

        for (int alen = 0; attlen < attachments.length; attlen++) 
        {

            MimeBodyPart messageAttachment = new MimeBodyPart();    
            fileName = ""+ attachments[attlen];


            messageAttachment.attachFile(fileName);
            messageAttachment.setFileName(attachment);
            multipart.addBodyPart(messageAttachment);

        }

Java Mail 1.3 后附加文件更簡單,

  • 只需使用 MimeBodyPart 方法直接或從文件路徑附加文件。

     MimeBodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.attachFile(String filePath); messageBodyPart.attachFile(File file); multipart.addBodyPart(messageBodyPart);

試試這個從數組中讀取文件名

 MimeBodyPart messageBodyPart =  new MimeBodyPart();      
     Multipart multipart = new MimeMultipart();

     for(int i = 0 ; i < FilePath.length ; i++){
          info("Attching the file + "+ FilePath[i]);
          messageBodyPart.attachFile(FilePath[i]);
          multipart.addBodyPart(messageBodyPart);                       
     }         
 message.setContent(multipart);

當然,我確實有更好的選擇,可以在一封郵件中發送多個文件。 Mutipart 類允許我們很容易地獲得這個特性。 如果您可能沒有關於它的任何信息,請從這里閱讀: https : //docs.oracle.com/javaee/6/api/javax/mail/Multipart.html

Multipart 類為我們提供了兩個不同參數的同名方法,即addBodyPart(BodyPart part) 和addBodyPart(BodyPart part, int index)。 對於單個文件,我們可以使用第一種方法,對於多個文件,我們可以使用第二種方法(需要兩個參數)。

 MimeMessage message = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            message.setFrom(new InternetAddress(username));

            for (String email : toEmails) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));
                }

                message.setSubject(subject);
                BodyPart messageBodyPart1 = new MimeBodyPart();
                messageBodyPart1.setText(typedMessage);

                multipart.addBodyPart(messageBodyPart1, i);
                i = i + 1;

                for (String filename : attachedFiles) {
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();


                    messageBodyPart2.attachFile(filename);

                    multipart.addBodyPart(messageBodyPart2, i);
                    i = i + 1;
                }

                message.setContent(multipart);
                Transport.send(message);
 for (String fileName: files) {
            MimeBodyPart messageAttachmentPart = new MimeBodyPart();
            messageAttachmentPart.attachFile(fileName);
            multipart.addBodyPart(messageAttachmentPart);
        }

您必須確保為每個附件創建一個新的 mimeBodyPart。 該對象是通過引用傳遞的,所以如果你只這樣做:

 MimeBodyPart messageAttachmentPart = new MimeBodyPart();
  
 for (String fileName: files) {
            messageAttachmentPart.attachFile(fileName);
            multipart.addBodyPart(messageAttachmentPart);
        }

它將附加相同的文件 X 次

@informatik01 在上面發布了一個答案,並附有指向文檔的鏈接,其中有一個示例

以下為我工作:

List<String> attachments = new ArrayList<>();

attachments.add("C:/Users/dell/Desktop/file1.txt");
attachments.add("C:/Users/dell/Desktop/file2.txt");
attachments.add("C:/Users/dell/Desktop/file3.txt");
attachments.add("C:/Users/dell/Desktop/file4.txt");
attachments.add("C:/Users/dell/Desktop/file5.txt");

MimeMessage msg = new MimeMessage(session);

if (attachments !=null && !attachments.isEmpty() ) {
MimeBodyPart attachmentPart = null;
            Multipart multipart = new MimeMultipart();
            for(String attachment : attachments) {
                attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(new File(attachment));
                multipart.addBodyPart(attachmentPart);
            }
            multipart.addBodyPart(textBodyPart);
            msg.setContent(multipart);
}
Transport.send(msg);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM