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

来源:互联网 发布:linux下载迅雷资源 编辑:程序博客网 时间:2024/04/27 22:29
//文件读取类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
原创粉丝点击