Sunday 19 November 2017

python code to send SMS data in excel automatically through way2sms

The below code is modification of code found at URL
https://github.com/PratikBodawala/way2sms

 Requirements:
 requests==2.12.4
beautifulsoup4==4.5.3
python 2.7.13

You can also download the code from
https://drive.google.com/file/d/1b-gySD2S5tlyhuwX0LnkyfzEFNMsD_9J/view?usp=sharing

Usage:
Create excel file with msgs in A1,A2,A3 ...cells 
and corresponding phone number in B1,B2,B3 ...cells as shown in below figure



Output:

Once u run the python code
you will be asked to
Enter the way2sms account username i.e, mobile number
Enter the way2sms password
Enter the path where the excel file is
here i have saved the excel file at C:\Users\SARVANI\Desktop\SEC8.xlsx
The excel file name is SEC8.xlsx




===============================================
import getpass
import urllib
import textwrap
import requests
import time
import os
import datetime
from bs4 import BeautifulSoup
import cPickle as pickle
import sys
import openpyxl
sys.stdout.flush()
url = 'http://www.way2sms.com'

class Way2sms(object):
    """mobile and string are keywords parameter of sms method."""
    def __init__(self):
        if os.path.exists('.token'):
            with open('.token', 'r') as Token:
                self.ses, self.token, self.new_url = pickle.load(Token)
            page = self.ses.get(self.new_url+'ebrdg?id='+self.token).text
            if 'Welcome to Way2SMS' in page:
                print 'session is ok'

            else:
                print 'session expired'
                response = requests.head(url, allow_redirects=True)
                self.new_url = response.url
                self.ses = requests.session()
                self.ses.headers.update({'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'DNT': '1', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.8'})
                usr = str(raw_input('Enter your mobile number:'))
                pas = getpass.getpass()
                if self.ses.post(self.new_url + 'Login1.action', 'username=' + str(usr) + '&password=' + str(pas)).ok:
                    print "Login successfully"
                    self.token = self.ses.cookies['JSESSIONID']
                    self.token = self.token[4:]
                    with open('.token', 'w') as Token:
                        pickle.dump((self.ses, self.token, self.new_url), Token)
                else:
                    print "Login failed"

        else:
            response = requests.head(url, allow_redirects=True)
            self.new_url = response.url
            self.ses = requests.session()
            self.ses.headers.update({'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache',
                                     'Upgrade-Insecure-Requests': '1',
                                     'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
                                     'Content-Type': 'application/x-www-form-urlencoded',
                                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                                     'DNT': '1', 'Accept-Encoding': 'gzip, deflate',
                                     'Accept-Language': 'en-US,en;q=0.8'})
            usr = str(raw_input('Enter your mobile number:'))
            pas = getpass.getpass()
            if self.ses.post(self.new_url + 'Login1.action', 'username=' + str(usr) + '&password=' + str(pas)).ok:
                print "Login successfully"
                self.token = self.ses.cookies['JSESSIONID']
                self.token = self.token[4:]
                with open('.token', 'w') as Token:
                    pickle.dump((self.ses, self.token, self.new_url), Token)
            else:
                print "Login failed"
    def successfully_sent(self, mobile, text):
        date = datetime.date.today().strftime('%d/%m/%Y')
        page = self.ses.post(self.new_url + 'sentSMS.action?dt=' + str(date) + '&Token=' + str(self.token))
        soup = BeautifulSoup(page.text, 'html.parser')
        first = soup.find('div', {'class': 'mess'})
        no = str(first.find('b').text)
        divrb = first.find('div', {'class': 'rb'})
        p = str(divrb.find('p').text)
        if (no == mobile) and (p == text):
            return True
        else:
            return False

    def sms(self):
        filename=str(raw_input('enter path to excel file: '))
        wb = openpyxl.load_workbook(filename)
        ws = wb.get_sheet_by_name('Sheet1')
        #print sheet['B1'].value
        rowcount=ws.max_row
        print rowcount
        for i in range(rowcount):
            mobile = str(ws.cell(row=i+1,column=2).value)
            string = str(ws.cell(row=i+1,column=1).value)       
            if type(mobile) is str:
                mobile = list(str(mobile).split(','))
            if type(mobile) is list:
                for mobile_no in mobile:
                    if len(mobile_no) is not 10:
                        print mobile_no, 'is not valid'
                    else:
                        lofstr = textwrap.wrap(string, 140)
                        for string in lofstr:
                            msglen = len(string)
                            qstring = urllib.quote(string)
                            page = self.ses.post(self.new_url+'smstoss.action', 'ssaction=ss&Token='+str(self.token)+'&mobile='+str(mobile_no)+'&message='+qstring+'&msgLen='+str(140-msglen)).text
                            print 'Sending SMS to', mobile_no,
                            for dot in range(3):
                                print '.',
                                time.sleep(1)
                            if "Rejected : Can't submit your message, finished your day quota." not in page:
                                if self.successfully_sent(mobile_no, string):
                                    print 'sent successfully.'
                                else:
                                    print 'failed to send.'
                            else:
                                print 'quota finished!'
                                sys.exit(1)
    def logout(self):
        self.ses.get(self.new_url+'main.action')
        try:
            os.remove('.token')
        finally:
            print 'Log-out!'
            sys.exit(0)       
if __name__ == '__main__':
   
        Way2sms().sms()
        Way2sms().logout()
================================


2 comments:

  1. Thanks a lot for sharing this tutorial. I am so glad to have a look at these details. The SMS marketing is popular across the world because it is easy and this is why you can find a lot of apps and services to send bulk SMS at very low price. I also got the real estate text marketing app and enjoying really good results with that.

    ReplyDelete
  2. Bro please write this code for pyhton 3.*. I dont have python 2.* and my whole work require python 3

    ReplyDelete