免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1998 | 回复: 0

用javamail发送一封有中文名的附件的邮件 [复制链接]

论坛徽章:
0
发表于 2005-07-19 23:39 |显示全部楼层

发送有中文文件名的附件的邮件用javamail通常会导致文件名出现乱码,这是因为MIME规范规定不允许encode文件名,但很多应用程序都亵渎这一规范,这已成事实的规范。
/*
* Created on 2005-7-19
*/
package com.jilaninfo.webmail;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
/**
* @author elgs
*/
public class Send
{
    public static void main(String[] args) throws Exception
    {
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "smtp.cableplus.com.cn");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.auth", "true");
        Session mailSession = Session.getInstance(props, new PopAuthenticator(
                "username", "password"));
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress("
elgs@cableplus.com.cn
"));
        String to = "
elgs@cableplus.com.cn
";
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        msg.setSentDate(new Date());
        msg.setSubject("中文标题");
        Multipart mp = new MimeMultipart();
        MimeBodyPart mbpFile = new MimeBodyPart();
        MimeBodyPart mbpText = new MimeBodyPart();
        FileDataSource fds = new FileDataSource("D:/工作流程.doc");
        mbpFile.setDataHandler(new DataHandler(fds));
        mbpFile.setFileName(MimeUtility.encodeText(fds.getName()));
        mp.addBodyPart(mbpFile);
        mbpText.setText("中文内容");
        mp.addBodyPart(mbpText);
        msg.setContent(mp);
        Transport.send(msg);
        System.out.println("Mail sent!");
    }
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4960/showart_36645.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP