【问题标题】:How to properly send mail javax.mail 1.4 with HTML code如何使用 HTML 代码正确发送邮件 javax.mail 1.4
【发布时间】:2014-12-10 23:09:16
【问题描述】:

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

1.- RCPT TO 看起来像未公开的收件人。

2.- 忽略 HTML 代码。

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

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

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

-------------- 日志 ------------ ----------------------

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 内容类型:文本/html;字符集=UTF-8 内容传输编码:引用打印

布宜诺斯艾利斯,

Se ha detectado un cambio entre los dos =00faltimos tests del paciente Pacie= nt Proves Center 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--

outlook 和 gmail 一样。

至少发送了电子邮件!

我们将不胜感激。

【问题讨论】:

    标签: java html encoding character-encoding jakarta-mail


    【解决方案1】:

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

    我在某处读到更改类路径中 jar 的顺序(右键单击,Eclipse 中的 java 构建路径,然后在“顺序和导出”选项卡上)可以解决问题,但使用 maven 不起作用。我所做的是排除这个库,在 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>
    

    所以,首先要确保您使用的是正确的库,并且您导入的类是您想要的(在 Eclipse 中,如果激活了“链接到编辑器”按钮,当您打开 .java 或 .class,项目资源管理器会转到该文件)。

    代码如下:

            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 是消息的正文。

    另外,如果你想对邮件服务器进行身份验证,你可能需要这样的东西:

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

    这对我有用,在消息正文中使用 html 代码、口音等。

    感谢您的宝贵时间。

    【讨论】:

      【解决方案2】:

      编辑

      尝试替换

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

      与:

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

      换行

      msg.setContent(multiParte);
      

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

      【讨论】:

      • 我用这个结果做了改变:
      • @Andrés_Serra 结果是什么?
      • 抱歉,我用这个结果进行了更改:java.io.IOException: "text/html" DataContentHandler 需要 String 对象,被赋予了 javax.mail.internet.MimeMultipart 类型的对象所以我尝试了直接传递正文消息的字符串。问题 #3(电子邮件正文开头和结尾的奇怪代码)已经消失,其他问题仍在发生。我只是试图在正文的第一行添加一个“b”标签,但没有被解释。我没有提到即使将发件人添加到安全列表中,仍然会通过垃圾邮件更改主题。
      • 同样的错误,函数 setContent 只接受 html 数据内容的字符串。我使用 maven,这是依赖项:javax.activationactivation1.1javax. mailmail1.4 但我只是意识到,该方法正在从另一个库中获取 de javax.mail 类! geronimo-javamail_1.4_spec_1.2.jar 必须是这样的。我需要指向 javax.mail 实际库。
      • @Andrés_Serra 我现在看到了问题 :) 让我知道您更改后它是否有效
      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多