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 vari
Give this a try:
String attachment = "Привет";
DataSource ds = new ByteArrayDataSource(attachment, "text/plain; charset=UTF-8");
messageBodyPart.setDataHandler(new DataHandler(ds));
UPDATE: (full example)
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Session;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class Main {
public static void main(String[] args) throws Exception {
String attachment = "Привет";
DataSource ds = new ByteArrayDataSource(attachment, "text/plain; charset=UTF-8");
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(ds));
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("Hello this is some text");
MimeMultipart mp = new MimeMultipart("mixed");
mp.addBodyPart(bodyPart);
mp.addBodyPart(attachmentPart);
MimeMessage msg = new MimeMessage((Session)null);
msg.setContent(mp);
msg.writeTo(System.out);
}
}
output:
Message-ID: <1439781957.1.1297366787857.JavaMail.dnault@dnault.local>
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_0_1579321858.1297366787792"
------=_Part_0_1579321858.1297366787792
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Hello this is some text
------=_Part_0_1579321858.1297366787792
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: base64
0J/RgNC40LLQtdGC
------=_Part_0_1579321858.1297366787792--