postgresql 使用 plpythonu 发送邮件及短信

闲来无事,自己写了个 postgresql 小监控程序,使用 plpythonu 实现了发送邮件和短信.现把发送邮件和短信的函数记录一下,以防忘记.

邮件服务的配置参考<>

CREATE EXTENSION IF NOT EXISTS plpythonu ;
CREATE EXTENSION IF NOT EXISTS plpython2u ;

--
-- Name: sp_util_exception_sendmail(text, text, text, text); Type: FUNCTION; Schema: public; Owner: postgres
--

CREATE FUNCTION public.sp_util_exception_sendmail(pi_receiver text, pi_subject text, pi_text text, pi_attach text) RETURNS text
    LANGUAGE plpythonu
    AS $$
  import commands
    
  if pi_attach == '': 
    cmds = 'echo "' + pi_text + '" | /bin/mailx  -s "' + pi_subject + '" '+ pi_receiver  
  else:
    cmds = 'echo "' + pi_text + '" | /bin/mailx  -s "' + pi_subject + '" '+ ' -a "'+ pi_attach + '" ' + pi_receiver 
	  
  (status, output) = commands.getstatusoutput(cmds)
	
  return status

$$;


ALTER FUNCTION public.sp_util_exception_sendmail(pi_receiver text, pi_subject text, pi_text text, pi_attach text) OWNER TO postgres;

--
-- Name: sp_util_exception_sendsms(text, text, text); Type: FUNCTION; Schema: public; Owner: postgres
--

CREATE FUNCTION public.sp_util_exception_sendsms(pi_receiver text, pi_text text, pi_source text) RETURNS text
    LANGUAGE plpython2u
    AS $$
  import commands
  import socket
  
  from urllib import request, parse,error
 
  response = urllib.request.urlopen('http://192.168.56.100:8888/MsgService/sms/?phone='+ pi_receiver+'&text='+ pi_text, timeout=0.5)
  return type(response)

$$;


ALTER FUNCTION public.sp_util_exception_sendsms(pi_receiver text, pi_text text, pi_source text) OWNER TO postgres;

你可能感兴趣的:(#,postgresql,sql,plpgsql)