简体   繁体   English

如何使用HTML代码正确发送邮件javax.mail 1.4

[英]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: 我正在尝试使用lib javax.mail 1.4在JAVA中发送电子邮件,但我有多个问题:

1.- The RCPT TO appears like undisclosed recipients. 1.- RCPT TO的显示方式类似于未公开的收件人。

2.- Ignores the HTML code. 2.-忽略HTML代码。

3.- Some strange code at the beginning and at the end of the email body (now I put the full code) 3.-在电子邮件正文的开头和结尾处有一些奇怪的代码(现在我输入完整的代码)

4.- The subjects change to SPAM. 4.-主题变为垃圾邮件。

5.- Doesn´t support acutes. 5.-不支持急性发作。

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; ------ = _ Part_0_1451711239.1417703117929内容类型:text / html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable charset = UTF-8内容传输编码:带引号的可打印

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. 私人检测中心= 00验证测试中心=证明中心1。保密信息= C3 = B3n信息通报= C3 = B3n =准信息对等体= C3 = B3n扩增子。

Un saludo. sal ------=_Part_0_1451711239.1417703117929-- ------ = _ Part_0_1451711239.1417703117929--

The same in outlook and gmail. 在Outlook和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. 我在两个不同的jar中放置了javax.mail类。 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. 一方面有geronimo-javamail,它是axis2-kernel(maven)的依赖项,另一方面有mail.jar,当我导入时,它拥有他的第一个库而不是第二个。

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. 我在某处读到,更改类路径中jar的顺序(右键单击,eclipse中的Java构建路径,然后在“ order and export”选项卡上)可以解决问题,但是使用maven无效。 What I have done is to exclude this library, changing in the pom: 我要做的是排除此库,在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). 因此, 首先,请确保您使用的库正确 ,并且导入的类是所需的类(在eclipse中,当您打开.java或.class时,如果激活了“链接到编辑器”按钮,则项目资源管理器转到该文件)。

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. 其中s_correuOrigen是发件人的电子邮件, destinatarios是字符串(收件人)的列表, asunto是主题, cuerpo是消息的主体。

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. 这对我有用,消息正文中带有html代码,重音符号等。

Thank you for your time. 感谢您的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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