JavaMail从字符串 - UTF-8编码发送邮件附件 [英] JavaMail sending mail attachment from string - encoding UTF-8

查看:190
本文介绍了JavaMail从字符串 - UTF-8编码发送邮件附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序必须发送一个文本文件,它首先必须以String形式生成。该文本包含非ASCII符号,所以我希望它是UTF-8。我已经尝试了很多变体,但是我收到的附件是一些问号。而且,当我发送与消息体相同的文本时,它可以正常工作。

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.

以下是使用附件生成MimeBodyPart的代码行:

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).

提前谢谢。
Timofey。

Thank you in advance. Timofey.

更新

阅读了您的回复,经过一些不成功的实验,我以为最好发布邮件的代码。我有 Mailer 类,它执行邮件,其他类可以调用其静态 sendMessage()方法发送一个消息。所有这些都运行在Google App Engine上。

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 fileName = cal.get(Calendar.YEAR) + "_"
            + cal.get(Calendar.MONTH) + "_"
            + cal.get(Calendar.DAY_OF_MONTH) + "_"
            + cal.get(Calendar.HOUR_OF_DAY) + "_"
            + cal.get(Calendar.MINUTE) + "_" + cal.get(Calendar.SECOND)
            + "_" + cal.get(Calendar.MILLISECOND) + ".txt";

    // create the message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();

    // fill message
    // Here we should have the msgBody.
    // Sending attachment contents for debugging only.
    messageBodyPart.setText(attachment + " - 4", "UTF-8", "plain");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    MimeBodyPart att = new MimeBodyPart();
    att.setText(attachment, "UTF-8", "plain");
    att.addHeader("Content-Type", "text/plain; charset=UTF-8"); 

    att.setFileName(fileName);
    multipart.addBodyPart(att);

    // Put parts in message
    msg.setContent(multipart);

    Transport.send(msg);
}

在另一个类中调用这个东西的行是:

And the line that calls this thing in another class is:

Mailer.sendMessage("mymail@example.com", "Test", "No body", "Привет, Я кусок текста");

邮件的原始来源,奇怪的是(抛弃看似无关的头文件):

And the raw source of the mail, strangely enough, is (leaving out the seemingly irrelevant headers):

Message-ID: <00163662e7107ccbe3049c1402fb@google.com>
Date: Sat, 12 Feb 2011 11:21:01 +0000
Subject: Pages
From: mymail@example.com
To: mymail@example.com
Content-Type: multipart/mixed; boundary=00163662e7107ccbd4049c1402fa

--00163662e7107ccbd4049c1402fa
Content-Type: text/plain; charset=KOI8-R; format=flowed; delsp=yes
Content-Transfer-Encoding: base64

8NLJ18XULCDxIMvV08/LINTFy9PUwSAtIDQNCg==
--00163662e7107ccbd4049c1402fa
Content-Type: text/plain; charset=US-ASCII; name="2011_1_12_11_21_1_691.txt"
Content-Disposition: attachment; filename="2011_1_12_11_21_1_691.txt"
Content-Transfer-Encoding: base64

Pz8/Pz8/LCA/ID8/Pz8/ID8/Pz8/Pw==
--00163662e7107ccbd4049c1402fa--

我只是不明白,为什么字符集与我想要的不同设置,他们来自哪里。

I just don't get it, why the charsets are different from what i am trying to set, and where they come from.

推荐答案

Yippie !!!

Yippie!!!

我终于做到了!简而言之,不要将内容类型设置为text / plain,将其设置为application / octet-stream

I finally did it! In short, don't set the content type to "text/plain", set it to "application/octet-stream"

MimeBodyPart attachmentPart = new MimeBodyPart();

try {
  DataSource ds = new ByteArrayDataSource(attachment.getBytes("UTF-8"), "application/octet-stream");
  attachmentPart = new MimeBodyPart();
  attachmentPart.setDataHandler(new DataHandler(ds));
} 
catch (Exception e) {
  Logger.getLogger("Blina").log(Level.SEVERE, Misc.getStackTrace(e));
}

attachmentPart.setFileName(fileName);
multipart.addBodyPart(attachmentPart);

// Put parts in message
msg.setContent(multipart);

这篇关于JavaMail从字符串 - UTF-8编码发送邮件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆