Search code examples
javajakarta-mailplaintext

Plain text email sent via JavaMail arrives as an attachment


I have written a code to send via java mail API.Everything is working fine but the plain text which I am sending in received by recipient in form of downloadable attachment rather than plain text message.

I don't know why this is happening. Given below is the code and its output when I run it.

        String toEmail=request.getParameter("email");
        String subject=request.getParameter("subject");
        String message=request.getParameter("message");

        String fromEmail="[email protected]";
        String username="suyash.tilhari12";
        String password="********";

        mailSender.sendEmail(fromEmail, username, password, toEmail, subject, message);

   public void sendEmail(String fromEmail,String username,String password,
            String toEmail,String subject,String  message) 
    {
        try
        {
        Properties props= System.getProperties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.fallback", "false");

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

        Message mailMessage=new MimeMessage(mailSession);
        mailMessage.setFrom(new InternetAddress(fromEmail));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        mailMessage.setContent(message, "html/text");
        mailMessage.setSubject(subject);

        Transport transport=mailSession.getTransport("smtp");
        transport.connect("smtp.gmail.com",username,password);
        transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
        }
        catch (Exception ex) {
            Logger.getLogger(MailSenderBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

I have used Java Mail API ,NetBeans IDE ,Glassfish Server,Enterprise JAVA Bean.

THE RESULT IS AS FOLLOWS:

Mail recipient- Look,the simple text message is in form of attachment.

enter image description here

The message is inside this attachment which is now downloaded and opened-

enter image description here

How is this caused and how can I solve it?


Solution

  • @Suyash: Try following instructions on this http://www.tutorialspoint.com/java/java_sending_email.htm link.