如何使用HTML代码正确发送邮件javax.mail 1.4 [英] How to properly send mail javax.mail 1.4 with HTML code

查看:160
本文介绍了如何使用HTML代码正确发送邮件javax.mail 1.4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用lib javax.mail 1.4在JAVA中发送电子邮件,并且我遇到了多个问题:

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.- RCPT TO看起来像未公开的收件人。

1.- The RCPT TO appears like undisclosed recipients.

2.-忽略HTML代码。

2.- Ignores the HTML code.

3.-一些奇怪的代码在电子邮件正文的开头和结尾(现在我输入了完整的代码)

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

4.-主题更改为垃圾邮件。

4.- The subjects change to SPAM.

5.-不支持急性。

以下是代码和日志。

    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

这就是我收到的信息:

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

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

Buenos dias

Buenos dias,

检测到的错误= 00验证测试中心=验证中心1。V ======================================================================================================================================================

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.

没有礼貌。
------ = _ Part_0_1451711239.1417703117929-

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

Outlook和gmail相同。

The same in outlook and gmail.

至少发送了电子邮件!

任何帮助都将受到赞赏。

Any help will be apreciated.

推荐答案

问题是这样的。我在两个不同的jar中放置了javax.mail类。一方面有geronimo-javamail,它是axis2-kernel(maven)的依赖项,另一方面有mail.jar,当我导入时,拥有了他的第一个库而不是第二个库。

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.

我在某处读到,更改类路径中jar的顺序(右键单击,eclipse中的Java构建路径,然后在 order and export选项卡上)可以解决问题,但是使用专家不起作用。我所做的就是排除了这个库,在pom中进行了更改:

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>

因此,首先确保您使用的是正确的库您导入的类就是您想要的类(在月食中,有一个链接到编辑器按钮,如果激活,则在打开.java或.class时,项目浏览器将转到该文件)。

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).

代码如下:

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

其中 s_correuOrigen 是发件人的电子邮件, destinatarios 是字符串列表(收件人), asunto 是主题, cuerpo 是邮件的正文。

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

这对我有用,体内有html代码邮件,重音符号等。

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

谢谢您的时间。

这篇关于如何使用HTML代码正确发送邮件javax.mail 1.4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆