EBS中使用JAVA方式發送HTML格式郵件

轉自huan.gu專欄:http://blog.csdn.net/gh320/article/details/17174769html

EBS中使用JAVA方式發送HTML格式郵件java

1、開發工具:JDeveloper
須要添加的Library:activation.jar和javax.mail.jar(自行下載)

2、注意事項:sql

一、設置項目的編碼格式爲UTF-8
二、使用Rebuiled或者run生成.class文件
三、將.class文件上傳到服務器中的$JAVA_TOP目錄相應的文件夾下

3、開發思想:
一、發送HTML的公共主程序能夠參考java的發送html郵件的程序;
二、在郵件中顯示出html的樣式效果是根據EBS中HTML報表的代碼樣式轉換而來

4、實現程序:
一、主程序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;
  }
}
二、郵件內容和收件人的程序 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 \n" +
        "FROM cux_test_com_data WHERE send_flag = 'N' \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 \n" +
        "  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\n" + "        FROM fnd_user_resp_groups_direct c, fnd_responsibility r, fnd_user fu, per_all_people_f pf\n" +
        "       WHERE c.responsibility_id = r.responsibility_id\n" +
        "         AND c.user_id = fu.user_id\n" +
        "         AND pf.email_address is not null\n" +
        "         AND fu.employee_id = pf.person_id\n" +
        "         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\n" + "   SET c.send_flag = 'Y', c.last_update_date = SYSDATE, c.last_updated_by = fnd_global.user_id\n" +
          " WHERE c.send_flag = 'N'";
        updatecompre = con.prepareStatement(update_com_sql);
        updatecomresult = updatecompre.executeQuery();
        String update_dept_sql =
          "UPDATE cux_test_dept_data d\n" + "   SET d.send_flag = 'Y', d.last_update_date = SYSDATE, d.last_updated_by = fnd_global.user_id\n" +
          " 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()) + "] ";
  }
}
5、配置
一、將生成的.class文件上傳至:$JAVA_TOP/cux/oracle/apps/pos/Util

二、定義併發程序
1.定義可執行:
Execution Method:Java Concurrent Program
Execution File Nam:CuxPtebsReport
Execution File Path:cux.oracle.apps.pos.Util
2.定義併發程序
相關文章
相關標籤/搜索