Alex Rivera | Logout

JavaMail sending mail attachment from string - encoding UTF-8

Asked 2011-02-10T17:31:06.570
30

My application has to send a textfile, which it first has to generate as a String. The text contains non-ASCII symbols, so i would like it to be UTF-8. I've tried a lot of variants, but all i receive as the attachment is some question marks. And, when i send the same text as the message body, it works all right.

Here is the line of code that generates the MimeBodyPart with the attachment:

String attachment = "Привет";
messageBodyPart.setContent(new String(attachment.getBytes("UTF-8"),
    "UTF-8"),"text/plain; charset=UTF-8");

I also tried using the string without any transformations, using just the bytes, now, as you see, i am trying to generate a string from the bytes...

What am i doing wrong? (And i do remember doing this in another project, which works, but i no longer have the access to its source code).

Thank you in advance. Timofey.

UPDATE

Having read your replies, and after some more unsuccessful experimenting i thought it best to publish the code of my mailing thing. I have the Mailer class, which does the mailing, and other classes can just call its static sendMessage() method to send a message. And it all runs on Google App Engine.

public static void sendMessage(String to, String subject, String msgBody,
            String attachment) throws AddressException, MessagingException {

    Properties props = new Properties();

    Session mailSession = Session.getDefaultInstance(props, null);
    Message msg = new MimeMessage(mailSession);
    String email = "bla-bla-bla"; // userService.getCurrentUser().getEmail();

    msg.setFrom(new InternetAddress(email));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    InternetAddress[] addresses = { new InternetAddress("bla-bla-bla") };

    msg.setReplyTo(addresses);
    msg.setSubject(subject);

    Calendar cal = Calendar.getInstance();

    String fil
Edit
Report

1 Answer

9

Had similar case, following code solved it:

MimeBodyPart att = new MimeBodyPart();
att.setFileName(MimeUtility.encodeText(fileName));
answered 2013-06-10T08:57:23.770

Your Answer