# -*- encoding : utf-8 -*- require 'savon' require 'log4r' require 'rchardet' module Esendex class Client include Log4r INBOX_SERVICE_WSDL = 'https://www.esendex.com/secure/messenger/soap/InboxService.asmx?wsdl' SEND_SERVICE_WSDL = 'https://www.esendex.com/secure/messenger/soap/SendService.asmx?wsdl' attr_accessor :username, :password, :account_reference attr_reader :sent_message_ids def initialize(*args) @username = args.shift @password = args.shift @account_reference = args.shift @sent_message_ids = [] Savon.configure do |config| config.raise_errors = true config.log = false config.log_level = :error HTTPI.log = false end @log = Logger.new "#{self.class.name}" @log.outputters = Outputter.stdout @log.level = ERROR @message_kind = String.new end def send_message(recipient, text) text = text.lstrip.rstrip @log.debug "TO:#{recipient} text size:#{text.size}" if CharDet.detect(text)['encoding'] == 'ascii' sms_parts = text.scan(/.{610}/mu) sms_parts << text[sms_parts.to_s.size..text.size] @message_kind = 'Text' @log.debug "#{@message_kind}:#{text.scan(/./mu)} = #{text.size}. #{sms_parts.size} part/s." sms(recipient, sms_parts) elsif CharDet.detect(text)['encoding'] == 'utf-8' sms_parts = text.scan(/.{70}/mu) sms_parts << text[sms_parts.to_s.size..text.size] @message_kind = 'Unicode' @log.debug "#{@message_kind}:#{text.scan(/./mu)} != #{text.size}. #{sms_parts.size} part/s." sms(recipient, sms_parts) else @log.debug "Unsupported encoding: #{CharDet.detect(text)['encoding']}" end end private def connect @client = Savon::Client.new(SEND_SERVICE_WSDL) #http://jira.codehaus.org/browse/JRUBY-5529 - jruby-openssl in --1.9 jruby mode @client.http.auth.ssl.verify_mode=(:none) end def sms(recipient, messages) @log.debug "#{@message_kind}:#{messages.size} parts." connect messages.each do |message| @log.debug "#{@message_kind}:#{message.size} bytes. Sending..." resp = @client.request :com, :send_message_full do |soap| soap.header["com:MessengerHeader"] = {"com:Username" => @username, "com:Password" => @password, "com:Account" => @account_reference} soap.body = {"com:recipient" => recipient, "com:body" => message, "com:type" => @message_kind} end @log.debug "Sent #{@message_kind}:#{recipient}:#{message.size} bytes" @sent_message_ids << resp.to_hash[:send_message_full_response][:send_message_full_result] end @log.debug "-=| #{messages.join(' + ')} |=-" @log.debug "-----" end end #module Client end #module Esendex #sms = Esendex::Client.new 'username', 'password', 'account_reference' #sms.send_message 'PHONENUMBER', 'message in any language'