Demo entry 6684322

java

   

Submitted by java on Dec 15, 2017 at 06:51
Language: Java. Code size: 11.6 kB.

package salaryPay.client.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;

/** 
 * 发送邮件的的工具类(JavaMail 版本:1.5.0)<br/>
 * 工具栏中方法参数无验证。传递需谨慎		
 * 
 * @author 尚吉存
 * 
 * @version 1.0 2017-11-22
 * 
 * @since JDK 1.8
 * 
 * @category SmartHR
 * */
public class SendMailUtil {

	//定义发送邮件使用的变量
	private String account; //登录账户
	private String pwd; //登录密码
	
	//默认构造方法
	private SendMailUtil(){}
	//初始化构造方法
	private SendMailUtil(String account,String pwd){
		this.account = account == null ? "":account;
		this.pwd = pwd == null ? "":pwd;
	}
	
	private static SendMailUtil instance;
	
	public static SendMailUtil getInstance(String account,String pwd){
		if(instance == null){
			synchronized(SendMailUtil.class){
				if (instance == null)
					instance = new SendMailUtil(account,pwd); 
			}
		}
		return instance;
	}
	
	/**
	 * 用户名密码验证类,需要实现抽象类Authenticator的抽象方法PasswordAuthentication
	 * */
	static class MyAuthenricator extends Authenticator{
        String userName = null;
        String password = null;
        public MyAuthenricator(String userName,String password){
            this.userName=userName;
            this.password=password;
        }
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName,password);
        }
    }
	
	/**
	 * 发送邮件				<br/>
	 * 参数无验证。传递请谨慎
	 * 
	 * @param fromMap 发件人Map(必须)。指定Key分别为:mail(发件人邮箱)、name(发件人别名。可空)。
	 * 
	 * @param toList 收件人List(必须)。List中Map的Key分别为:mail(收件人邮箱)、name(收件人别名。可空)。
	 * 
	 * @param ccList 抄送人List(非必须)。List中Map的Key分别为:mail(收件人邮箱)、name(收件人别名。可空)。
	 * 
	 * @param bccList 密送人List(非必须)。List中Map的Key分别为:mail(收件人邮箱)、name(收件人别名。可空)。
	 * 
	 * @param title 邮件标题(必须)
	 * 
	 * @param contentType 内容类型。txt(默认纯文本)、html(显示以html格式的文本内容)、annex(带附件内容)
	 * 
	 * @param content 内容。根据contentType不同。处理不同,其中txt和html差不多。
	 * 
	 * @param fileList 附件路径列表。仅在contentType为annex时使用。
	 * */
	public void SendMail(Map<String,String> fromMap,
			List<Map<String,String>> toList,List<Map<String,String>> ccList,List<Map<String,String>> bccList,
			String title,String contentType,String content,List<String> fileList){
		//创建参数配置, 用于连接邮件服务器的参数配置
		Properties prop = new Properties();
		//服务器
        prop.setProperty("mail.smtp.host", "smtp.viphrm.com"); //阿里云邮箱。如果其他邮箱。prop配置参考网上。其他相同
		//协议
		prop.setProperty("mail.transport.protocol", "smtp");
		//使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //端口
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.socketFactory.port", "465");
        
    	/*
    	 //腾讯企业邮箱使用代码
    	//协议
		prop.setProperty("mail.transport.protocol", "smtps");
		//服务器地址(邮件服务器)
        prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
        //端口
        prop.setProperty("mail.smtp.port", "25");
        //使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        
        //开启安全协议。使用SSL,企业邮箱必需!
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException ge) {
        	ge.printStackTrace();
        }
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);*/
        
        //创建一个邮件会话
        Session session = Session.getDefaultInstance(prop, new MyAuthenricator(this.account, this.pwd));
        //设置session的调试模式,可查看发送日志。发布时取消
        //session.setDebug(true);
        
        try {
			//创建一个邮件
	        MimeMessage message = new MimeMessage(session);
	        //From:发件人。 发件人、别名、字符集(后两个可选)
        	message.setFrom(new InternetAddress(fromMap.get("mail"),fromMap.get("name"), "UTF-8"));
        	
        	//To: 收件人
        	int addSize = toList.size();
        	Address[] addresss = new Address[addSize];
        	for(int i = 0; i < addSize; i++){
        		Map<String,String> toMap = toList.get(i);
        		addresss[i] = new InternetAddress(toMap.get("mail"), toMap.get("name"), "UTF-8");
        	}
        	message.setRecipients(MimeMessage.RecipientType.TO, addresss);
            	
        	//Cc: 抄送人(可选)
        	if(ccList != null && ccList.size() > 0){
        		int ccSize = ccList.size();
        		Address[] ccAddresss = new Address[ccSize];
        		for(int j = 0; j < ccSize; j++){
        			Map<String,String> ccMap = ccList.get(j);
        			ccAddresss[j] = new InternetAddress(ccMap.get("mail"), ccMap.get("name"), "UTF-8");
        		}
        		message.setRecipients(MimeMessage.RecipientType.CC, ccAddresss);
        	}
            	
        	//Bcc: 密送人(可选)
        	if(bccList != null && bccList.size() > 0){
        		int bccSize = bccList.size();
        		Address[] bccAddresss = new Address[bccSize];
        		for(int k = 0; k < bccSize; k++){
        			Map<String,String> bccMap = bccList.get(k);
        			bccAddresss[k] = new InternetAddress(bccMap.get("mail"), bccMap.get("name"), "UTF-8");
        		}
        		message.setRecipients(MimeMessage.RecipientType.BCC, bccAddresss);
        	}
            	
        	//发送日期
        	message.setSentDate(new Date());
            //邮件主题
            message.setSubject(title, "UTF-8");
             
            //根据不同情况。写入内容
            if("html".equalsIgnoreCase(contentType)){
            	message.setContent(content, "text/html;charset=UTF-8");
            }else if("annex".equalsIgnoreCase(contentType)){
            	//容器类,可以包含多个MimeBodyPart对象
 	            Multipart mp = new MimeMultipart();
 	            
 	            //MimeBodyPart可以包装文本,图片,附件
	            MimeBodyPart body = new MimeBodyPart();
	            //HTML正文
	            body.setContent(content, "text/html; charset=UTF-8");
	            mp.addBodyPart(body);
	            
	            //添加图片&附件
	            if(fileList != null && fileList.size() >0){
	            	int fileSize = fileList.size();
	            	for(int z = 0; z < fileSize; z++){
	            		body = new MimeBodyPart();
	            		FileDataSource fds = new FileDataSource(fileList.get(z));
	            		body.setDataHandler(new DataHandler(fds));
	            		body.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
	            		mp.addBodyPart(body);
	            	}
	            }
	            
	            //设置邮件内容
	            message.setContent(mp);
            }else{
            	message.setText(content);
            }
            
            //保存前面的设置
            message.saveChanges();
        	
        	//发送邮件
			Transport.send(message);
		} catch (MessagingException me) {
			me.printStackTrace();
        } catch (UnsupportedEncodingException ue) {
        	ue.printStackTrace();
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	
	/**
	 * 发送邮件				<br/>
	 * 参数无验证。传递请谨慎
	 * 
	 * @param session 邮件会话(必须)
	 * 
	 * @param fromMail 发件人邮箱。
	 * 
	 * @param toList 收件人邮箱集。
	 * 
	 * @param ccList 抄送人邮箱集。
	 * 
	 * @param title 邮件标题(必须)
	 * 
	 * @param txt 内容
	 * */
	public void SendSimpleMail(String fromMail,List<String> toList,List<String> ccList,String title,String txt){
		//创建参数配置, 用于连接邮件服务器的参数配置
		Properties prop = new Properties();
		//服务器
        prop.setProperty("mail.smtp.host", "smtp.viphrm.com");
		//协议
		prop.setProperty("mail.transport.protocol", "smtp");
		//使用smtp身份验证
        prop.setProperty("mail.smtp.auth", "true");
        //端口
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.socketFactory.port", "465");
          
      	/*
      	 //腾讯企业邮箱使用代码
      	//协议
  		prop.setProperty("mail.transport.protocol", "smtps");
  		//服务器地址(邮件服务器)
          prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
          //端口
          prop.setProperty("mail.smtp.port", "25");
          //使用smtp身份验证
          prop.setProperty("mail.smtp.auth", "true");
          
          //开启安全协议。使用SSL,企业邮箱必需!
          MailSSLSocketFactory sf = null;
          try {
              sf = new MailSSLSocketFactory();
              sf.setTrustAllHosts(true);
          } catch (GeneralSecurityException ge) {
          	ge.printStackTrace();
          }
          prop.put("mail.smtp.starttls.enable", "true");
          prop.put("mail.smtp.ssl.socketFactory", sf);*/
        
        //创建一个邮件会话
        Session session = Session.getDefaultInstance(prop, new MyAuthenricator(this.account, this.pwd));
        //设置session的调试模式,可查看发送日志。发布时取消
        //session.setDebug(true);
        
        try {
			//创建一个邮件
	        MimeMessage message = new MimeMessage(session);
	        //From:发件人。 发件人、别名、字符集(后两个可选)
        	message.setFrom(new InternetAddress(fromMail));
        	
        	//To: 收件人
        	int addSize = toList.size();
        	Address[] addresss = new Address[addSize];
        	for(int i = 0; i < addSize; i++){
        		addresss[i] = new InternetAddress(toList.get(i));
        	}
        	message.setRecipients(MimeMessage.RecipientType.TO, addresss);
        	
        	//Cc: 抄送人(可选)
        	if(ccList != null && ccList.size() > 0){
        		int ccSize = ccList.size();
        		Address[] ccAddresss = new Address[ccSize];
        		for(int j = 0; j < ccSize; j++){
        			ccAddresss[j] = new InternetAddress(ccList.get(j));
        		}
        		message.setRecipients(MimeMessage.RecipientType.CC, ccAddresss);
        	}
        	
        	//发送日期
        	message.setSentDate(new Date());
            //邮件主题
            message.setSubject(title);
            //写入内容
            message.setText(txt);
             
            //保存前面的设置
            message.saveChanges();
            
        	//发送邮件
			Transport.send(message);
		} catch (MessagingException me) {
			me.printStackTrace();
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	
	public static void main(String[] args) {
		SendMailUtil sendMail = SendMailUtil.getInstance("ms.payrollagency@viphrm.com", "Ms1234567");
		//测试发送多人邮件
		Map<String,String> fromMap = new HashMap<String,String>(); 
		fromMap.put("mail", "ms.payrollagency@viphrm.com");
		fromMap.put("name", "发件人别名");
		
		List<String> toList = new ArrayList<String>();
		toList.add("shangjc@microseer.com");
			
		List<String> ccList = new ArrayList<String>();
		ccList.add("shangjc@microseer.com");
		
		sendMail.SendSimpleMail("ms.payrollagency@viphrm.com", toList, ccList, "测试发送多人邮件(标题)", 
				"(内容)当你看到这段文字内容的时候。说明测试发送多人邮件已经成功完成。。。。。");
	}
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).