服务器通过模板发送邮件java代码

//文件读取类
public class TemplateFileRead {
	private String content= null;
	public TemplateFileRead() {
	}
	
	public TemplateFileRead(String  content) {
		this.content=content;
	}

	
	public void  readTemplateFile(String path) {
		StringBuffer buffer = null;
		try {
			File file = new File(path);
			InputStream inputStream = new FileInputStream(file);
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			buffer = new StringBuffer();
			String line = "";
			while (null!=(line=reader.readLine()))
				buffer.append(line);
			reader.close();
			this.content=buffer.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	

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


//部分业务代码
String path = request.getSession().getServletContext().getRealPath(dcConfig.getChangePwdVcodeTempPath());	//获取邮件模板路径
			TemplateFileRead temp = new TemplateFileRead();
			temp.readTemplateFile(path);
			
			String content = temp.getContent();
			content = content.replace("#vCode", vCode);
			content = content.replace("#web_admin_email", p2pContact.getPubEmail());//
			content = content.replace("#web_svr_email", p2pContact.getEmail());//
			content = content.replace("#web_svr_tel", p2pContact.getTel());//
			content = content.replace("#web_com_sign", p2pContact.getCenterBuilder());//
			
			//发送邮件执行
			MailServices services = MailServices.getInstance();
			services.sendMailOfTemplet(email,"密码修改时的验证码邮件,请勿回复!", content);

/**
 * Desc:发送邮件
 * 
 * @author **
 * @date 2014-7-25 下午03:17:01
 */
public class MailServices {

	private static MailServices instance;

	private static final Log log = LogFactory.getLog(MailServices.class);
	private static String smtpServer ="mail.ccxe.com.cn";		//接收邮件服务器(POP3)、发送邮件服务器(SMTP)
	private static String senderAddress = "***@***.com.cn";	//发送者帐号
	private static String senderPassword = "****";			//发送者密码
	
	public synchronized  static MailServices getInstance(){
		//if(null==instance)    //必须屏蔽,以保证gxgxContact获取的是最新信息 
			instance=new MailServices();
		return instance;
	}
	
	/**
	 * Desc:使用模板发送邮件
	 * 
	 * @author **
	 * @date 2014-7-24 下午04:57:03
	 * @param address
	 * @param title
	 * @param content
	 */
	public void sendMailOfTemplet(String address, String title,String content){
		sendMail(address, title, content);
	}
	
	/**
	 * Desc:发送邮件
	 * 
	 * @author **
	 * @date 2014-7-24 下午04:57:52
	 * @param address
	 * @param title
	 * @param content
	 */
	private void sendMail(String address, String title, String content) {
		//判断是否需要身份认证
	    MyAuthenticator authenticator = new MyAuthenticator(senderAddress,senderPassword);
	    Properties properties = new Properties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.host", smtpServer);
	    // 根据邮件会话属性和密码验证器构造一个发送邮件的session    
	    Session sendMailSession = Session.getDefaultInstance(properties,authenticator);    
	    try {    
		    // 根据session创建一个邮件消息    
		    Message mailMessage = new MimeMessage(sendMailSession);    
		    // 创建邮件发送者地址    
		    Address from = new InternetAddress(senderAddress);    
		    // 设置邮件消息的发送者    
		    mailMessage.setFrom(from);    
		    // 创建邮件的接收者地址,并设置到邮件消息中    
		    Address to = new InternetAddress(address);    
		    // Message.RecipientType.TO属性表示接收者的类型为TO    
		    mailMessage.setRecipient(Message.RecipientType.TO,to);    
		    // 设置邮件消息的主题    
		    mailMessage.setSubject(title);    
		    // 设置邮件消息发送的时间    
		    mailMessage.setSentDate(new Date());    
		    // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象    
		    Multipart mainPart = new MimeMultipart();    
		    // 创建一个包含HTML内容的MimeBodyPart    
		    BodyPart html = new MimeBodyPart();    
		    // 设置HTML内容    
		    html.setContent(content, "text/html;charset=utf-8");    
		    mainPart.addBodyPart(html);    
		    // 将MiniMultipart对象设置为邮件内容    
		    mailMessage.setContent(mainPart);    
		    // 发送邮件    
		    Transport.send(mailMessage);    
	    } catch (MessagingException ex) {    
	    	ex.printStackTrace();    
	    } catch (Exception ex) {    
	    	ex.printStackTrace();    
	    } 
	}
	
	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);   
	    }   
	}   

	/**
	 * Desc:测试邮件发送
	 * 注:Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
	 * 	  需用rar打开D:\Program Files\MyEclipse 6.6\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_6.6.0.zmyeclipse660200810\data\libraryset\EE_5/javaee.jar,删除其中的mail包导入mail.jar
	 * @author **
	 * @date 2014-7-25 下午03:18:10
	 * @param args
	 */
	public static void main(String[] args) {
		MailServices mail = MailServices.getInstance() ;
		
		StringBuffer sb = new StringBuffer();
		sb.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
		sb.append("<html><head>");
		sb.append("<script type='text/javascript'>");
		sb.append("");
		sb.append("</script>");
		sb.append("</head><body></body></html>");
		
		mail.sendMail("*********@****.com.cn","测试", "---------测试----------") ; 
	}
	
	/*public void senderGorupEmail(String address , String title ,Template template ,Expression expressions , List<String> replacesList) {
		try{	
			this.template = template ;
			this.expression = expressions ;
			TemplateContentReplace replace = new TemplateContentReplace(template , expressions) ;
			replace.setContentAll(replacesList) ;
			this.sendMailOfTemplet(address, title, template) ;
		}catch(Exception e) {
			e.printStackTrace() ;
		}
	}*/
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值