JavaMail sending mail attachment from string - encoding UTF-8

前端 未结 8 2075
面向向阳花
面向向阳花 2021-02-03 22:34

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

8条回答
  •  旧巷少年郎
    2021-02-03 23:09

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

提交回复
热议问题