• EBS中使用JAVA方式发送HTML格式邮件


    转自huan.gu专栏:http://blog.csdn.net/gh320/article/details/17174769

    EBS中使用JAVA方式发送HTML格式邮件

    一、开发工具:JDeveloper
    需要添加的Library:activation.jar和javax.mail.jar(自行下载)

    二、注意事项:

    1、设置项目的编码格式为UTF-8
    2、使用Rebuiled或者run生成.class文件
    3、将.class文件上传到服务器中的$JAVA_TOP目录相应的文件夹下

    三、开发思想:
    1、发送HTML的公共主程序可以参考java的发送html邮件的程序;
    2、在邮件中显示出html的样式效果是根据EBS中HTML报表的代码样式转换而来

    四、实现程序:
    1、主程序SendHtmlMail.java中的host、user、pwd、from这里是写死了,可以提取出来当参数传入更具有通用型
    package cux.oracle.apps.pos.Util;
    
    import java.io.FileOutputStream;
    import java.io.UnsupportedEncodingException;
    
    import java.sql.PreparedStatement;
    
    import java.sql.ResultSet;
    
    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    import oracle.apps.fnd.cp.request.JavaConcurrentProgram;
    
    /**
    * 创建 HTML 格式的邮件
    *
    * @author Jason Gu
    */
    public class SendHtmlMail
    {
    
      public String sendMessage(String host, String user, String pwd, String from,
                                String to, String subject,
                                String body) throws MessagingException,
                                                    java.io.UnsupportedEncodingException
      {
        Properties props = new Properties();
    
        // 设置发送邮件的邮件服务器的属性
        props.put("mail.smtp.host", host);
    
        // 需要经过授权,也就是用户名和密码的校验,这样才能通过验证(一定要有这一条)
        props.put("mail.smtp.auth", "true");
    
        // 创建该邮件应用程序所需的环境信息以及会话信息
        Session session = Session.getDefaultInstance(props);
    
        // 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
        // 用(你可以在控制台(console)上看到发送邮件的过程)
        session.setDebug(true);
    
        // 根据上面的 Session 实例创建 MimeMessage 实例,即一封邮件
        MimeMessage msg = new MimeMessage(session);
    
        try
        {
          // 设置发件人地址
          msg.setFrom(new InternetAddress(from));
    
          // 设置收件人地址
          msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    
          // 设置 E-mail 主题
          msg.setSubject(subject);
    
          // 设置发送时间
          msg.setSentDate(new Date());
    
          // 设置 E-mail 正文部分
          // msg.setText(body);
          msg.setContent(body, "text/html;charset = UTF-8");
    
          // 保存对该 MimeMessage 实例的更改
          msg.saveChanges();
    
          // 发送邮件
          Transport transport = session.getTransport("smtp");
    
          // 连接服务器的邮箱
          transport.connect(host, user, pwd);
    
          // 把邮件发送出去
          transport.sendMessage(msg, msg.getAllRecipients());
          transport.close();
          // 将 msg 对象中内容写入文件
          msg.writeTo(new FileOutputStream("SendHtmlMail.eml"));
          return "S";
        } catch (Exception e)
        {
          e.printStackTrace();
          return "E";
        }
      }
    
      public static String main(String to,String subject,String body) throws MessagingException,
                                                  UnsupportedEncodingException
      {
        String host = "172.17.27.249"; // smtp服务器
        String user = "Ebs-admin"; // 用户名
        String pwd = "[CONTRACT]2013(approval)"; // 密码
        String from = "Ebs-admin@jd.com";
    
        SendHtmlMail sendmail = new SendHtmlMail();
        String result =
          sendmail.sendMessage(host, user, pwd, from, to, subject, body);
        return result;
      }
    }
    2、邮件内容和收件人的程序CuxPtebsReport.java
    package cux.oracle.apps.pos.Util;
    
    import java.sql.PreparedStatement;
    
    import java.util.Date;
    
    import java.text.SimpleDateFormat;
    
    import oracle.apps.fnd.common.VersionInfo;
    import oracle.apps.fnd.cp.request.CpContext;
    import oracle.apps.fnd.cp.request.JavaConcurrentProgram;
    import oracle.apps.fnd.cp.request.LogFile;
    import oracle.apps.fnd.cp.request.ReqCompletion;
    import oracle.apps.fnd.framework.OAException;
    import oracle.apps.fnd.util.ParameterList;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    
    import oracle.apps.fnd.util.NameValueType;
    
    import cux.oracle.apps.pos.Util.SendHtmlMail;
    
    /**
    *  请求调用生成 HTML 格式的邮件
    *
    * @author Jason Gu
    */
    public class CuxPtebsReport implements JavaConcurrentProgram
    {
      public static final String RCS_ID =
        "$Header: CuxRepayReport.java 120.1 2013/09/06 14:36:06 sabatra noship $";
      public static final boolean RCS_ID_RECORDED =
        VersionInfo.recordClassVersion("$Header: CuxRepayReport.java 120.1 2013/09/06 14:36:06 sabatra noship $",
                                       "%packagename%");
      protected LogFile log;
      protected ReqCompletion reqc;
      private static SimpleDateFormat mDateFormat;
      private String l_return_status = "S";
    
      public void runProgram(CpContext cpContext)
      {
        ParameterList lPara = cpContext.getParameterList();
        StringBuffer com_content = new StringBuffer();
        StringBuffer dept_content = new StringBuffer();
        String sendresult = "S";
        String cux_combody = new String();
        String cux_deptbody = new String();
        String body = new String();
        try
        {
          this.log = cpContext.getLogFile();
          this.reqc = cpContext.getReqCompletion();
    
          Connection con = cpContext.getJDBCConnection();
    
          this.log.writeln("input parameters list:", 1);
          while (lPara.hasMoreElements())
          {
            NameValueType nvt = lPara.nextParameter();
            this.log.writeln(nvt.getName() + ":" + nvt.getValue(), 1);
    
          }
          //获取当前日期
          java.util.Calendar c = java.util.Calendar.getInstance();
          java.text.SimpleDateFormat f =
            new java.text.SimpleDateFormat("yyyy年MM月dd日");
          //邮件主题
          String subject = f.format(c.getTime()) + "新增公司和部门";
          //表格标题
          String com = f.format(c.getTime()) + "数据新增公司";
          String dept = f.format(c.getTime()) + "数据新增部门";
          String comheader =
            "<table border=1 cellspacing=0 cellpadding=2><tr><td colspan=4 align=center>" +
            com +
            "</td></tr><tr><td nowrap>公司编码</td><td nowrap>公司名称</td><td nowrap>生效日期</td><td>最后更新日期</td></tr>";
          String combody =
            "<tr align=left><td nowrap>VAR_A</td><td nowrap>VAR_B</td><td nowrap>VAR_C</td><td nowrap>VAR_D</td></tr>";
          String deptheader =
            "<table border=1 cellspacing=0 cellpadding=2><tr><td colspan=4 align=center>" +
            dept +
            "</td></tr><tr><td nowrap>部门编码</td><td nowrap>部门名称</td><td nowrap>生效日期</td><td>最后更新日期</td></tr>";
          String deptbody =
            "<tr align=left><td nowrap>VAR_E</td><td nowrap>VAR_F</td><td nowrap>VAR_G</td><td nowrap>VAR_H</td></tr>";
          String foot = "</table><br><br>";
    
          PreparedStatement compre = null;
          PreparedStatement deptpre = null;
          PreparedStatement updatecompre = null;
          PreparedStatement updatedeptpre = null;
          PreparedStatement mailtopre = null;
          ResultSet comresult = null;
          ResultSet deptresult = null;
          ResultSet mailtoresult = null;
          ResultSet updatecomresult = null;
          ResultSet updatedeptresult = null;
          this.log.writeln("start datebase connection...", 1);
    
          //新增公司数据
          String comsql =
            "SELECT company_code, company_name, to_char(start_date, 'yyyy-mm-dd') start_date, to_char(last_update_date,'yyyy-mm-dd') last_update_date 
    " +
            "FROM cux_test_com_data WHERE send_flag = 'N' 
    ";
    
          compre = con.prepareStatement(comsql);
          comresult = compre.executeQuery();
          while (comresult.next())
          {
            this.log.writeln("com_code:" + comresult.getString("company_code"), 1);
            cux_combody = combody;
            cux_combody =
                cux_combody.replace("VAR_A", comresult.getString("company_code"));
            cux_combody =
                cux_combody.replace("VAR_B", comresult.getString("company_name"));
            String com_start_date = comresult.getString("start_date");
            if (com_start_date == null)
            {
              com_start_date = " ";
            }
            String date = com_start_date;
            cux_combody = cux_combody.replace("VAR_C", date);
            cux_combody =
                cux_combody.replace("VAR_D", comresult.getString("last_update_date"));
            com_content.append(cux_combody);
          }
    
          //部门新增数据
          String deptsql =
            "SELECT dept_code, dept_name, to_char(start_date,'yyyy-mm-dd') start_date,to_char(last_update_date,'yyyy-mm-dd') last_update_date 
    " +
            "  FROM cux_test_dept_data where send_flag = 'N'";
          deptpre = con.prepareStatement(deptsql);
          deptresult = deptpre.executeQuery();
          //deptresult.
          while (deptresult.next())
          {
            cux_deptbody = deptbody;
            cux_deptbody =
                cux_deptbody.replace("VAR_E", deptresult.getString("dept_code"));
            cux_deptbody =
                cux_deptbody.replace("VAR_F", deptresult.getString("dept_name"));
            String dept_start_date = deptresult.getString("start_date");
            if (dept_start_date == null)
            {
              dept_start_date = " ";
            }
            String start_date = dept_start_date;
            cux_deptbody = cux_deptbody.replace("VAR_G", start_date);
            cux_deptbody =
                cux_deptbody.replace("VAR_H", deptresult.getString("last_update_date"));
            dept_content.append(cux_deptbody);
          }
    
          int resp_id = cpContext.getRespId();
          this.log.writeln("resp_id:" + resp_id, 2);
          //获取职责id
          String addrsql =
            "SELECT distinct pf.email_address
    " + "        FROM fnd_user_resp_groups_direct c, fnd_responsibility r, fnd_user fu, per_all_people_f pf
    " +
            "       WHERE c.responsibility_id = r.responsibility_id
    " +
            "         AND c.user_id = fu.user_id
    " +
            "         AND pf.email_address is not null
    " +
            "         AND fu.employee_id = pf.person_id
    " +
            "         AND c.responsibility_id = " + resp_id;
          //this.log.writeln("addrsql:" + addrsql, 2);
          mailtopre = con.prepareStatement(addrsql);
          mailtoresult = mailtopre.executeQuery();
          while (mailtoresult.next())
          {
            String addr = mailtoresult.getString("email_address");
            this.log.writeln("addr:" + addr, 1);
            if (addr != null && addr != "")
            {
              if (!"".equals(com_content.toString()) ||
                  !"".equals(dept_content.toString()))
              {
                this.log.writeln("com not null or dept not null in", 4);
                //收件人
                //to = "jisuqing@jd.com";
                //String to = "cwzhaorui@jd.com";
                //邮件内容
                if (com_content.toString().equals("") &&
                    !"".equals(dept_content.toString()))
                {
                  this.log.writeln("com null,dept not null", 4);
                  body = deptheader + dept_content.toString() + foot;
                } else if (!"".equals(com_content.toString()) &&
                           dept_content.toString().equals(""))
                {
                  this.log.writeln("com not null,dept null", 4);
                  body = comheader + com_content.toString() + foot;
                } else if (!"".equals(com_content.toString()) &&
                           !"".equals(dept_content.toString()))
                {
                  this.log.writeln("com not null,dept not null", 4);
                  body =
                      comheader + com_content.toString() + foot + deptheader + dept_content.toString() +
                      foot;
                }
                //发送邮件
                SendHtmlMail sendmail = new SendHtmlMail();
                sendresult = sendmail.main(addr, subject, body);
              } else
              {
                this.log.writeln("没有需要发送的内容", 4);
              }
            } else
            {
              write("resp_id:" + resp_id + "未维护邮箱");
            }
          }
    
          if (!"S".equals(sendresult))
          {
            this.l_return_status = "E";
          }
    
          if ("S".equals(this.l_return_status))
          {
            this.reqc.setCompletion(0, "program completed Successfully.");
            String update_com_sql =
              "UPDATE cux_test_com_data c
    " + "   SET c.send_flag = 'Y', c.last_update_date = SYSDATE, c.last_updated_by = fnd_global.user_id
    " +
              " WHERE c.send_flag = 'N'";
            updatecompre = con.prepareStatement(update_com_sql);
            updatecomresult = updatecompre.executeQuery();
            String update_dept_sql =
              "UPDATE cux_test_dept_data d
    " + "   SET d.send_flag = 'Y', d.last_update_date = SYSDATE, d.last_updated_by = fnd_global.user_id
    " +
              " WHERE d.send_flag = 'N'";
            updatedeptpre = con.prepareStatement(update_dept_sql);
            updatedeptresult = updatedeptpre.executeQuery();
          } else
          {
            this.reqc.setCompletion(2,
                                    "program completed with error. Please see request log for details.");
          }
        }
    
        catch (OAException localOAException)
        {
          localOAException.printStackTrace();
          this.reqc.setCompletion(2, localOAException.getMessage());
        } catch (Exception localException)
        {
          localException.printStackTrace();
          this.reqc.setCompletion(2, localException.toString());
        }
      }
    
      protected void write(String paramString)
      {
        this.log.writeln(getCurrDateStr() + paramString, 0);
      }
    
      private String getCurrDateStr()
      {
        if (mDateFormat == null)
        {
          mDateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
        }
    
        return "[" + mDateFormat.format(new Date()) + "] ";
      }
    }
    五、配置
    1、将生成的.class文件上传至:$JAVA_TOP/cux/oracle/apps/pos/Util

    2、定义并发程序
    1.定义可执行:
    Execution Method:Java Concurrent Program
    Execution File Nam:CuxPtebsReport
    Execution File Path:cux.oracle.apps.pos.Util
    2.定义并发程序
  • 相关阅读:
    GTK+中的树状列表构件(GtkTreeView)
    [TOP]疯狂的投资
    多线程模式之MasterWorker模式
    一年读书总结
    Microsoft Visual Studio正忙解决办法
    使用vs自带的性能诊断工具
    C#中的扩展方法
    从委托、匿名方法到Lambda
    c#中的事件
    sqlserver中创建包含事务的存储过程
  • 原文地址:https://www.cnblogs.com/wanghang/p/6299482.html
Copyright © 2020-2023  润新知