且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-07 18:47:55

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

 < img src =cid:unique-name-or-id /&GT; 

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

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();
}

I am getting this output:

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

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" />

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