【问题标题】:Send image in Email Body using Java使用 Java 在电子邮件正文中发送图像
【发布时间】:2012-11-01 17:28:11
【问题描述】:

我已经能够使用 Java 在电子邮件中将图像作为附件发送。我现在正尝试在电子邮件正文中发送相同的图像,如下所示:

public static void main(String[] args) throws NoSuchProviderException, MessagingException {
    System.out.println("Sending mail...");
    Properties props = new Properties();
    props.setProperty("mail.smtp.starttls.enable", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.host", "smtp.gmail.com");

props.setProperty("mail.smtp.port", "587");
    props.setProperty("mail.smtp.user", "mysusername");
    props.setProperty("mail.smtp.password", "mypassword");

    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(true);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("HTML  mail with images");
    message.setFrom(new InternetAddress("myaddress@gmail.com"));
    message.setContent
      ("<h1>This is a test</h1>" 
       + "<img src=\"C:/Users/pc/Desktop/Photos/Shammah.PNG\">", 
       "text/html");
    message.addRecipient(Message.RecipientType.TO,
         new InternetAddress("receiver@simbatech.biz"));

    transport.connect();//This is line 46
    transport.sendMessage(message,
        message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

我得到这个输出:

Sending mail...
DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning        javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
Exception in thread "main" javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at image.in.body.ImageInBody.main(ImageInBody.java:46)
Java Result: 1

当我为我的 Gmail 帐户使用正确的用户名和密码时,为什么身份验证失败?

【问题讨论】:

  • 错误涉及身份验证,而不是您的实际正文内容...您的设置有问题。

标签: java gmail jakarta-mail


【解决方案1】:

使用内联内容处置创建一个多部分正文,并在您的图像中编码 base64。

查看此 SO 了解一些详细信息(在 Python 中)Sending Multipart html emails which contain embedded images

【讨论】:

    【解决方案2】:

    你需要像这样声明你的图片:

    <img src="cid:unique-name-or-id" />
    

    将图像加载为 MimeBodyPart,并将唯一名称或 ID 与 MimeBodyPart 的文件名匹配。

    【讨论】:

      【解决方案3】:

      首先,请参阅common mistakes 的 JavaMail FAQ 条目。

      然后,查看带有sample code for connecting to Gmail 的 JavaMail FAQ 条目。

      请注意,没有“mail.smtp.password”属性。由于您没有提供密码,因此身份验证失败。

      【讨论】:

        【解决方案4】:

        看下面的代码可能是完整的

        class SimpleMail2 {
            public static void main(String[] args) throws Exception{
        
                System.out.println("Sending mail...");
                Properties props = new Properties();
                props.put("mail.smtp.host", "smtp.gmail.com");
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", "465");
        
                Session mailSession = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("sender@gmail.com","password");
                    }
                });
                Message message = new MimeMessage(mailSession);
                message.setFrom(new InternetAddress("sender@gmail.com"));
                message.setSubject("HTML  mail with images");
                message.setRecipient(Message.RecipientType.TO, new InternetAddress("receiver@gmail.com"));
                message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!");
        
                MimeMultipart multipart = new MimeMultipart("related");
                BodyPart messageBodyPart = new MimeBodyPart();
                String htmlText = "<H1>Raghava chary</H1>" + "<img src=\"cid:image\">";
                messageBodyPart.setContent(htmlText, "text/html");
                multipart.addBodyPart(messageBodyPart);
                try {
                    messageBodyPart = new MimeBodyPart();
                    InputStream imageStream = SimpleMail2.class.getClass().getResourceAsStream("/ab/log.gif");
                    DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(imageStream), "image/gif");
                    messageBodyPart.setDataHandler(new DataHandler(fds));
                    messageBodyPart.setHeader("Content-ID","<image>");
                    multipart.addBodyPart(messageBodyPart);
                    message.setContent(multipart);
                    Transport.send(message);
                    System.out.println("Done");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        

        并添加 org.apache.commons.io.jar.zip 和 axiom-api-1.2.6.jar 并添加 mail.jar 和 activation.jar

        【讨论】:

          【解决方案5】:

          另一个常见的错误(今天咬我):图像的 Content-ID 标头必须在 中。不这样做会破坏某些邮件程序(gmail、OS X 10.10),但不会破坏其他邮件程序(Outlook、iOS

          【讨论】:

          • 好吧,这结束了一个漫长而混乱的谜团。谢谢!
          猜你喜欢
          • 1970-01-01
          • 2011-04-12
          • 1970-01-01
          • 1970-01-01
          • 2015-11-27
          • 2018-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多