在java中发送多部分电子邮件

时间:2016-06-28 06:10:06

标签: java email mime-message

这是我的代码:

            MimeMessage emailMessage = new MimeMessage(session);

            emailMessage.setFrom(new InternetAddress(from));
            emailMessage.addRecipient(Message.RecipientType.TO,  new InternetAddress(to));      
            emailMessage.setSubject("testing html and inline images emails");

            MimeMultipart multipart = new MimeMultipart("related");

            BodyPart text = new MimeBodyPart();
            String htmlText = "<H1>Hello</H1><br/> <p align=center><img src=\"cid:senny\"> </p>";
            text.setContent(htmlText, "text/html");
            multipart.addBodyPart(text);

            BodyPart image = new MimeBodyPart();
            DataSource fds = new FileDataSource("http://mobilemarketingwatch.com/wp-content/uploads/2016/01/Is-Google-Searching-for-the-Next-Big-Thing1.jpg");         
            image.setDataHandler(new DataHandler(fds));
            image.addHeader("Content-ID","<senny>");
            multipart.addBodyPart(image);

            emailMessage.setContent(multipart, "text/html; charset=utf-8");
            emailMessage.saveChanges();            

            Transport.send(emailMessage);

我收到这条消息的电子邮件:

  

javax.mail.internet.MimeMultipart@598f069a

而不是真实的消息。  有什么想法??

1 个答案:

答案 0 :(得分:0)

sending a Multipart object的方法是emailMessage.setContent(multipart),而不是setContent(Object o, String type)