7

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?

Stanley Mungai
  • 4,044
  • 30
  • 100
  • 168

5 Answers5

11

see the below code may be use full

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

and add org.apache.commons.io.jar.zip and axiom-api-1.2.6.jar and add mail.jar and activation.jar

Syjin
  • 2,740
  • 1
  • 27
  • 31
Lucky
  • 103
  • 1
  • 6
8

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.

Alexandre Lavoie
  • 8,711
  • 3
  • 31
  • 72
2

Create a multipart body with content-disposition inline and encode in base64 your image.

Check this SO for some details (in Python) Sending Multipart html emails which contain embedded images

Community
  • 1
  • 1
Daniel Voina
  • 3,185
  • 1
  • 27
  • 32
1

First, see this JavaMail FAQ entry of common mistakes.

Then, see this JavaMail FAQ entry with sample code for connecting to Gmail.

Note that there is no "mail.smtp.password" property. Since you're not supplying a password, authentication is failing.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
1

Another common mistake (bit me today): the Content-ID header for the image must be in <angle brackets>. Failure to do so will break some mail programs (gmail, OS X 10.10) but not others (Outlook, iOS <= 8.1).

David Leppik
  • 3,194
  • 29
  • 18