JavaMail中文附件处理(转载)

 

package  mail;

import  java.io.IOException;
import  java.io.UnsupportedEncodingException;

import  java.util.Date;
import  java.util.List;
import  java.util.Map;
import  java.util.Properties;
import  javax.activation.DataHandler;
import  javax.activation.FileDataSource;
import  javax.mail. * ;
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;

import  com.opensymphony.xwork2.ActionContext;
import  org.apache.commons.logging.Log;
import  org.apache.commons.logging.LogFactory;

public   class  sendMail  {
    
private List<String> fujian;
    
private List<String> fujianContentType;
    
private List<String> fujianFileName;

    
private mailConfig mailconfig;
    
private user.YongHu yh;
    
private String to_mailAddress;// 收件人
    private String subject;// 主题
    private String content;// 信件内容
    private String from_mailAddress;// 发件人
    private String Msg;
    
private static Log log = LogFactory.getLog(sendMail.class);
    
    


    
// 初始化
    private void init() throws Exception {
         Map session
=(Map) ActionContext.getContext().get("session");
        
if (this.yh == null{
            
this.yh = new user.YongHu();
            
if (session.get(Struts2.sessionVariableName.userName) == null{
                
throw (new Exception("你还没有登陆"));
            }
 else {
                
this.yh.setDomain((String) session.get(Struts2.sessionVariableName.userDomain));
                
this.yh.setName((String) session.get(Struts2.sessionVariableName.userName));
                
this.yh.setPassword((String) session.get(Struts2.sessionVariableName.userPassWord));
            }

        }


        
if ("".equals(this.from_mailAddress)) {
            
this.from_mailAddress = yh.getName() + "@" + yh.getDomain();
        }


    }


    Multipart mm 
= new MimeMultipart();// 新建一个MimeMultipart对象用来存放多个BodyPart对象

    
// 发送邮件
    public String sendmail() {
        
        
try {
            
            init();
            Map application
= (Map) ActionContext.getContext().get("application");
            mailConfig mailconfig 
= (mailConfig) application.get(Struts2.sessionVariableName.mailConfig);
            Properties props 
= new Properties();
            props.put(
"mail.smtp.host", mailconfig.getSendHost());// 存储发送邮件服务器
            props.put("mail.smtp.auth""true");// 是否通过验证
            Session s = Session.getInstance(props);
            
// s.setDebug(true);
            MimeMessage message = new MimeMessage(s);
            
// --给消息对象设置发件人、收件人、主题、发信时间--

            
// 设置发件人
            if (this.from_mailAddress == null{    
                
this.from_mailAddress = this.yh.getName() + "@"
                        
+ this.yh.getDomain();
            }

            message.setFrom(
new InternetAddress(this.from_mailAddress));
            
if ("".equals(this.to_mailAddress) || this.to_mailAddress == null{
                
throw (new Exception("收件人不能为空"));
            }

            InternetAddress to 
= new InternetAddress(this.to_mailAddress);
            message.setRecipient(Message.RecipientType.TO, to);
// 设置收件人,并设置其接收类型为TO
            message.setSubject(this.subject);// 设置主题
            message.setSentDate(new Date());// 设置信件日期
            TianJiaNeiRong();
            TianJiaFuJian();
            message.setContent(mm);
// 把mm作为消息对象的内容
            message.saveChanges();

            Transport transport 
= s.getTransport(mailconfig.getSendProtocol());
            
// 以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数为密码
            
// transport.connect(mailconfig.getSendHost(),yh.getName()+"%"+yh.getDomain(),yh.getPassword());
            transport.connect(mailconfig.getSendHost(), yh.getName(), yh
                    .getPassword());        
            
            transport.sendMessage(message, message.getAllRecipients());
            
            log.info(message.toString());
            transport.close();
            Msg 
= "邮件已发送";
            
return "success";
        }
 catch (Exception e) {
            Msg 
= "发送失败:" + e.getMessage();
            
return "failed";
        }

    }


    
// 添加邮件内容
    private void TianJiaNeiRong() throws MessagingException {
        BodyPart mdp 
= new MimeBodyPart();
        
//mdp.setText(this.content);    
        mdp.setContent(this.content,  "text/html;charset="UTF-8"" );
        mm.addBodyPart(mdp);
    }


    
// 添加多个附件
    private void TianJiaFuJian() throws MessagingException, IOException {
        
for (int i = 0; i < this.fujian.size(); i++{
            
if (fujianFileName.get(i) != ""{
                BodyPart mdp 
= new MimeBodyPart();
                String path 
= fujian.get(i).toString();
                FileDataSource fds 
= new FileDataSource(path);
                DataHandler dh 
= new DataHandler(fds);
                mdp.setDataHandler(dh);                
                log.info(
"附件名:"+fujianFileName.get(i));
                
//mailCaoZuo.base64encode()的作用是防止文件名乱码
                mdp.setFileName(MimeUtility.encodeText(fujianFileName.get(i)));// 加上文件名将作为附件发送,否则将作为信件的文本内容;MimeUtility.encodeText()函数是把中文的文件名转换为base64编码,可以用
MimeUtility.decodeText()解码;只有编码后你所发送的邮件才能被其他软件正确解析否则乱码!
                log.info("编码后的附件名:"+mdp.getFileName());                
                mm.addBodyPart(mdp);
// 将含有附件的BodyPart加入到MimeMultipart对象中
            }
        }

    }


    
public void setTo_mailAddress(String to_mailAddress) {
        
this.to_mailAddress = to_mailAddress;
    }


    
public void setSubject(String subject) {
        
if ("".equals(subject)) {
            subject 
= "无标题";
        }
        
        
try {
            
this.subject=MimeUtility.encodeText( subject,"UTF-8","B");
                         
//MimeUtility.decodeText()邮件头的解码
        }
 catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
    }


    
public void setContent(String content) {
        
if ("".equals(content)) {
            content 
= " ";
        }
    
            
this.content = content;    //邮件体在javamail里面是不需要编码的,javamail会自动编码
    }


    
public void setFrom_mailAddress(String from_mailAddress) {

        
this.from_mailAddress = from_mailAddress;
    }


    
public void setYh(user.YongHu yh) {
        
this.yh = yh;
    }


    
public String getMsg() {
        
return Msg;
    }


    
public void setFujian(List<String> fujian) {
        
this.fujian = fujian;
    }


    
public void setFujianContentType(List<String> fujianContentType) {
        
this.fujianContentType = fujianContentType;
    }


    
public void setFujianFileName(List<String> fujianFileName) {
        
this.fujianFileName = fujianFileName;
    }


    
public mailConfig getMailconfig() {
        
return mailconfig;
    }


    
public void setMailconfig(mailConfig mailconfig) {
        
this.mailconfig = mailconfig;
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值