Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Java API
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Ron McLeod
Paul Clapham
Tim Cooke
Devaka Cooray
Sheriffs:
Liutauras Vilda
paul wheaton
Rob Spoor
Saloon Keepers:
Tim Moores
Stephan van Hulst
Tim Holloway
Piet Souris
Mikalai Zaikin
Bartenders:
Carey Brown
Roland Mueller
Forum:
Other JSE/JEE APIs
Arabic characters issue in java mail
arul arumugam
Greenhorn
Posts: 1
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Hi, I have written a
java
mail program to send a mail. When I am sending arabic char they are coming as ???.
I will enclose my program kindly help me. Thanks a ton in advance.
My propery file content -sample
test1=äæÝãÈÑ
test2=ÏíÓãÈÑ
2FASubject=??? - ??? ??? ??? ???
2FAFirstLine=<p> سامبا</p>
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Calendar; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import javax.mail.Address; /** * @author aar * @param language * Class TwoFAMailer is standalone program and it reads the Report file names from anfreports.txt file then it adds all the files into zip * and sends mail to configured mail id. */ public class TwoFAMailer { public static String strArabicDisclaimerTxt = null; public static String strEnglishDisclaimerTxt = null; private static File arabicDisclaimerFile; private static File englishDisclaimerFile; private Properties props = new Properties(); private ResourceBundle en_US = null; private ResourceBundle ar_SA = null; private static final String PROPS_PATH = "/home/ibf/tuxbatch/consumer/ebank/lib/BATCHENV.properties"; private static final String DISCLAIMERDIR = "/home/ibf/tuxbatch/consumer/ebank/estatement/"; private String emailServer = ""; private String emailFrom = ""; private String emailTo = ""; private int invalidEamilInHostCount = 0; String dataFilePath = ""; String zipFileName =""; String reportTxtFileName =""; static { // load the disclaimer text during class loading. getArabicDisclaimerFromFile(); getEnglishDisclaimerFromFile(); } public TwoFAMailer() { try{ loadProperties(); }catch(Exception ex){ System.out.println( " Exception while loading properties "+ex.getMessage()); ex.printStackTrace(); } } /** * @param args-language */ public static void main(String[] args) { System.out.println(" 2FAMailer java invoked "); try { int arglength = args.length;// for validating the inputs String language = null; String mailId=""; TwoFAMailer twoFAMailer = new TwoFAMailer(); if (arglength < 1) { // Failure condition System.out.println(" Input parameter Language is missing.. "); return; } else { language = args[0]; // first argument is language if(! ("0".equals(language) || "1".equals(language) )){ System.out.println(" Language value should be either 0 or 1. 0 for english , 1 for Arabic "); return; } if( arglength == 2 ){ mailId = args[1];// second argument is mail id if (!twoFAMailer.isValidEmail(mailId)) { System.out.println(" We expect second param as email but the given Email id is not Valid kindly check or dont give email id"); return; } } } twoFAMailer.sendMail(mailId, language);//invoke sendMail method to send a mail System.out.println(" Mail had sent successfully "); } catch (Exception ex) { System.out.println(" Mail sending Failed "+ex.getMessage()); ex.printStackTrace(); } } private boolean sendMail(String mailId, String language) throws Exception { boolean sent = true; try { System.out.println( " sendMail method Entry " +mailId); Properties props = System.getProperties(); props.put("mail.smtp.host", emailServer); // Setup mail server Session session = Session.getInstance(props, null); Multipart multipart = new MimeMultipart(); // Multipart to add message & attachment MimeMessage message = new MimeMessage(session); // Define message BodyPart attachment = new MimeBodyPart(); // Create object for attachment part DataSource source = null;// to be used for file attachment in mail // Generated Report names available in file. BufferedReader inputStream = new BufferedReader(new FileReader(dataFilePath+reportTxtFileName)); String inLine = null; //To get the file names while reading from anfreports.txt file Vector fileNamesVector = new Vector();//to store the report file names String sXMailer = "Samba Message Center, MPHS/STG"; // for arabic text encoding message.setFrom(new InternetAddress(emailFrom));//set sender mail id if( mailId != null && !mailId.equals("") )// if the user gives maid id as input param then take that, else take it from configration emailTo = mailId; message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); // set recipient mail id //Set subject for the mail if (language.equals("0")) {//For language english message.setSubject(getString("2FASubject", language)); message.setHeader("X-Mailer", MimeUtility.encodeText(sXMailer,"windows-1252", null)); message.setHeader("Content-type","text/html; charset=windows-1252"); } else { message.setSubject(new String(getString("2FASubject", language).getBytes(), "windows-1256"),"windows-1256"); message.setHeader("X-Mailer",MimeUtility.encodeText(sXMailer,"windows-1256",null)); message.setHeader("Content-Type","text/html; charset=windows-1256"); } //Setting HTML contents with message object setHtmlContent(language,multipart); // Read the file names from txt file and store it in vector while ((inLine = inputStream.readLine()) != null) { //Comment : 1 : In future if the No. of files get increased also we have no impact : fileNamesVector.add(inLine);//add file names into vector } inputStream.close(); String[] sourceFileNames = new String[fileNamesVector.size()]; // Refer Comment : 1 fileNamesVector.copyInto(sourceFileNames); //copy all the objects into String array i.e all files names /* If the zip file needs with timestamp we can enable this commented block String[] strtimestamp; strtimestamp = sourceFileNames[0].split("\\.");//assume we have atleast one file zipFileName+="-"+strtimestamp[strtimestamp.length-1]; */ zipFileName+=".zip";//In configration we have only name not with extention //Call createZip to generate zip file. //this createZip method can be kept it in this same file also, but to make generic I created as new file new ZipCreator().createZip(zipFileName,sourceFileNames,dataFilePath); //zip created and placed in data folder source = new FileDataSource(dataFilePath+zipFileName); attachment.setDataHandler(new DataHandler(source)); attachment.setFileName(zipFileName); // Attachment file set here. like AnnualFeeReport-2FA.zip multipart.addBodyPart(attachment);// File attachment to multipart message.setContent(multipart);// multipart has your message and attachment Transport.send(message); // Send message - done. System.out.println( " Mail Sent successfully to : "+emailTo ); } catch (javax.mail.SendFailedException sndFailEx) { throw new Exception(sndFailEx.getMessage()); } catch (javax.mail.internet.AddressException addrsEx) { throw new Exception(addrsEx.getMessage()); } catch (Exception mail) { sent = false; System.out.println("TwoFAMailer() :: sendMail : "+ mail.getMessage()); throw new Exception(mail.getMessage()); } return sent; } private void setHtmlContent(String language,Multipart multipart){ try{ StringBuffer tableContentMsg = new StringBuffer();//to manage html content MimeBodyPart htmlPart = new MimeBodyPart(); //For html contents Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR);// Need year for copyright notice String rtl = ""; // for arabic alignment String boldTagO = "";// for arabic alignment String boldTagC = "";// for arabic alignment // Wrap the body in a TABLE with RTL -- for arabic alignment if( language.equals("1") ) { rtl = "DIR='RTL'"; boldTagO = ""; boldTagC = ""; } String sDisclaimer = getDisclaimerText(language); tableContentMsg.append("<HTML><BODY><table width='100%' " + rtl + "><tr><td>"); tableContentMsg.append(getString("2FAFirstLine", language)); tableContentMsg.append(getString("2FASeconLine", language)); tableContentMsg.append(getString("2FAthirdLine", language)); tableContentMsg.append("<p> </p>"); tableContentMsg.append("<p> </p>"); tableContentMsg.append(sDisclaimer); tableContentMsg.append("Copyright © "+year+", Samba Financial Group</font></td><td style='border-color:gray; border-top-style: solid; border-top-width:1' width='50%' align='left'><font face='Arial' size='1'> <a href='http://www.samba.com'>samba.com</a> | <a href='http://www.sambaonline.com'>sambaonline.com</a> | <a href='http://www.sambacapital.com'>sambacapital.com</a> </font></td></tr></table>"); tableContentMsg.append("</td></tr></table></BODY></HTML>"); htmlPart.setContent(new String(tableContentMsg.toString().getBytes(), "windows-1256"), "text/html; charset=windows-1256"); multipart.addBodyPart(htmlPart); // Html content attachment to multipart }catch(Exception ex){ ex.printStackTrace(); } } /** * isValidEmail method validates the given email * @param email */ private boolean isValidEmail(String email) { boolean matchFound = false; if (email != null && email.length() > 0) { // Set the email pattern string Pattern p = Pattern.compile(".+@.+\\.[a-zA-Z]+"); // Match the given string with the pattern Matcher m = p.matcher(email); // check whether match is found matchFound = m.matches(); } return matchFound; } /* * Read the Arabic disclaimer text from the file */ public static void getArabicDisclaimerFromFile() { StringBuffer buf = new StringBuffer(); String sThisLine; arabicDisclaimerFile = new File(DISCLAIMERDIR+"ArabicEStatementDisclaimer.txt"); BufferedReader br = null; try { br =new BufferedReader(new InputStreamReader(new FileInputStream(arabicDisclaimerFile),Charset.forName("Cp1256"))); while ((sThisLine = br.readLine()) != null) { buf.append(sThisLine); buf.append("\n"); } strArabicDisclaimerTxt = new String(buf.toString().getBytes("Cp1256"),"Cp1252"); br.close(); // System.out.println(" strArabicDisclaimerTxt : "+strArabicDisclaimerTxt); } catch (Exception e) { System.out.println("static block "+e); } finally { if ( br != null ) { try { br.close(); } catch(IOException close) { System.out.println("Exception closing BufferedReader "+close); } } } //System.out.println("consumer.ebank.estatement.EStatementMailer; Exit getArabicDisclaimerFromFile()"); } /* * Read the English disclaimer from the file. */ public static void getEnglishDisclaimerFromFile() { StringBuffer buf = new StringBuffer(); String sThisLine; englishDisclaimerFile = new File(DISCLAIMERDIR+ "EnglishEStatementDisclaimer.txt"); BufferedReader br = null; try { br = new BufferedReader(new FileReader(englishDisclaimerFile)); while ((sThisLine = br.readLine()) != null) { buf.append(sThisLine); buf.append("\n"); } strEnglishDisclaimerTxt = buf.toString(); br.close(); } catch (IOException e) { // printError("static block TwoFAMailer ",e); } finally { if (br != null) { try { br.close(); } catch (IOException close) { // printError("Exception closing BufferedReader ", close); } } } } private void loadProperties() throws Exception { FileInputStream fis = new FileInputStream(PROPS_PATH); props.load(fis); fis.close(); Locale localeUS = new Locale("en", "US"); en_US = ResourceBundle.getBundle("com.test.Estatement", localeUS); Locale localeSA = new Locale("ar", "SA"); ar_SA = ResourceBundle.getBundle("com.test.Estatement", localeSA); emailServer = props.getProperty("ESTATEMENT_EMAIL_SERVER").trim(); emailFrom = props.getProperty("ESTATEMENT_FROM").trim(); // Need new configration //New configurations added dataFilePath = props.getProperty("DATAFILEPATH").trim(); zipFileName = props.getProperty("ZIPFILENAME").trim(); reportTxtFileName = props.getProperty("REPORTTXTFILENAME").trim(); emailTo = props.getProperty("MAILTO").trim(); } private String getString(String _key, String language) { String value = ""; if (language.equals("0")) { value = en_US.getString(_key); } else { value = ar_SA.getString(_key); } System.out.println(" KEY :: "+_key+" VALUE :: "+value); return value; } /* * Depending on the language selected returns the disclaimer text from the appropriate file. */ private String getDisclaimerText(String language) throws Exception { // printDebug("Entry getDisclaimerText()"); if (strArabicDisclaimerTxt == null || strEnglishDisclaimerTxt == null) { throw new Exception("Disclaimer file could not be loaded"); } return (language.equals("1")) ? strArabicDisclaimerTxt: strEnglishDisclaimerTxt; } }
Yasser Abdalkarem
Greenhorn
Posts: 1
posted 13 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
try to add this :
setHeader("Content-Transfer-Encoding", "8Bit");
She still doesn't approve of my superhero lifestyle. Or this shameless plug:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
how to send multiple data in a table in a mail application?
Encoding XML file using Base64Encoder
How a character save in 2 bytes in Java?
Exception in thread "main" javax.mail.AuthenticationFailedException:
arabic text from linux to windows oc4j servers
More...