Advertisement
hpodf

Untitled

Oct 5th, 2017
984
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.47 KB | None | 0 0
  1. import httplib2
  2.  
  3. from email.encoders import encode_base64
  4. from apiclient import discovery
  5. from oauth2client import client
  6. from oauth2client import tools
  7. from oauth2client.file import Storage
  8. import base64
  9. from email.mime.audio import MIMEAudio
  10. from email.mime.base import MIMEBase
  11. from email.mime.image import MIMEImage
  12. from email.mime.multipart import MIMEMultipart
  13. from email.mime.text import MIMEText
  14. import mimetypes
  15. import os
  16.  
  17. from apiclient import errors
  18.  
  19.  
  20. try:
  21.     import argparse
  22.     flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  23. except ImportError:
  24.     flags = None
  25.  
  26. # If modifying these scopes, delete your previously saved credentials
  27. # at ~/.credentials/gmail-python-quickstart.json
  28. SCOPES = 'https://mail.google.com/'
  29. CLIENT_SECRET_FILE = 'client_id.json'
  30. APPLICATION_NAME = 'Gmail API Python Quickstart'
  31.  
  32.  
  33. def get_credentials():
  34.     """Gets valid user credentials from storage.
  35.  
  36.    If nothing has been stored, or if the stored credentials are invalid,
  37.    the OAuth2 flow is completed to obtain the new credentials.
  38.  
  39.    Returns:
  40.        Credentials, the obtained credential.
  41.    """
  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-quickstart.json')
  48.  
  49.     store = Storage(credential_path)
  50.     credentials = store.get()
  51.     if not credentials or credentials.invalid:
  52.         flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  53.         flow.user_agent = APPLICATION_NAME
  54.         if flags:
  55.             credentials = tools.run_flow(flow, store, flags)
  56.         else: # Needed only for compatibility with Python 2.6
  57.             credentials = tools.run(flow, store)
  58.         print('Storing credentials to ' + credential_path)
  59.     return credentials
  60.  
  61.  
  62. def CreateMessage(sender, to, subject, message_text):
  63.   """Create a message for an email.
  64.  
  65.  Args:
  66.    sender: Email address of the sender.
  67.    to: Email address of the receiver.
  68.    subject: The subject of the email message.
  69.    message_text: The text of the email message.
  70.  
  71.  Returns:
  72.    An object containing a base64url encoded email object.
  73.  """
  74.   message = MIMEText(message_text)
  75.   message['to'] = to
  76.   message['from'] = sender
  77.   message['subject'] = subject
  78.   return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}
  79.  
  80.  
  81. def create_message_with_attachment(
  82.     sender, to, subject, message_text, file):
  83.   """Create a message for an email.
  84.  
  85.  Args:
  86.    sender: Email address of the sender.
  87.    to: Email address of the receiver.
  88.    subject: The subject of the email message.
  89.    message_text: The text of the email message.
  90.    file: The path to the file to be attached.
  91.  
  92.  Returns:
  93.    An object containing a base64url encoded email object.
  94.  """
  95.   message = MIMEMultipart()
  96.   message['to'] = to
  97.   message['from'] = sender
  98.   message['subject'] = subject
  99.  
  100.   msg = MIMEText(message_text)
  101.   message.attach(msg)
  102.  
  103.   content_type, encoding = mimetypes.guess_type(file)
  104.   print(content_type)
  105.   if content_type is None or encoding is not None:
  106.     content_type = 'application/octet-stream'
  107.   main_type, sub_type = content_type.split('/', 1)
  108.   print(main_type)
  109.   print(sub_type)
  110.   if main_type == 'text':
  111.     fp = open(file, 'rb')
  112.     msg = MIMEText(fp.read(), _subtype=sub_type)
  113.     fp.close()
  114.   elif main_type == 'image':
  115.     fp = open(file, 'rb')
  116.     msg = MIMEImage(fp.read(), _subtype=sub_type)
  117.     fp.close()
  118.   elif main_type == 'audio':
  119.     fp = open(file, 'rb')
  120.     msg = MIMEAudio(fp.read(), _subtype=sub_type)
  121.     fp.close()
  122.   else:
  123.     fp = open(file, 'rb')
  124.     msg = MIMEBase(main_type, sub_type)
  125.     msg.set_payload(fp.read())
  126.     encode_base64(msg)
  127.     msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
  128.     fp.close()
  129.   filename = os.path.basename(file)
  130.   msg.add_header('Content-Disposition', 'attachment', filename=filename)
  131.  
  132.   message.attach(msg)
  133.  
  134.   return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}
  135.  
  136. def SendMessage(service, user_id, message):
  137.   """Send an email message.
  138.  
  139.  Args:
  140.    service: Authorized Gmail API service instance.
  141.    user_id: User's email address. The special value "me"
  142.    can be used to indicate the authenticated user.
  143.    message: Message to be sent.
  144.  
  145.  Returns:
  146.    Sent Message.
  147.  """
  148.   try:
  149.     message = (service.users().messages().send(userId=user_id, body=message)
  150.                .execute())
  151.     print('Message Id: %s' % message['id'])
  152.     return message
  153.   except errors.HttpError:
  154.     print('An error occurred: %s' % error)
  155.  
  156.  
  157.  
  158. def main():
  159.     """Shows basic usage of the Gmail API.
  160.  
  161.    Creates a Gmail API service object and outputs a list of label names
  162.    of the user's Gmail account.
  163.    """
  164.     credentials = get_credentials()
  165.     http = credentials.authorize(httplib2.Http())
  166.     service = discovery.build('gmail', 'v1', http=http)
  167.  
  168.     results = service.users().labels().list(userId='me').execute()
  169.     labels = results.get('labels', [])
  170.     msg_att = create_message_with_attachment()
  171.     SendMessage(service, 'me',msg_att)
  172.  
  173.     # if not labels:
  174.     #     print('No labels found.')
  175.     # else:
  176.     #   print('Labels:')
  177.     #   for label in labels:
  178.     #     print(label['name'])
  179.  
  180.  
  181. if __name__ == '__main__':
  182.     main()`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement