现在的位置: 首页 > 综合 > 正文

Java发送email 带附件

2018年02月10日 ⁄ 综合 ⁄ 共 6677字 ⁄ 字号 评论关闭
package com.chengxi.jm.test;

import java.util.Properties;

/***
 * 邮件发送的参数类
 * 
 * @author wzh
 * @version 1.0
 */
public class Mail_SendProper {
	//邮件服务器
	private String host;
	private String port = "25";
	//邮件发送者地址
	private String sendAddress ;
	//接收地址
	private String receiveAddress = "372849177@qq.com";
	
	//是否需要验证
	private boolean isValidate ;
	
	private String username;
	private String password;
	
	private String  subject;//邮件主题
	private String  content;//邮件内容
	
	private String[] attacheFileName;//邮件附件的名称
	private String[] recs;//存储接收者邮件地址
	
	public Properties getProperties(){
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.post", port);
		properties.put("mail.smtp.auth",isValidate?"true":"false");
		
		return properties;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public String getSendAddress() {
		return sendAddress;
	}

	public void setSendAddress(String sendAddress) {
		this.sendAddress = sendAddress;
	}

	public String getReceiveAddress() {
		return receiveAddress;
	}

	public void setReceiveAddress(String receiveAddress) {
		this.receiveAddress = receiveAddress;
	}

	public boolean isValidate() {
		return isValidate;
	}

	public void setValidate(boolean isValidate) {
		this.isValidate = isValidate;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String[] getAttacheFileName() {
		return attacheFileName;
	}

	public void setAttacheFileName(String[] attacheFileName) {
		this.attacheFileName = attacheFileName;
	}

	public String[] getRecs() {
		return recs;
	}

	public void setRecs(String[] recs) {
		this.recs = recs;
	}
	
	
}
<pre name="code" class="java">

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/***
 * 使用第三方邮件服务器登陆 <br/>
 * 验证服务器是否登陆成功
 * 
 * @author wzh
 * @version 1.0
 */
public class MailAttorney extends Authenticator{
	private String username;
	private String password;

	public MailAttorney(String username,String password){
		this.username = username;
		this.password = password;
	}
	
	/*
	 *  重写父类方法
	 */
	protected PasswordAuthentication getPasswordAuthentication() {
		PasswordAuthentication passwordAuthentication = new PasswordAuthentication(username, password);
		return passwordAuthentication;
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

package com.chengxi.jm.test;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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 wzh
 * @version 1.0
 *
 */
public class Send_Mail {
	
	
	public static boolean MailText(Mail_SendProper prop) throws MessagingException{
		MailAttorney mailAttorney = null ;
		//判断是否需要身份验证
		if(prop.isValidate()){
			mailAttorney = new MailAttorney(prop.getUsername(), prop.getPassword());
		}
		//根据邮件会话属性 和密码验证器
		Session  sendMailSession = Session.getInstance(prop.getProperties(),mailAttorney);
		//消息对象
		Message mailMessage =  new MimeMessage(sendMailSession);
		//发送者地址
		Address internetAddress = new InternetAddress(prop.getSendAddress());
		//设置发送者地址
		mailMessage.setFrom(internetAddress);
		
		//定义address数组
		Address[]  ad =null;
		String[] rec = prop.getRecs();
		
		if(rec!=null){
			ad = new InternetAddress[rec.length];
			for(int i = 0 ;i<rec.length;i++){
				ad[i] = new InternetAddress(rec[i]);
			}
		}else{
			ad = new InternetAddress[1];
			ad[0] =  new InternetAddress(prop.getReceiveAddress());
		}
		
		mailMessage.setRecipients(Message.RecipientType.TO, ad);
		mailMessage.setSubject(prop.getSubject());
		mailMessage.setContent(prop.getContent(), "text/html;chartset=gbk");
		mailMessage.setSentDate(new Date());
		
		Transport.send(mailMessage);
		return true;
	}
	
	public static boolean MailAttache(Mail_SendProper prop) throws MessagingException, UnsupportedEncodingException{
		MailAttorney mailAttorney = null ;
		//判断是否需要身份验证
		if(prop.isValidate()){
			mailAttorney = new MailAttorney(prop.getUsername(), prop.getPassword());
		}
		//根据邮件会话属性 和密码验证器
		Session  sendMailSession = Session.getInstance(prop.getProperties(),mailAttorney);
		//消息对象
		Message mailMessage =  new MimeMessage(sendMailSession);
		//发送者地址
		Address internetAddress = new InternetAddress(prop.getSendAddress());
		//设置发送者地址
		mailMessage.setFrom(internetAddress);
		
		//定义address数组
		Address[]  ad =null;
		String[] rec = prop.getRecs();
		
		if(rec!=null){
			ad = new InternetAddress[rec.length];
			for(int i = 0 ;i<rec.length;i++){
				ad[i] = new InternetAddress(rec[i]);
			}
		}else{
			ad = new InternetAddress[1];
			ad[0] =  new InternetAddress(prop.getReceiveAddress());
		}
		
		mailMessage.setRecipients(Message.RecipientType.TO, ad);
		mailMessage.setSubject(prop.getSubject());
		mailMessage.setSentDate(new Date());
		
		
		// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart();         
      
      
        //   设置邮件的文本内容
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setText("邮件的具体内容在此");
        multipart.addBodyPart(contentPart);
        //添加附件
        BodyPart messageBodyPart= new MimeBodyPart();
        DataSource source = new FileDataSource("d:\\poi搞出来的.xls");
        //添加附件的内容
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(MimeUtility.encodeText(source.getName(),"utf-8",null));
        //添加附件的标题
        //这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
       // BASE64Encoder enc = new BASE64MailboxEncoder();
        //messageBodyPart.setFileName("=?GBK?B?"+enc.encode(affixName.getBytes())+"?=");
        multipart.addBodyPart(messageBodyPart);
      
      
        //将multipart对象放到message中
        mailMessage.setContent(multipart);
		Transport.send(mailMessage);
		return true;
	}
	
	public static void main(String[] args) {
		Mail_SendProper prop = new Mail_SendProper();
		prop.setHost("smtp.163.com");
		prop.setPort("25");
		prop.setValidate(true);
		prop.setSendAddress("a372849177@163.com");
		prop.setUsername("a372849177@163.com");
		prop.setPassword("*****");
		
		
		String[] recs = new String[]{"huang@myxiaomai.com","372849177@qq.com"};
		prop.setRecs(recs);
		
		prop.setSubject("今天是"+new Date()+",keepmoving!");
		
		
		StringBuffer sb = new StringBuffer();
		sb.append("<h1>这是标题</h1>");
		sb.append("<h2><font color=red>这倒霉孩子</font></h2>");
		
		prop.setContent(sb.toString());
		
		//发送邮件
		try {
			//boolean result = MailText(prop);
			boolean result;
			try {
				result = MailAttache(prop);
				if(result){
					System.out.println("发送成功");
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

抱歉!评论已关闭.