JavaMail - Problemas com acentuação no campo "PARA"

3 respostas
C

Pessoal,

boa tarde.

Estou tendo problemas com a API JavaMail. Tenho um sistema que envia um e-mail para o usuário depois que ele se cadastra, com a sua senha, que é gerado automáticamente, O sistema monta o campo do destinatário da mensagem, inserindo o nome completo do usuário que se cadastrou, e entre os sinas “<” e “>” o email. O problema é quando o nome do usuário possui acentuação (o que ocorre na maioria das vezes). Ocorre um erro que descrevo no final desta mensagem.

Se eu envio uma mensagem por algum cliente de e-mail que use o mesmo SMTP, aonde o nome do destinatário possua acentuação, funciona sem problemas.

Lendo o erro, desconfiei que o problema poderia estar no campo “Content-Transfer-Encoding” do Header da mensagem, já que era o único campo do header diferente das mensagens que enviava pelo cilente de e-mail (nos clientes de e-mail este campo estava preenchido assim: “Content-Transfer-Encoding= 8bit”)

Por isso montei o código abaixo, na tentativa de solucionar o erro:

msg.setHeader("Content-Type", "text/plain; charset=ISO-8859-1; format=flowed");
msg.setHeader("Content-Transfer-Encoding", "8bit");
msg.setHeader("X-Accept-Language", "pt-br, pt");
msg.setHeader("User-Agent", "Sistema FaleConosco");
msg.setHeader("Organization", "E4W");

Só que não funcionou. Todos os outros campos do Header são modificados, segundo as instruções que passei, menos o “Content-Transfer-Encoding”, que apresenta-se sempre da seguinte maneira: “Content-Transfer-Encoding= quoted-printable”.

Pode até ser que o problema não seja nele. A desconfiança recai sobre ele por causa de ser o único campo diferente das mensagens enviadas pelo cliente de e-mail, e que são entregues sem problemas.

Abaixo segue a mensagem de erro que é retornado:

INVALID HEADER (INVALID CHARACTERS OR SPACE GAP)

Non-encoded 8-bit data (char E9 hex) in message header ‘To’: To: “Andr\351” <[email removido]

This nondelivery report was generated by the amavisd-new program
at host darwin. Our internal reference code for your message
is 30477-03-11.

WHAT IS AN INVALID CHARACTER IN MAIL HEADER?

The RFC 2822 standard specifies rules for forming internet messages.
It does not allow the use of characters with codes above 127 to be used
directly (non-encoded) in mail header (it also prohibits NUL and bare CR).

If characters (e.g. with diacritics) from ISO Latin or other alphabets
need to be included in the header, these characters need to be properly
encoded according to RFC 2047. This encoding is often done transparently
by mail reader (MUA), but if automatic encoding is not available (e.g.
by some older MUA) it is the user’s responsibility to avoid the use
of such characters in mail header, or to encode them manually. Typically
the offending header fields in this category are ‘Subject’, ‘Organization’,
and comment fields in e-mail addresses of the ‘From’, ‘To’ and ‘Cc’.

Sometimes such invalid header fields are inserted automatically
by some MUA, MTA, content checker, or other mail handling service.
If this is the case, that service needs to be fixed or properly configured.
Typically the offending header fields in this category are ‘Date’,
‘Received’, ‘X-Mailer’, ‘X-Priority’, ‘X-Scanned’, etc.

If you don’t know how to fix or avoid the problem, please report it
to your postmaster or system manager.

Return-Path: ><[email removido]>
Your message [email removido]
could not be delivered to:
<[email removido]>:
554 5.6.0 Message with invalid header rejected, id=30477-03-11 - Non-encoded 8-bit data (char E9 hex) in message header ‘To’: To: “Andr\351” <[email removido]

Reporting-MTA: dns; darwin
Received-From-MTA: smtp; smtp.e4w.com.br ([127.0.0.1])
Arrival-Date: Thu, 31 Mar 2005 15:43:52 -0300 (BRT)

Final-Recipient: rfc822; [email removido]
Action: failed
Status: 5.6.0
Diagnostic-Code: smtp; 554 5.6.0 Message with invalid header rejected, id=30477-03-11 - Non-encoded 8-bit data (char E9 hex) in message header ‘To’: To: “Andr\351” ><[email removido]
Last-Attempt-Date: Thu, 31 Mar 2005 15:43:52 -0300 (BRT)

Received: from ti02.e4w.com.br (unknown [10.0.0.1])

by smtp.e4w.com.br (Postfix) with ESMTP id 366482D50ED

for ><[email removido]>; Thu, 31 Mar 2005 15:43:52 -0300 (BRT)

Message-ID: <a href="mailto:[email removido]">[email removido]</a>

Date: Thu, 31 Mar 2005 12:49:16 -0300 (BRT)

From: CVRD - Fale Conosco <[email removido]>

To: André <[email removido]>

Subject: Abertura de conta no sistema Fale Conosco

MIME-Version: 1.0

Content-Type: text/plain; charset=ISO-8859-1

Content-Transfer-Encoding: quoted-printable

X-Accept-Language: pt-br, pt

User-Agent: Sistema FaleConosco

Organization: E4W

Agradeço desde já pela paciência em ler esta enorme mensagem.

3 Respostas

C

Pessoal, já passei os parâmetros “Content-Type: text/plain; charset=ISO-8859-1; format=flowed” e “Content-Transfer-Encoding: 8bit”, mais não adiantou nada. Já enviei mensagens sem acentuação no campo para que são entregues corretamentes, e comparei o Header com as da mensagens enviadas pelo Thunderbird, e estão identicos.

Abaixo segue a outra mensagem de erro que ocorre:

INVALID HEADER (INVALID CHARACTERS OR SPACE GAP)

Non-encoded 8-bit data (char E1 hex) in message header ‘To’: To: “Caio T\341cito” <caio.tac…

This nondelivery report was generated by the amavisd-new program
at host darwin. Our internal reference code for your message
is 22163-01-90.

WHAT IS AN INVALID CHARACTER IN MAIL HEADER?

The RFC 2822 standard specifies rules for forming internet messages.
It does not allow the use of characters with codes above 127 to be used
directly (non-encoded) in mail header (it also prohibits NUL and bare CR).

If characters (e.g. with diacritics) from ISO Latin or other alphabets
need to be included in the header, these characters need to be properly
encoded according to RFC 2047. This encoding is often done transparently
by mail reader (MUA), but if automatic encoding is not available (e.g.
by some older MUA) it is the user’s responsibility to avoid the use
of such characters in mail header, or to encode them manually. Typically
the offending header fields in this category are ‘Subject’, ‘Organization’,
and comment fields in e-mail addresses of the ‘From’, ‘To’ and ‘Cc’.

Sometimes such invalid header fields are inserted automatically
by some MUA, MTA, content checker, or other mail handling service.
If this is the case, that service needs to be fixed or properly configured.
Typically the offending header fields in this category are ‘Date’,
‘Received’, ‘X-Mailer’, ‘X-Priority’, ‘X-Scanned’, etc.

If you don’t know how to fix or avoid the problem, please report it
to your postmaster or system manager.

Return-Path: ><[email removido]>
Your message [email removido]
could not be delivered to:
<[email removido]>:
554 5.6.0 Message with invalid header rejected, id=22163-01-90 - Non-encoded 8-bit data (char E1 hex) in message header ‘To’: To: “Caio T\341cito” <caio.tac…

Reporting-MTA: dns; darwin
Received-From-MTA: smtp; smtp.e4w.com.br ([127.0.0.1])
Arrival-Date: Mon, 4 Apr 2005 11:08:37 -0300 (BRT)

Final-Recipient: rfc822; [email removido]
Action: failed
Status: 5.6.0
Diagnostic-Code: smtp; 554 5.6.0 Message with invalid header rejected, id=22163-01-90 - Non-encoded 8-bit data (char E1 hex) in message header ‘To’: To: “Caio T\341cito” ><caio.tac…
Last-Attempt-Date: Mon, 4 Apr 2005 11:08:38 -0300 (BRT)

Received: from ti02.e4w.com.br (unknown [10.0.0.1])

by smtp.e4w.com.br (Postfix) with ESMTP id 6710C2EC9AB

for ><[email removido]>; Mon,  4 Apr 2005 11:08:37 -0300 (BRT)

Message-ID: <a href="mailto:[email removido]">[email removido]</a>

Date: Mon, 4 Apr 2005 08:14:21 -0300 (BRT)

From: CVRD - Fale Conosco <[email removido]>

To: Caio Tácito <[email removido]>

Subject: Abertura de conta no sistema Fale Conosco

MIME-Version: 1.0

Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Content-Transfer-Encoding: 8bit

Algue teria ideia do que pode ser?

T

É bastante simples - não mexi no seu exemplo, mas dá para entender.
Estou usando JavaMail 1.3.2 e isto funciona até com Microsoft JVM (dá para entender?)

Esse construtor de InternetAddress que recebe o encoding também mexe no cabeçalho e o codifica usando “Q Encoding” ou “B Encoding”. Isso torna possível mandar os cabeçalhos do email sem dar problemas.

InternetAddress[] addressesTo = new InternetAddress[] {
                new InternetAddress("[email removido]", "Luís Inácio Lula da Silva",  "ISO-8859-1"),
                new InternetAddress("[email removido]", "Antônio Palocci",  "ISO-8859-1"),
            };
            msg.setRecipients(Message.RecipientType.TO, addressesTo);
            msg.setSentDate(new java.util.Date());
            msg.setSubject("Protesto contra os impostos escorchantes");
C

Olá thingol,

valeu pela resposta. Realmente funcionou. Como é que eu não vi isso antes? :shock:

Se bem que eu já havia descoberto um jeito de resolver o problema, com o seguinte código:

enderecoCc = InternetAddress.parse(MimeUtility.encodeText(endCc[0]) + " <" + endCc[1] + “>”)

Mais eu achei esta forma que você descreveu mais limpa e clara. Vou usa-la :wink:

Obrigado.

Criado 31 de março de 2005
Ultima resposta 4 de abr. de 2005
Respostas 3
Participantes 2