Search code examples
javajakarta-maildatahandler

Javamail, error when sending attachments.


I am trying to send an email. When I send it without an attachment, it sends the email correctly. If I try to attach something, then it doesn't work.

The Class:

import com.sun.mail.smtp.SMTPTransport;

import java.io.File;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    public static void Send(String from, String pass, String[] to, String assunto, String mensagem, File[] anexos) {
        String host = "smtp.risantaisabel.com.br";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        //String[] to = {"[email protected]"}; // added this line

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(from));
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        InternetAddress[] toAddress = new InternetAddress[to.length];
        boolean enviado = true;
        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) { // changed from a while loop
            try {
                toAddress[i] = new InternetAddress(to[i]);
            } catch (AddressException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
       // System.out.println(Message.RecipientType.TO);

        for( int i=0; i < toAddress.length; i++) { // changed from a while loop
            try {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            message.setSubject(assunto);
            //message.setContent(mensagem, "text/plain");
            message.setText(mensagem);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);

            if(anexos.length == 0){
            }
            else {
                 Multipart mp = new MimeMultipart();          
                 BodyPart messageBodyPart = new MimeBodyPart();  

                for(int i = 0; i < anexos.length;i++) {
                    MimeBodyPart mbp2 = new MimeBodyPart();    

                    FileDataSource fds = new FileDataSource(anexos[i].getPath());  

                    mbp2.setDataHandler(new DataHandler(fds));          
                    mbp2.setFileName(fds.getName());    

                    mp.addBodyPart(mbp2);   
                }
                messageBodyPart.setContent(message, "multipart/mixed");  
                mp.addBodyPart(messageBodyPart); 
                message.setContent(mp);
            }
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            JOptionPane.showMessageDialog(null, "<html><b>Email não enviado, tente novamente confirmando seus dados");
            enviado = false;
            e.printStackTrace();
        }
        if(enviado) {
            JOptionPane.showMessageDialog(null, "<html><b>Email enviado.</html></b> \n\n Caso tenha digitado errado o email, somente pela sua caixa de entrada poderá confirmar se chegou. \n\n<html> Email da parte digitado:<b><font size = 3 COLOR=#ff0000> " + to[0]);
        }
    }
}

If I change the the setContent to text/plain, I get:

javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: "text/html" DataContentHandler requires String object, was given object of type class javax.mail.internet.MimeMessage
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)

If I change the setContent to multipart/mixed, I get:

javax.mail.MessagingException: MIME part of type "multipart/mixed" contains object of type javax.mail.internet.MimeMessage instead of MimeMultipart

Do you have any idea how I can fix this? Thanks.


Solution

  • Remove

    message.setText(mensagem);
    

    Change

    messageBodyPart.setContent(message, "multipart/mixed");
    

    to

    messageBodyPart.setText(mensagem);
    

    and move it and the following line above the "for" loop.

    Also, see this JavaMail FAQ entry of common mistakes.