vikka
vikka

Reputation: 53

Arabic and JavaMail Issue

i am facing an issue in one of my struts applications. I have JSP page which accepts inputs from the user and sends to a email address. I have set the encoding in the JSP Page as follows.

<%@ page  pageEncoding="UTF-8"  contentType="text/html; charset=UTF-8" language="java"%>

Now when the user submits the form to action i use the below code to send email to the recipient.

Properties properties = new Properties();
    properties.put("mail.smtp.host", "10.51.10.44");
    properties.put("mail.smtp.port", "25");
    properties.setProperty("charset","utf-8");
    Session session = Session.getDefaultInstance(properties, null);
    try  {

            MimeMessage message = new MimeMessage(session);
            String msg = formatEmail(userForm.getContent(),userForm.getUsername(),ip,host);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject,  "UTF-8");
            BodyPart messageBodyPart = new MimeBodyPart(); 
            messageBodyPart.setHeader("Content-Type","text/plain; charset=UTF-8"); 
            System.out.println("subject :-"+subject);
            System.out.println("MESSAGE :-"+msg);
            messageBodyPart.setContent(msg.toString(), "text/html;charset=UTF-8");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart( messageBodyPart ); 
            message.setContent( multipart); 
            Transport.send(message);

But my recipient is receiving the arabic email's content and subject as junk as follows.

سيسيششسيؕكنشسيكتسيشماسيشنلاسيشتلشسيتلشسيجشسيلجسشتنسي

Please help...I know this is a encoding issue. I get success if i change the encoding of the jsp to

<%@ page  pageEncoding="UTF-8"  contentType="text/html; charset=iso-8859-1" language="java"%>

But by doing that all the other text which is retried from DB and displayed in JSP pages goes as Question mark.

Upvotes: 2

Views: 1867

Answers (2)

Ahmed Mourad
Ahmed Mourad

Reputation: 303

Pretty sure the original author no longer cares about this problem, but for future readers, this's how to solve it:

  • For a plain text body part:

    new MimeBodyPart().setText(text, "UTF-8")
    
  • For setting the subject of the email:

    msg.setSubject(subject, "UTF-8")
    
  • If you're adding an attchement the name of which is in Arabic, you need to set this system property:

    System.setProperty("mail.mime.charset", "UTF-8")
    

    JavaMail uses this property internally to get the default encoding used for the file name of the attachement.

Upvotes: 1

Rakesh Patel
Rakesh Patel

Reputation: 383

set the content also.

msg.setContent(text, "text/plain;Charset=UTF-8");

Upvotes: 5

Related Questions