How to encode an address on the Internet

code for sending email:

MimeMessage msg = new MimeMessage(session); msg.setSubject("subject", "UTF-8"); // here you specify your subject encoding msg.setContent("yourBody", "text/plain; charset=utf-8"); msg.setFrom("senderAddress"); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(address)); Transport.send(msg); 

My probe is that, as I encoded the object in utf-8, how can I encode the recipient address, i.e. new InternetAddress(address)

+8
java email
source share
2 answers

Email address must comply with RFC822

JavaMail MimeMessage uses InternetAddress :

This class is an email address on the Internet using the RFC822 syntax. Typical address syntax is in the form "user@host.domain" or "Personal name <user@host.domain>".

The RFC822 format says:

Note that RFC 822 limits the repertoire of an ASCII character . In practice, other characters (such as Γ€ or Γ©) usually work inside quoted lines used for comments (and comments), but they should not be at the appropriate addresses.

Personal names for addresses support different encodings

InternetAddress uses a personal name:

If the name contains non-US-ASCII characters, the name will be encoded using the specified encoding in accordance with RFC 2047. If the name contains only US-ASCII characters, the encoding is not performed and the name is used as is.

To set the encoding for the encoding, there is an InternetAddress # constructor . Looking at the sources:

 public InternetAddress(String address, String personal, String charset) throws UnsupportedEncodingException { this.address = address; setPersonal(personal, charset); } 

it simply calls setPersonal (..) , so it selects the method that is most convenient for you.

To find the encoding, use Charset.forName () .

+14
source share

I do this where addressString is an email address with NLS characters:

 InternetAddress address = new InternetAddress(addressString); String personal = address.getPersonal(); if(personal != null) { address.setPersonal(personal, "utf-8"); } 

getPersonal() gets the raw personal name, if any, because if you created InternetAddress with a single line or use InternetAddress.parse() , you won’t have a partial name on a separate line:

public java.lang.String getPersonal ()

Get a personal name. If the name is encoded in accordance with RFC 2047, it is decoded and converted to Unicode. If decoding or conversion is not performed, the raw data is returned as is.

Then setPersonal() sets the string again, but this time tells InternetAddress to encode it:

public void setPersonal (name java.lang.String, java.lang.String charset)

Set a personal name. If the name contains non-US-ASCII characters, then the name will be encoded using the specified encoding in accordance with RFC 2047. If the name contains only US-ASCII characters, the encoding is not performed and the name is used as is.

+3
source share

All Articles