javamail发送excel附件

*

1,附件名乱码解决

Multipart mm = new MimeMultipart();
BodyPart mdp = new MimeBodyPart();

mdp.setFileName(MimeUtility.encodeWord(attachname));

2,新方法发送附件

public void sendAttachByTemplate(File file,
            TBaseMailset from, String toEmail,String attachname) {
        String subject = "薪酬通知邮件";
        try {
            getMailSession().setDebug(true);
            Message msg = new MimeMessage(getMailSession());
            //发件人
            if(from!=null&&!"".equals(from.getMail())){
                msg.setFrom(new InternetAddress(from.getMail()));//邮箱地址
            }else{
                msg.setFrom(new InternetAddress("lantuo103@163.com"));//邮箱地址
            }
            //收件人
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toEmail));
            //设置主题
            msg.setSubject(subject);
            //发送时间
            msg.setSentDate(new java.util.Date());

            // 添加附件
            Multipart mm = new MimeMultipart();
            BodyPart mdp = new MimeBodyPart();
            ///E:/JavaWorkspace/rs/WebRoot/WEB-INF/classes/xlsresult/ygxc.xls
            //File file = new File(this.getClass().getResource("/").getPath()+"xlsresult/ygxc.xls"); 
            FileDataSource fds = new FileDataSource(file);
            DataHandler dh = new DataHandler(fds);
            //mdp.setFileName("salary.xls");//设置后缀为xls的名字后就可以发送excel附件了
            //mdp.setFileName(attachname);//设置后缀为xls的名字后就可以发送excel附件了
            mdp.setFileName(MimeUtility.encodeWord(attachname));//设置后缀为xls的名字后就可以发送excel附件了
            
            //mdp.setFileName(URLEncoder.encode(attachname, "UTF-8"));
            
            mdp.setDataHandler(dh);
            mm.addBodyPart(mdp);
            msg.setContent(mm);
            
            Transport transport = mailSession.getTransport("smtp");
            //transport.connect("smtp.163.com", "lantuo103@163.com", "lantuo");
            if(from!=null){ //如果没有设置发送邮箱
                transport.connect(from.getServerHost(), from.getMail(), from.getMailPassword());
            }else{
                transport.connect("smtp.163.com", "lwww@163.com", "lwww");
            }
            transport.sendMessage(msg, msg.getAllRecipients());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
package com.magnetic.project.util.mail;


/** 
* 发送邮件需要使用的基本信息 
*/ 
import java.util.Properties; 
public class MailSenderInfo { 
    // 发送邮件的服务器的IP和端口 
    private String mailServerHost; 
    private String mailServerPort = "25"; 
    // 邮件发送者的地址 
    private String fromAddress; 
    // 邮件接收者的地址 
    private String toAddress; 
    // 登陆邮件发送服务器的用户名和密码 
    private String userName; 
    private String password; 
    // 是否需要身份验证 
    private boolean validate = false; 
    // 邮件主题 
    private String subject; 
    // 邮件的文本内容 
    private String content; 
    // 邮件附件的文件名 
    private String[] attachFileNames;     
    /** 
      * 获得邮件会话属性 
      */ 
    public Properties getProperties(){ 
      Properties p = new Properties(); 
      p.put("mail.smtp.host", this.mailServerHost); 
      p.put("mail.smtp.port", this.mailServerPort); 
      p.put("mail.smtp.auth", validate ? "true" : "false"); 
      return p; 
    } 
    public String getMailServerHost() { 
      return mailServerHost; 
    } 
    public void setMailServerHost(String mailServerHost) { 
      this.mailServerHost = mailServerHost; 
    }
    public String getMailServerPort() { 
      return mailServerPort; 
    }
    public void setMailServerPort(String mailServerPort) { 
      this.mailServerPort = mailServerPort; 
    }
    public boolean isValidate() { 
      return validate; 
    }
    public void setValidate(boolean validate) { 
      this.validate = validate; 
    }
    public String[] getAttachFileNames() { 
      return attachFileNames; 
    }
    public void setAttachFileNames(String[] fileNames) { 
      this.attachFileNames = fileNames; 
    }
    public String getFromAddress() { 
      return fromAddress; 
    } 
    public void setFromAddress(String fromAddress) { 
      this.fromAddress = fromAddress; 
    }
    public String getPassword() { 
      return password; 
    }
    public void setPassword(String password) { 
      this.password = password; 
    }
    public String getToAddress() { 
      return toAddress; 
    } 
    public void setToAddress(String toAddress) { 
      this.toAddress = toAddress; 
    } 
    public String getUserName() { 
      return userName; 
    }
    public void setUserName(String userName) { 
      this.userName = userName; 
    }
    public String getSubject() { 
      return subject; 
    }
    public void setSubject(String subject) { 
      this.subject = subject; 
    }
    public String getContent() { 
      return content; 
    }
    public void setContent(String textContent) { 
      this.content = textContent; 
    } 
} 

**

package com.magnetic.project.util.mail;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
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 com.magnetic.project.po.TRsYgxc;

public class MailService {

    Session mailSession = null;

    public Session getMailSession() {
        if (mailSession == null) {
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            mailSession = Session.getInstance(props, null);
        }
        return mailSession;
    }

    public void sendAttachBySys(Map<String, List<String>> map,
            String fromEmail, String toEmail) {
        String subject = "薪酬通知邮件";
        try {
            getMailSession().setDebug(true);
            Message msg = new MimeMessage(getMailSession());
            msg.setFrom(new InternetAddress(fromEmail));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toEmail));
            msg.setSubject(subject);
            msg.setSentDate(new java.util.Date());

            // 添加附件
            Multipart mm = new MimeMultipart();
            BodyPart mdp = new MimeBodyPart();
            StringBuffer sb = new StringBuffer();
            String salaryTime=null;
            sb.append("用户名	工号	薪酬月份	基本工资	绩效奖金	其他补贴	其他补贴备注	其他奖励1	其他奖励1备注	其他奖励2"+
                        "	其他奖励2备注	过节费	扣罚	扣罚备注	应发工资合计	个人住房公积金	个人基本养老保险"+
                        "	个人医疗保险	个人失业保险	个人企业年金	其他保险	他代扣费用"+
                        "	应税工资	税金	扣款合计	互助前实发	互助保险	合计	总部已发放	代扣工会经费	实发"+
                        "	雇主住房公积金缴费	雇主基本养老保险缴费	雇主医疗保险缴费	雇主生育保险缴费	雇主工伤保险缴费"+
                        "	雇主失业保险缴费	雇主企业年金缴费	雇主其他保险缴费	误餐餐补	交通费	电话费"+
                        "	差旅费	其他1	其他2	其他合计
");
            if (map != null && !map.isEmpty()) {
                for (String key : map.keySet()) {
                    List<String> list = map.get(key);
                    for (int i = 0; i < list.size(); i++) {
                        String value = list.get(i);
                        if(i==2){
                            salaryTime=value;
                        }
                        if (i == 0) {
                            sb.append(value);
                        } else {
                            sb.append("	" + value);
                        }

                    }
                    sb.append("
");
                }
            }

            
            DataHandler dh = new DataHandler(sb.toString(),
                    "text/plain;charset=gb2312");
            mdp.setFileName("salary"+salaryTime+".xls");
            mdp.setDataHandler(dh);
            mm.addBodyPart(mdp);
            msg.setContent(mm);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect("smtp.163.com", "lantuo103@163.com", "lantuo");
            transport.sendMessage(msg, msg.getAllRecipients());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void sendAttachBySys(TRsYgxc ygxc,
            String fromEmail, String toEmail) {
        String subject = "薪酬通知邮件";
        try {
            getMailSession().setDebug(true);
            Message msg = new MimeMessage(getMailSession());
            msg.setFrom(new InternetAddress(fromEmail));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toEmail));
            msg.setSubject(subject);
            msg.setSentDate(new java.util.Date());

            // 添加附件
            Multipart mm = new MimeMultipart();
            BodyPart mdp = new MimeBodyPart();
            StringBuffer sb = new StringBuffer();
            sb.append("用户名	工号
");
            System.out.println((ygxc.getGrqynj()==null)+"ttttttttttttt");
            System.out.println((ygxc.getGrqynj())+"ttttttttttttt");
            sb.append(ygxc.getUser().getUserName()+"	"+
                    ygxc.getUser().getUserLoginAcount()+"	"+
                    ygxc.getXcyf()==null?"":ygxc.getXcyf()+"	"+
                

                
                DataHandler dh = new DataHandler(sb.toString(),
                        "text/plain;charset=gb2312");
                mdp.setFileName("salary"+ygxc.getXcyf()+".xls");
                mdp.setDataHandler(dh);
                mm.addBodyPart(mdp);
                msg.setContent(mm);
                Transport transport = mailSession.getTransport("smtp");
                transport.connect("smtp.163.com", "lantuo103@163.com", "lantuo");
                transport.sendMessage(msg, msg.getAllRecipients());

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

**

package com.magnetic.project.util.mail;


import javax.mail.*;
  
public class MyAuthenticator extends Authenticator{
    String userName=null;
    String password=null;
     
    public MyAuthenticator(){
    }
    public MyAuthenticator(String username, String password) { 
        this.userName = username; 
        this.password = password; 
    } 
    protected PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(userName, password);
    }
}
 

**

*

有问题在公众号【清汤袭人】找我,时常冒出各种傻问题,然一通百通,其乐无穷,一起探讨


原文地址:https://www.cnblogs.com/qingmaple/p/4245652.html