如何使用JavaMail发送带附件的HTML电子邮件

10
以下Java代码用于将文件附加到HTML电子邮件并发送。我想在这封HTML电子邮件中添加附件。任何建议将不胜感激。
以下是翻译后的内容:

以下Java代码用于将文件附加到HTML电子邮件并发送。我希望能够在这封HTML电子邮件中添加附件。如有建议,敬请指教。

public void sendEmail(final String userName, final String password, final String host, final String html, final List<String> emails, String subject, String file) throws MessagingException
    {
        System.out.println("User Name: " + userName);
        System.out.println("Password: " + password);
        System.out.println("Host: " + host);

        //Get the session object  
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator()
                {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return new PasswordAuthentication(userName, password);
                    }
                });

        if (!emails.isEmpty())
        {
            //Compose the message  
            InternetAddress[] address = new InternetAddress[emails.size()];
            for (int i = 0; i < emails.size(); i++)
            {
                address[i] = new InternetAddress(emails.get(i));
            }

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(userName));
            message.setRecipients(Message.RecipientType.TO, address);
            message.setSubject(subject);

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            Multipart multipart = new MimeMultipart();

            messageBodyPart = new MimeBodyPart();
            String fileName = "attachmentName";
            DataSource source = new FileDataSource(file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(html, "text/html; charset=utf-8");
            message.setContent(multipart);
            //send the message  
            Transport.send(message);

            System.out.println("message sent successfully...");
        } else
        {
            System.out.println("No Recieptions");
        }

    }

这只给我带来了附件。但我想发送包含此附件的HTML电子邮件。


与https://dev59.com/km435IYBdhLWcg3wxDH_、https://dev59.com/qWUq5IYBdhLWcg3wJNLg等其他问题重复。 - Jozef Chocholacek
1
@JozefChocholacek;你疯了吗?你读了上面的链接和主题吗? - Terance Wijesuriya
1
@JozefChocholacek;首先仔细阅读内容。 - Terance Wijesuriya
2个回答

29

创建一个包含HTML正文和附件的邮件,实际上意味着创建一个内容为“多部分实体”的邮件,其中包含两个部分,其中一个是HTML内容,另一个是附加的文件。

这与您当前的代码不符:

Multipart multipart = new MimeMultipart(); // creating a multipart is OK

// Creating the first body part of the multipart, it's OK
messageBodyPart = new MimeBodyPart();
// ... bla bla
// ok, so this body part is the "attachment file"
messageBodyPart.setDataHandler(new DataHandler(source));
// ... bla bla
multipart.addBodyPart(messageBodyPart); // at this point, the multipart contains your file attachment, but only that!

// at this point, you set your mail's body to be the HTML message    
message.setContent(html, "text/html; charset=utf-8");
// and then right after that, you **reset** your mail's content to be your multipart, which does not contain the HTML
message.setContent(multipart);

目前,你的电子邮件内容是一个只有1个部分的多部分文件,该部分就是你的附件。

因此,为了达到预期的结果,你需要采取不同的步骤:

  1. 创建一个多部分文件(像之前一样)
  2. 创建一个部分,将你的文件附件作为内容添加进去(像之前一样)
  3. 将第一个部分添加到多部分文件中(像之前一样)
  4. 创建第二个 MimeBodyPart
  5. 将你的HTML内容添加到第二个部分中
  6. 将这个第二个部分添加到你的多部分文件中
  7. 设置你的电子邮件内容为多部分文件(像之前一样)

大致翻译为:

Multipart multipart = new MimeMultipart(); //1
// Create the attachment part
BodyPart attachmentBodyPart = new MimeBodyPart(); //2
attachmentBodyPart.setDataHandler(new DataHandler(fileDataSource)); //2
attachmentBodyPart.setFileName(file.getName()); // 2
multipart.addBodyPart(attachmentBodyPart); //3
// Create the HTML Part
BodyPart htmlBodyPart = new MimeBodyPart(); //4
htmlBodyPart.setContent(htmlMessageAsString , "text/html"); //5
multipart.addBodyPart(htmlBodyPart); // 6
// Set the Multipart's to be the email's content
message.setContent(multipart); //7

请注意,原始代码还包含几个常见的JavaMail错误 - Bill Shannon
1
这里没有电子邮件正文。我的正文在附加的文件中。 有没有办法使正文包含HTML标记? - Mr.Koçak
@Mr.Koçak,问题出现在注释的步骤5。如果您的客户端中没有显示,请建议您打开并检查发送的邮件是否有其他问题,并且可以提供一个带有最小示例的不同问题供其他人查看。 - GPI
1
好的,谢谢。我找到了解决方案。不同之处在于在添加包含HTML标记的消息正文后立即使用以下代码: messagebody.setContent(emailMessage.getText(),"text/html; charset=UTF-8");
message.saveChanges(); 然后我添加了附件,它就起作用了。
- Mr.Koçak
确认 @GPI 的代码对我也有效,这将把 HTML 字符串 htmlMessageAsString 放入邮件正文中,并将文档 file 作为附件添加。 - lolynns

1
**Send Email using html body and file attachement**

          > try {
            host = localhost;//use your host or pwd if any
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.setProperty("mail.smtp.auth", "false");

            Session session = Session.getInstance(props, null);
            MimeMessage mailer = new MimeMessage(session);

            // recipient
            mailer.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toEmail));
            // sender
            mailer.setFrom(new InternetAddress(fromEmail));
            // cc
            if (ccEmail != null) {
                for (int i = 0; i < ccEmail.size(); i++) {
                    String cc = ccEmail.get(i);
                    mailer.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(cc));
                }
            }
            Transport t = session.getTransport("smtp");
            t.connect();

            mailer.setSubject(subject);
            mailer.setFrom(new InternetAddress(fromEmail));

            // attachement
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            BodyPart attachmentBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(htmlbody, "text/html"); // 5
            multipart.addBodyPart(messageBodyPart);

            // file path
            File filename = new File(xmlurl);
            DataSource source = new FileDataSource(filename);

            attachmentBodyPart.setDataHandler(new DataHandler(source));

            attachmentBodyPart.setFileName(filename.getName());

            multipart.addBodyPart(attachmentBodyPart);

            mailer.setContent(multipart);

            Transport.send(mailer);
            System.out.println("Mail completed");
         } catch (SendFailedException e) {//errr
            }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接