简体   繁体   中英

How to properly send mail javax.mail 1.4 with HTML code

I´m trying to send an email in JAVA using the lib javax.mail 1.4, and i have more than a few problems:

1.- The RCPT TO appears like undisclosed recipients.

2.- Ignores the HTML code.

3.- Some strange code at the beginning and at the end of the email body (now I put the full code)

4.- The subjects change to SPAM.

5.- Doesn´t support acutes.

Here comes the code and log.

    public static void enviarCorreo(String asunto, List<String> destinatarios, String cuerpo) {

    try {

        if(destinatarios!=null && !"".equals(destinatarios)) {

            System.out.println("Creando handlers para los tipos..");

            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
            mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822");

            System.out.println("Sending mail...");

            Properties props = System.getProperties();

            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.host", "work.host.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "25");
            props.put("mail.smtp.allow8bitmime", "true");               
            props.put("mail.debug", "true");

            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getDefaultInstance(props, auth);

            Address[] destinataris = new Address[9];

            String s_correuOrigen = "somemail@work.com";

            /**
             *  Copiado de Enviar Mail
             */

            MimeMessage msg = new MimeMessage(session);
            msg.addHeader("Return-Receipt-To", s_correuOrigen);
            msg.addHeader("Disposition-Notification-To", s_correuOrigen);
            msg.setFrom(new InternetAddress(s_correuOrigen));

            String s_destinataris = "";
            for (int d=0; d<destinatarios.size(); d++) {
                s_destinataris+=destinatarios.get(d);
                if (d!=destinatarios.size()-1) {
                    s_destinataris+=",";
                }
            }

            System.out.println("destinatarios: "+s_destinataris);

            System.out.println("mensaje UTF-8 : "+cuerpo);

            destinataris  = InternetAddress.parse(s_destinataris, false);
            MimeMultipart multiParte = new MimeMultipart();

            BodyPart texto = new MimeBodyPart();
            texto.setContent(cuerpo, "text/html; charset=UTF-8");

            multiParte.addBodyPart(texto);

            msg.setContent(multiParte);

            msg.setRecipients(Message.RecipientType.TO, destinataris);
            msg.setSubject("Resultat de l´enviament de correus","utf-8");

            Transport.send(msg);

            /*Message msg = new MimeMessage(session);
            msg.addHeader("Return-Receipt-To", s_correuOrigen);
            msg.addHeader("Disposition-Notification-To", s_correuOrigen);
            msg.setFrom(new InternetAddress(s_correuOrigen));

            destinataris  = InternetAddress.parse(destinatarios, false);

            MimeMultipart multiParte = new MimeMultipart();

            BodyPart texto = new MimeBodyPart();
            texto.setContent(cuerpo, "text/plain; charset=\"Cp1252\"");
            multiParte.addBodyPart(texto);

            msg.setContent(multiParte);

            msg.setRecipients(Message.RecipientType.TO, destinataris);
            msg.setSubject("Resultat de l´enviament de correus ");

            Transport.send(msg);*/



            /*Message msg = new MimeMessage(session);
            msg.addHeader("Return-Receipt-To", s_correuOrigen);
            msg.addHeader("Disposition-Notification-To", s_correuOrigen);
            msg.addHeader("From", s_correuOrigen);
            msg.addHeader("Sender", s_correuOrigen);
            msg.setFrom(new InternetAddress(s_correuOrigen));

            MimeMultipart multiParte = new MimeMultipart();
            BodyPart texto = new MimeBodyPart();
            texto.setContent(cuerpo, "text/html");
            multiParte.addBodyPart(texto);
            msg.setContent(multiParte);

            destinataris = InternetAddress.parse(destinatarios, false);
            msg.setRecipients(Message.RecipientType.TO, destinataris);
            msg.setSubject(asunto);

            Transport.send(msg);*/



            /*Transport transport = session.getTransport();

            MimeMessage message = new MimeMessage(session);
            message.setSubject(asunto);
            message.setFrom(new InternetAddress(s_correuOrigen));
            message.setContent(cuerpo, "text/html; charset=utf-8");

            for (int d=0; d<destinatarios.size(); d++) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinatarios.get(d)));
            }

            transport.connect();
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            transport.close();*/



            /*MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(s_correuOrigen));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress("mymail@work.com"));

            Multipart mp = new MimeMultipart();
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(cuerpo, "text/html");
            mp.addBodyPart(htmlPart);
            msg.setContent(mp);
            Transport.send(msg);*/
        }

    }catch (Exception ex) {
        ex.printStackTrace();
    }
}

-------------------------- THE LOG ----------------------------------

Loading javamail.default.providers from jar:file:/C:/servidors/apache-tomcat-6.0.32/lib/mail.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
Loading javamail.default.providers from jar:file:/C:/Users/andreus/workspaceP4H/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/p4h2013/WEB-INF/lib/mail-1.4.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@7de9da21; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@7de9da21; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "work.host.com", port 25, isSSL false
220 llwg961.work.com ESMTP Postfix
DEBUG SMTP: connected to host "work.host.com", port: 25

EHLO PROGRAMACIO22
250-llwg961.work.com
250-PIPELINING
250-SIZE 26214400
250-ETRN
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "26214400"
DEBUG SMTP: Found extension "ETRN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
YWxhcm1lc0BsaW1pdC5lcw==
334 UGFzc3dvcmQ6
ZThURG03JXFxYg==
235 2.7.0 Authentication successful
DEBUG SMTP: use8bit true
MAIL FROM:<somemail@work.com>
250 2.1.0 Ok
RCPT TO:<mymail@gmail.com>
250 2.1.5 Ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   mymail@gmail.com
DATA
354 End data with <CR><LF>.<CR><LF>

------=_Part_0_1451711239.1417703117929
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<b>Buenos dias,<b>

Se ha detectado un cambio entre los dos =00faltimos tests del paciente Pacie=
nt Proves Centre 1. Vaya a la secci=C3=B3n de Informes de la aplicaci=C3=B3n=
 para terapeutas para ver la informaci=C3=B3n ampliada.

Un saludo.
------=_Part_0_1451711239.1417703117929--

.
250 2.0.0 Ok: queued as 84B431001522
QUIT
221 2.0.0 Bye
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "work.host.com", port 25, isSSL false
220 llwg961.work.com ESMTP Postfix
DEBUG SMTP: connected to host "work.host.com", port: 25

EHLO PROGRAMACIO22
250-llwg961.work.com
250-PIPELINING
250-SIZE 26214400
250-ETRN
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "26214400"
DEBUG SMTP: Found extension "ETRN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
YWxhcm1lc0BsaW1pdC5lcw==
334 UGFzc3dvcmQ6
ZThURG03JXFxYg==
235 2.7.0 Authentication successful
DEBUG SMTP: use8bit true
MAIL FROM:<somemail@work.com>
250 2.1.0 Ok
RCPT TO:<mymail@work.com>
250 2.1.5 Ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   mymail@work.com
DATA
354 End data with <CR><LF>.<CR><LF>

------=_Part_0_1451711239.1417703117929
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<b>Buenos dias,<b>

Se ha detectado un cambio entre los dos =00faltimos tests del paciente Pacie=
nt Proves Centre 1. Vaya a la secci=C3=B3n de Informes de la aplicaci=C3=B3n=
 para terapeutas para ver la informaci=C3=B3n ampliada.

Un saludo.
------=_Part_0_1451711239.1417703117929--

.
250 2.0.0 Ok: queued as 6DB81100152B
QUIT
221 2.0.0 Bye

And this is what i receive:

------=_Part_0_1451711239.1417703117929 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable

Buenos dias,

Se ha detectado un cambio entre los dos =00faltimos tests del paciente Pacie= nt Proves Centre 1. Vaya a la secci=C3=B3n de Informes de la aplicaci=C3=B3n= para terapeutas para ver la informaci=C3=B3n ampliada.

Un saludo. ------=_Part_0_1451711239.1417703117929--

The same in outlook and gmail.

At least the email is sended!

Any help will be apreciated.

EDIT

Try replace

        MimeMultipart multiParte = new MimeMultipart();

        BodyPart texto = new MimeBodyPart();
        texto.setContent(cuerpo, "text/html; charset=UTF-8");

        multiParte.addBodyPart(texto);

        msg.setContent(multiParte);

        msg.setRecipients(Message.RecipientType.TO, destinataris);
        msg.setSubject("Resultat de l´enviament de correus","utf-8");

        Transport.send(msg);

with:

        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(cuerpo, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        // add the Multipart to the message
        msg.setContent(mp, "text/html");

        // send the message
        Transport.send(msg);

Change the line

msg.setContent(multiParte);

to

msg.setContent(multiParte,"text/html");

The problem was that. I had the javax.mail classes in two different jars. On the one hand had geronimo-javamail that was a dependency of axis2-kernel (maven), and on the other hand had the mail.jar, when I import, held his first library instead of the second.

I read somewhere that changing the order of the jars in the classpath (right click, java build path in eclipse and then on the "order and export" tab) could have solved the problem, but using maven does not work. What I have done is to exclude this library, changing in the pom:

  <dependency>
     <groupId> org.apache.axis2 </ groupId>
     <artifactId> axis2-kernel </ artifactId>
     <version> 1.4.1 </ version>
     <exclusions>
        <exclusion>
           <artifactId> geronimo-javamail_1.4_spec </ artifactId>
           <groupId> org.apache.geronimo.specs </ groupId>
        </ exclusion>
      </ exclusions>
  </ dependency>

So, first of all ensure that you are using the right libraries and that your imported classes are those what you want (in eclipse there is the "link to editor" button, if activated, when you open a .java or .class, the project explorer goes to that file).

The code has been as follows:

        Properties props = System.getProperties();

        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "work.mailing.es");
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "false");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        Address[] destinataris = new Address[9];

        MimeMessage msg = new MimeMessage(session);
        msg.addHeader("Return-Receipt-To", s_correuOrigen);
        msg.addHeader("Disposition-Notification-To", s_correuOrigen);
        msg.setFrom(new InternetAddress(s_correuOrigen));

        String s_destinataris = "";
        for (int d=0; d<destinatarios.size(); d++) {
            s_destinataris+=destinatarios.get(d);
            if (d!=destinatarios.size()-1) {
                s_destinataris+=",";
            }
        }

        System.out.println("destinatarios: "+s_destinataris);

        destinataris  = InternetAddress.parse(s_destinataris, false);
        MimeMultipart multiParte = new MimeMultipart();

        BodyPart texto = new MimeBodyPart();
        texto.setContent(cuerpo, "text/html; charset=UTF-8");

        multiParte.addBodyPart(texto);

        msg.setContent(multiParte);

        msg.setRecipients(Message.RecipientType.TO, destinataris);
        msg.setSubject(asunto,"utf-8");

        Transport.send(msg);

Where s_correuOrigen is the email of the sender, destinatarios is a List of strings (the recipients), asunto is the subject and cuerpo is the body of the message.

Also if you want to authenticate to the mailing server, you may need something like this:

public class SMTPAuthenticator extends javax.mail.Authenticator {
    public PasswordAuthentication getPasswordAuthentication() {
        String username = "someone@somewhere.es";
        String password = "password";
        return new PasswordAuthentication(username, password);
    }
}

This worked for me, with html code in the body of the message, accents, etc.

Thank you for your time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM