Advertisement
Guest User

Untitled

a guest
Aug 6th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.95 KB | None | 0 0
  1. import httplib2
  2. import os, glob,time
  3. from PyPDF2 import PdfFileReader, PdfFileWriter
  4. import oauth2client
  5. from oauth2client import client, tools
  6. import base64
  7. from email.mime.multipart import MIMEMultipart
  8. from email.mime.text import MIMEText
  9. from apiclient import errors, discovery
  10. import mimetypes
  11. from email.mime.image import MIMEImage
  12. from email.mime.audio import MIMEAudio
  13. from email.mime.base import MIMEBase
  14. from email import encoders
  15.  
  16. def pdf_splitter(path):
  17.     fname = os.path.splitext(os.path.basename(path))[0]
  18.  
  19.     pdf = PdfFileReader(path)
  20.     for page in range(pdf.getNumPages()):
  21.         pdf_writer = PdfFileWriter()
  22.         pdf_writer.addPage(pdf.getPage(page))
  23.  
  24.         output_filename = 'temp_{}_page_{}.pdf'.format(
  25.             fname, page+1)
  26.  
  27.         with open(output_filename, 'wb') as out:
  28.             pdf_writer.write(out)
  29.  
  30.         print('Created: {}'.format(output_filename))
  31.  
  32. def pdf_temp_del():
  33.     for filename in glob.glob("./temp*"):
  34.         os.remove(filename)
  35.  
  36.  
  37. SCOPES = 'https://www.googleapis.com/auth/gmail.send'
  38. CLIENT_SECRET_FILE = 'client_secret.json'
  39.  
  40.  
  41. def get_credentials():
  42.     home_dir = os.path.expanduser('~')
  43.     credential_dir = os.path.join(home_dir, '.credentials')
  44.     if not os.path.exists(credential_dir):
  45.         os.makedirs(credential_dir)
  46.     credential_path = os.path.join(credential_dir,
  47.                                    'gmail-python-email-send.json')
  48.     store = oauth2client.file.Storage(credential_path)
  49.     credentials = store.get()
  50.     if not credentials or credentials.invalid:
  51.         flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  52.         flow.user_agent = APPLICATION_NAME
  53.         credentials = tools.run_flow(flow, store)
  54.         print('Storing credentials to ' + credential_path)
  55.     return credentials
  56.  
  57. def SendMessageInternal(service, user_id, message):
  58.     try:
  59.         message = (service.users().messages().send(userId=user_id, body=message).execute())
  60.         print('Message Id: %s' % message['id'])
  61.         return message
  62.     except errors.HttpError as error:
  63.         print('An error occurred: %s' % error)
  64.         return "Error"
  65.     return "OK"
  66.  
  67. def SendMessage(sender, to, subject, attachmentFile=None):
  68.     credentials = get_credentials()
  69.     http = credentials.authorize(httplib2.Http())
  70.     service = discovery.build('gmail', 'v1', http=http)
  71.     if attachmentFile:
  72.         message1 = createMessageWithAttachment(sender, to, subject, attachmentFile)
  73.     result = SendMessageInternal(service, "me", message1)
  74.     return result
  75.  
  76. def createMessageWithAttachment(
  77.     sender, to, subject, attachmentFile):
  78.    
  79.     message = MIMEMultipart('mixed')
  80.     messageA = MIMEMultipart('alternative')
  81.     message.attach(messageA)
  82.  
  83.     print("create_message_with_attachment: file: %s" % attachmentFile)
  84.     content_type, encoding = mimetypes.guess_type(attachmentFile)
  85.  
  86.     if content_type is None or encoding is not None:
  87.         content_type = 'application/octet-stream'
  88.     main_type, sub_type = content_type.split('/', 1)
  89.     fp = open(attachmentFile, 'rb')
  90.     msg = MIMEBase(main_type, sub_type)
  91.     msg.set_payload(fp.read())
  92.     fp.close()
  93.     encoders.encode_base64(msg)
  94.    
  95.     filename = os.path.basename(attachmentFile)
  96.     msg.add_header('Content-Disposition', 'attachment', filename=filename)
  97.     msg.add_header('To', to)
  98.     msg.add_header('Subject', subject)
  99.     message.attach(msg)
  100.     raw = base64.urlsafe_b64encode(msg.as_bytes())
  101.     raw = raw.decode()
  102.     return {'raw': raw}
  103.  
  104. def main():
  105.     sender = 'toby.lat12@gmail.com'
  106.     subject = 'January Invoice'
  107.     emaillist = ['toby.lat12@gmail.com','theminecraftmastermind686@gmail.com']
  108.     for item in emaillist:
  109.         to = item
  110.         attachpath = 'temp_multi_page_{}.pdf'.format(emaillist.index(item)+1)
  111.         SendMessage(sender, to, subject, attachpath)
  112.  
  113. if __name__ == '__main__':
  114.     pdf_splitter('multi.pdf')
  115.     main()
  116.     time.sleep(15)
  117.     pdf_temp_del()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement