1
votes

I sent myself a Chinese email via gmail and I received it successfully with the following headers Successful email header

When I send a Chinese email via javax.mail it appears as follows in my mail browser failed email

The header for the failed email is as follows: enter image description here

My code is as follows:

    public boolean send() throws TestReportingException, MessagingException
    {
        try
        {

            String encodingOptions = "text/plain; charset=UTF-8";

            Authenticator authenticator = new Authenticator()
            {
                // override the getPasswordAuthentication method
                protected PasswordAuthentication getPasswordAuthentication()
                {
                    return new PasswordAuthentication(username, password);
                }
            };

            // Create the mail session
            Session session = Session.getInstance(maileProperties, authenticator);

            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setHeader("Content-Type", encodingOptions);

            // Set From: header field of the header.
            mimeMessage.setFrom(new InternetAddress(from, fromName));

            // Set To: header field of the header.
            for (String s : toList)
            {
                if (null == s)
                {
                    throw new TestReportingException("Email address is null");
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(s));
            }

            for (String s : ccList)
            {
                mimeMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(s));
            }

            // Set Subject: header field
            mimeMessage.setSubject(subject,"UTF-8");

            // Create the message part
            //MimeBodyPart messageBodyPart = new MimeBodyPart();
        //    messageBodyPart.setContent(message, encodingOptions);

            // Create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            mimeMessage.setHeader("Content-Type", encodingOptions);
            // Now set the actual message
            messageBodyPart.setText(message, "utf-8", "plain");

            // Now set the actual message
            //messageBodyPart.setText(message, "utf-8", "html");

            Multipart multipart = new MimeMultipart();

            // Set text message part
            multipart.addBodyPart(messageBodyPart);



            // Part two is attachment
            if (null != attachmentSource)
            {
                messageBodyPart = new MimeBodyPart();

                messageBodyPart.setDataHandler(new DataHandler(attachmentSource));
                messageBodyPart.setFileName(attachmentSource.getName());
                multipart.addBodyPart(messageBodyPart);

            }

            // Send the complete message parts
            mimeMessage.setContent(multipart);


            // Send message
            //Transport.send(mimeMessage);

            SSm.getLogger().debug("Subject: "+mimeMessage.getSubject());




            Transport.send(mimeMessage);

            SSm.getLogger().info("\n\nSent message successfully....");

            clear();

            return true;

        }
        catch (MessagingException mex)
        {
            SSm.getLogger().error(mex.getMessage());
            throw mex;
        }
        catch (Exception e)
        {
            SSm.getLogger().error(e.getMessage(), e);
            throw new TestReportingException(e.getMessage(), e);
        }
    }

Properties are:

  • host =smtp.gmail.com
  • mail.smtp.auth=true
  • mail.smtp.starttls.enable=true mail.smtp.host=smtp.gmail.com
  • mail.smtp.port=587 mail.mime.charset=UTF-8

NOTES: The text is not corrupted before it is sent. message.getSubject() prints out as clean Chinese text I am guessing something is wrong with the way I did the encoding

EDIT

Here's the debug output:

DEBUG: setDebug: JavaMail version 1.5.5

DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]

DEBUG SMTP: need username and password for authentication

DEBUG SMTP: useEhlo true, useAuth true

DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false

220 smtp.gmail.com ESMTP s20sm18171725pfg.11 - gsmtp

DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

>

EHLO jake-yoga3.hitronhub.home

250-smtp.gmail.com at your service, [96.49.181.179]

250-SIZE 35882577

250-8BITMIME

250-STARTTLS

250-ENHANCEDSTATUSCODES

250-PIPELINING

250-CHUNKING

250 SMTPUTF8

DEBUG SMTP: Found extension "SIZE", arg "35882577"

DEBUG SMTP: Found extension "8BITMIME", arg ""

DEBUG SMTP: Found extension "STARTTLS", arg ""

DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""

DEBUG SMTP: Found extension "PIPELINING", arg ""

DEBUG SMTP: Found extension "CHUNKING", arg ""

DEBUG SMTP: Found extension "SMTPUTF8", arg ""

STARTTLS

220 2.0.0 Ready to start TLS

EHLO jake-yoga3.hitronhub.home

250-smtp.gmail.com at your service, [96.49.181.179]

250-SIZE 35882577

250-8BITMIME

250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH

250-ENHANCEDSTATUSCODES

250-PIPELINING

250-CHUNKING

250 SMTPUTF8

DEBUG SMTP: Found extension "SIZE", arg "35882577"

DEBUG SMTP: Found extension "8BITMIME", arg ""

DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH"

DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""

DEBUG SMTP: Found extension "PIPELINING", arg ""

DEBUG SMTP: Found extension "CHUNKING", arg ""

DEBUG SMTP: Found extension "SMTPUTF8", arg ""

DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2

DEBUG SMTP: Using mechanism LOGIN

DEBUG SMTP: AUTH LOGIN command trace suppressed

DEBUG SMTP: AUTH LOGIN succeeded

DEBUG SMTP: use8bit false

MAIL FROM:

250 2.1.0 OK s20sm18171725pfg.11 - gsmtp

RCPT TO:

250 2.1.5 OK s20sm18171725pfg.11 - gsmtp

DEBUG SMTP: Verified Addresses

DEBUG SMTP: [email protected]

DATA

354 Go ahead s20sm18171725pfg.11 - gsmtp

From: iKoda Report

To: [email protected]

Message-ID: <1926337998.1.1488002481716@jake-yoga3>

Subject: =?UTF-8?B?QnZ4Y2Igw6TCuMKtIMOkwrjCrSDDpMK4wq0gw6TCuMKtIMOkwrjCrQ==?=

MIME-Version: 1.0

Content-Type: multipart/mixed;

   boundary="----=_Part_0_1855484302.1488002481637"

>

------=_Part_0_1855484302.1488002481637

Content-Type: text/plain; charset=utf-8

Content-Transfer-Encoding: base64

>

RGVhciBaeGN2LA0KDQpCdnhjYiDDpMK4wq0gw6TCuMKtIMOkwrjCrSDDpMK4wq0gw6TCuMKtw6TC

uMKtIMOkwrjCrSDDpMK4wq0gw6TCuMKtIMOkwrjCrWh0dHBzOi8vd3d3Lmkta29kYS5jb20vZGVs

aXZlcnkvZHNmcj91ZnQ9MTAxMjc3MCZjPTEwMTI3NjTDpMK4wq0gw6TCuMKtIMOkwrjCrSDDpMK4

wq0gw6TCuMKt

------=_Part_0_1855484302.1488002481637--

.

250 2.0.0 OK 1488002489 s20sm18171725pfg.11 - gsmtp

DEBUG SMTP: message successfully delivered to mail server

QUIT

221 2.0.0 closing connection s20sm18171725pfg.11 - gsmtp

[INFO] "jake.app" com.ikoda.service.utilities.EmailOut.send(EmailOut.java:256) 01:27:

>

Sent message successfully....

>

1
First, fix these common JavaMail mistakes. Did you copy your code from this other post? Even the comments are surprisingly similar. What version of JavaMail are you using? What does the JavaMail debug output show?Bill Shannon
yes, I reposted as the other post had a major human error in it. I'm not seeing any of the common errors, The authenticator may not be ideal, but it works. I'll look into the javamail logs. Thanks for the tipJake
What major human error? And, fix Session.getDefaultInstance. "It works" is not the same as "it's correct". None of these are probably the cause of your problem, but that's why I want to see the JavaMail debug output.Bill Shannon
oops, OK. I've fixed that. I have also added the debug output from javax.mail. I am unusually stick on this. I usually get through this kind of issues in a couple of hours. Any advice would be deeply appreciatedJake
If you send the message from Gmail to Gmail and it works, you should be able to construct an equivalent message using JavaMail. Your first example above looks like the Subject isn't encoded at all, which is definitely a mistake. Is your browser running in a Chinese locale? That may be the only reason that works. You might want to try reading the messages using another mail reader such as Thunderbird.Bill Shannon

1 Answers

0
votes

I have found the problem. The problem was NOT in the Email class and only tangentially related to javamail. (so the code above is correct)

The problem is in extracting the text from a hotwired instance of Spring's MessageBundle in my Controller.

I INCORRECTLY used the following code so that my logging class could log the Strings pulled from the message bundle.

byte[] barray =messageSource.getMessage(code, null, LocaleContextHolder.getLocale()).getBytes(Charset.forName("UTF-8"));
    String s = new String(barray);

Log4j could read the Strings in the subject and message (built by StringBuilder) which led me to believe that the Strings were in correct UTF-8. However, javax.mail garbled the in transmission.

What I should have done is this:

messageSource.getMessage(code, null, LocaleContextHolder.getLocale())

Now my logger just gets ???, but the email sends just fine.

So, Keep It Simple Stupid.