java实现邮件发送、抄送、密送、多个附件发送

package com.asiacom.Email;

import javax.mail.Authenticator;  
import javax.mail.PasswordAuthentication;  
  
/** 
 * 用户名和密码的验证 
 */  
public class MailAuthenticator extends Authenticator{  
    private  String username="[email protected]";     
    private  String password="XXX";     
      
    public MailAuthenticator() {  
        super();  
    }  
      
    /** 
     * 设置验证的用户名和密码 
     */  
    public MailAuthenticator(String userName , String password) {  
        super();  
        this.username = userName;  
        this.password = password;  
    }  
    protected PasswordAuthentication getPasswordAuthentication()  
    {     
        return new PasswordAuthentication(this.username,this.password);     
    }     
}  

package com.asiacom.Email;

import java.util.Date;  

public class EmailMessage   
{  
    /** 
     * 邮件的信息,可以自己进行设置。 
     * 为了方便直接全部设置为静态 
     */  
      
	//收件人邮箱  
    public  static String TO = "XXX@XXX";     
    //发件人邮箱  
    public  static String FROM = "[email protected]";  
    public  static String PASSWORD="";
    //名字
    public  static String FROM_NAME = "XXX";   
    //抄送人  (多人时以‘,’隔开)    
    public  static String CC="[email protected]";      
    //密送  
    public  static String BCC="[email protected]";         
    //邮件的类型  
    public  static String Email_Content = "text/plain";  
    //邮件标题  
    public  static String Email_Subject = "Test Email With JavaMail";     
    //邮件头  
    public  static String Email_Header = "This Is Email Header";      
    //内容  
    public  static String Email_Body = "<a href=\"http://www.asiacom.tk\">This Is Email Body</a>";   
    //服务器 比如163的可以设置为smtp.163.com  
    public  static String Email_Host = "smtp.XXX.com";            
    //发送时间  
    public  static Date sendDate = new Date();    
    //是否需要验证用户名和密码  
    public  static boolean validate = true;       
}  

package com.asiacom.Email;

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

import javax.activation.DataHandler;  
import javax.activation.DataSource;  
import javax.activation.FileDataSource;  
import javax.mail.Address;  
import javax.mail.Authenticator;  
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;  
  
  
public class SendEmail   
{  
      
    /**   
    * 发送普通邮件   
    * @throws Exception   
    */     
    public void doSendNormalMail(){     
    	//获取系统环境    
        Properties prop = new Properties();    
        Authenticator auth = null;  
        //判断发送邮件是否需要验证  
        if (EmailMessage.validate){  
        	//邮件服务器认证   用户名和密码  
            auth =  new MailAuthenticator();    
        }  
        //添加必要的信息  
        prop.put("mail.smtp.host", EmailMessage.Email_Host);     
        prop.put("mail.smtp.auth", "true");     
          
        //设置对话和邮件服务器进行通讯  
        Session session = Session.getDefaultInstance(prop, auth);     
        //在控制台显示Debug信息  
        session.setDebug(true);  
        //设置邮件对象  
        Message message = new MimeMessage(session);     
        try{     
        	//设置邮件主题   
            message.setSubject(EmailMessage.Email_Subject);     
            //设置邮件标题     
            message.setHeader("Header", EmailMessage.Email_Header);   
            //设置发送时间     
            message.setSentDate(EmailMessage.sendDate);  
              
            //设置发信人地址  和 名字  
            Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME);     
            //把发件人信息添加到信息中  
            message.setFrom(address);     
              
            //设置发件人地址  
            Address toAddress = new InternetAddress(EmailMessage.TO);   
            //设置接收人地址  
            message.setRecipient(Message.RecipientType.TO, toAddress);  
            //设置多个收件人地址     
            //message.addRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));   
            /*
             * 发送多人
	            List to=new ArrayList();
	            to.add(0, "XXXg@XX");
	            to.add(1,"[email protected]");
	            String toList = null; 
	            toList = getMailList(to); 
	            InternetAddress[] iaToList = InternetAddress().parse(toList); 
	            message.setRecipients(Message.RecipientType.TO, iaToList); // 收件人 
             */   
          	//抄送
            InternetAddress[] iaToListcs = InternetAddress.parse(EmailMessage.CC); 
            message.setRecipients(Message.RecipientType.CC, iaToListcs); // 抄送人 
            //密送
            InternetAddress[] iaToListms = InternetAddress.parse(EmailMessage.BCC); 
            message.setRecipients(Message.RecipientType.BCC, iaToListms); // 密送人 
            //设置邮件格式  
            message.setContent("Content", EmailMessage.Email_Content);   
            //设置邮件内容    必须在设置文件格式后面  
            message.setText(EmailMessage.Email_Body);   
              
            //保存上面添加的信息  
            message.saveChanges();     
            //发送邮件   
            System.out.println("sendNormalEmail() 开始发送邮件...");     
            Transport.send(message);     
            System.out.println("发送成功!");     
        } catch (Exception e)  {     
        	System.out.println("出现错误");     
                e.printStackTrace();     
        }     
    }     
      
    /** 
     * 发送HTML格式的邮件 
     */  
    public void doSendHtmlMail() {     
    	//获取系统环境    
        Properties prop = new Properties();    
  
        Authenticator auth = null;  
        if (EmailMessage.validate){  
        	//邮件服务器认证   用户名和密码  
            auth = new MailAuthenticator();  
        }  
        //添加必要的信息  
        prop.put("mail.smtp.host", EmailMessage.Email_Host);     
        prop.put("mail.smtp.auth", "true");     
          
        //设置对话和邮件服务器进行通讯  
        Session session = Session.getDefaultInstance(prop, auth);     
          
        //设置邮件对象  
        Message message = new MimeMessage(session);     
        try   
        {     
        	//设置邮件主题   
            message.setSubject(EmailMessage.Email_Subject);     
            //设置邮件标题     
            message.setHeader("Header", EmailMessage.Email_Header);   
            //设置发送时间     
            message.setSentDate(EmailMessage.sendDate);  
              
            //设置发信人地址  和 名字  
            Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME);     
            //把发件人信息添加到信息中  
            message.setFrom(address);     
              
            //设置发件人地址  
            Address toAddress = new InternetAddress(EmailMessage.TO);   
            //设置接收人地址  
            message.setRecipient(Message.RecipientType.TO, toAddress);   
            //设置发送信息的内容   下面为发送html 
            //设置邮件格式  
            EmailMessage.Email_Content = "text/html; charset=utf-8";  
            message.setContent(EmailMessage.Email_Body, EmailMessage.Email_Content);   
  
            //保存上面添加的信息  
            message.saveChanges();     
            //发送邮件   
            System.out.println("开始发送邮件...");     
            Transport.send(message);     
            System.out.println("发送成功!");     
        } catch (Exception e){     
                System.out.println("出现错误");     
                e.printStackTrace();     
        }     
    }     
    /** 
     * 发送带有附件格式的邮件 
     */  
    public void doSendAttachmentMail(){     
    	//获取系统环境    
        Properties prop = new Properties();    
  
        Authenticator auth = null;  
        if (EmailMessage.validate){  
        	//邮件服务器认证   用户名和密码  
            auth = new MailAuthenticator();  
        }  
        //添加必要的信息  
        prop.put("mail.smtp.host", EmailMessage.Email_Host);     
        prop.put("mail.smtp.auth", "true");     
          
        //设置对话和邮件服务器进行通讯  
        Session session = Session.getDefaultInstance(prop, auth);     
          
        //设置邮件对象  
        Message message = new MimeMessage(session);     
        try   
        {     
        	//设置邮件主题   
            message.setSubject(EmailMessage.Email_Subject);     
            //设置邮件标题     
            message.setHeader("Header", EmailMessage.Email_Header);   
            //设置发送时间     
            message.setSentDate(EmailMessage.sendDate);  
              
            //设置发信人地址  和 名字  
            Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME);     
            //把发件人信息添加到信息中  
            message.setFrom(address);     
              
            //设置发件人地址  
            Address toAddress = new InternetAddress(EmailMessage.TO);   
            //设置接收人地址  
            message.setRecipient(Message.RecipientType.TO, toAddress);     
               
            //设置发送信息的内容   下面为发送附件  
            message.setContent(EmailMessage.Email_Body, EmailMessage.Email_Content);   
              
            BodyPart messageBodyPart = new MimeBodyPart();     
            messageBodyPart.setText("bodypart");     
              
            Multipart multipart = new MimeMultipart();     
            multipart.addBodyPart(messageBodyPart);  
            List<Map<String,String>> fileList=new ArrayList<Map<String, String>>();
            Map<String,String> map =new HashMap<String,String>();
            Map<String,String> map1 =new HashMap<String,String>();
            map.put("name", "newout.xl");
            map.put("address", "E:\\newout.xls");
            map1.put("name", "123文件名.xls");
            map1.put("address", "E:\\123文件名.xls");
            fileList.add(0, map);
            fileList.add(1, map1);
            for(int i=0;i<fileList.size();i++){
	            messageBodyPart = new MimeBodyPart();
	            //设置上传的资源  
	            DataSource source = new FileDataSource(fileList.get(i).get("address"));    
	            //添加到  
	            messageBodyPart.setDataHandler(new DataHandler(source));     
	            //设置文件名称,记得后缀名  
	            messageBodyPart.setFileName(fileList.get(i).get("name"));     
	            multipart.addBodyPart(messageBodyPart);    
	              
	            message.setContent(multipart);  
	
	            //保存上面添加的信息  
	            message.saveChanges();
            }     
            //发送邮件   
            System.out.println("doSendAttachmentMail() 开始发送邮件……");     
            Transport.send(message);     
            System.out.println("发送成功!");     
        } catch (Exception e){     
                System.out.println("出错");     
                e.printStackTrace();     
        }     
    } 
    /*
     * 遍历List返回字符串
     */
    private String getMailList(List mailArray) { 

    	StringBuffer toList = new StringBuffer(); 
    	int length = mailArray.size(); 
    	if (mailArray != null && length < 2) { 
    		toList.append(mailArray.get(0)); 
    	} else { 
	    	for (int i = 0; i < length; i++) { 
		    	toList.append(mailArray.get(i)); 
		    	if (i != (length - 1)) { 
		    	toList.append(","); 
		    	} 
	
	    	} 
    	} 
    	return toList.toString(); 

    } 
    /** 
     * @param args 
     */  
    public static void main(String[] args)  
    {  
      //new SendEmail().doSendNormalMail();  
      //new SendEmail().doSendHtmlMail();  
      new SendEmail().doSendAttachmentMail();  
    }  
  
}


你可能感兴趣的:(java实现邮件发送、抄送、密送、多个附件发送)