Many of my friends have used javamail to send emails. garbled characters in the email body are easy to solve. However, no matter how you transcode the subject, a bunch of garbled characters are always displayed. What should I do?
The email subject in javamail must be base64-encoded,
Format:
=? Gb2312? B? Xpq1xmpcwuvs0b6t1tjww6osx + u + OB/stcfcvkossqlq3rjew9zc66oh? =
Therefore, use MSG directly. setsubject ("Chinese topic"), or MSG. setsubject ("Chinese topic ". getbytes ("8859_1"), "gb2312") are both garbled.
Before setting a subject, encode the topic string in base64 format and add an encoding header. The sample code is as follows:
Try {
String subject = "China National helloworld ";
String content = "test the language problem in the email. helloworld ";
Context CTX = new initialcontext ();
If (CTX = NULL)
Throw new exception ("no context ()");
System. Out. println (CTX );
Javax. Mail. Session mailsession = (javax. Mail. Session) CTX. Lookup ("Java: COMP/ENV/mail/session ");
System. Out. println (mailsession );
Message MSG = new mimemessage (mailsession );
Internetaddress [] toaddrs = internetaddress. parse ("david.li@maxcard.com", false );
MSG. setrecipients (message. recipienttype. To, toaddrs );
// Msg. setsubject ("=? Gb2312? B? "+ Base64.encode (subject. getbytes () + "? = ");
// Convert Chinese to gb2312 Encoding
Subject = stringutil. getstring (subject, "gb2312 ");
Subject = new string (base64.encode (subject). getbytes ()));
MSG. setsubject ("=? Gb2312? B? "+ Subject + "? = ");
MSG. setfrom (New internetaddress ("david.li@maxcard.com "));
MSG. settext (stringutil. getstring (content, "gb2312 "));
//
Transport T = mailsession. gettransport ("SMTP ");
T. Send (MSG );
Out. println ("successful ");
// Transport. Send (MSG );
} Catch (exception e ){
Out. println ("failed ");
System. Out. println (E );
}
If you have any questions, please contact: webmaster@bcxy.com
Source: http: // http://www.bcxy.com/java/cnmailsubject.htm