使用 Java 在电子邮件正文中发送图像

2022-01-23 00:00:00 gmail java jakarta-mail

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

I have been able to send Image as an Attachment in an Email using Java. I am now trying to send the same image in the Email Body Like this:

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 帐户使用正确的用户名和密码时,为什么身份验证失败?

Why is authentication failing while I am using the correct username and Password for My Gmail account?

推荐答案

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

You need to declare your images like this :

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

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

Load images as MimeBodyPart and match the unique-name-or-id with the FileName of the MimeBodyPart.

相关文章