Created
September 24, 2018 06:26
-
-
Save abhi1010/21dd891ea4df5ca9507c5fa945cb9005 to your computer and use it in GitHub Desktop.
send mails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import httplib2 | |
from email.encoders import encode_base64 | |
from apiclient import discovery | |
from oauth2client import client | |
from oauth2client import tools | |
from oauth2client.file import Storage | |
import base64 | |
from email.mime.audio import MIMEAudio | |
from email.mime.base import MIMEBase | |
from email.mime.image import MIMEImage | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
import mimetypes | |
import os | |
from apiclient import errors | |
try: | |
import argparse | |
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() | |
except ImportError: | |
flags = None | |
# If modifying these scopes, delete your previously saved credentials | |
# at ~/.credentials/gmail-python-quickstart.json | |
SCOPES = 'https://mail.google.com/' | |
CLIENT_SECRET_FILE = 'client_id.json' | |
APPLICATION_NAME = 'Gmail API Python Quickstart' | |
def get_credentials(): | |
"""Gets valid user credentials from storage. | |
If nothing has been stored, or if the stored credentials are invalid, | |
the OAuth2 flow is completed to obtain the new credentials. | |
Returns: | |
Credentials, the obtained credential. | |
""" | |
home_dir = os.path.expanduser('~') | |
credential_dir = os.path.join(home_dir, '.credentials') | |
if not os.path.exists(credential_dir): | |
os.makedirs(credential_dir) | |
credential_path = os.path.join(credential_dir, | |
'gmail-python-quickstart.json') | |
store = Storage(credential_path) | |
credentials = store.get() | |
if not credentials or credentials.invalid: | |
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) | |
flow.user_agent = APPLICATION_NAME | |
if flags: | |
credentials = tools.run_flow(flow, store, flags) | |
else: # Needed only for compatibility with Python 2.6 | |
credentials = tools.run(flow, store) | |
print('Storing credentials to ' + credential_path) | |
return credentials | |
def CreateMessage(sender, to, subject, message_text): | |
"""Create a message for an email. | |
Args: | |
sender: Email address of the sender. | |
to: Email address of the receiver. | |
subject: The subject of the email message. | |
message_text: The text of the email message. | |
Returns: | |
An object containing a base64url encoded email object. | |
""" | |
message = MIMEText(message_text) | |
message['to'] = to | |
message['from'] = sender | |
message['subject'] = subject | |
return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')} | |
def create_message_with_attachment( | |
sender, to, subject, message_text, file): | |
"""Create a message for an email. | |
Args: | |
sender: Email address of the sender. | |
to: Email address of the receiver. | |
subject: The subject of the email message. | |
message_text: The text of the email message. | |
file: The path to the file to be attached. | |
Returns: | |
An object containing a base64url encoded email object. | |
""" | |
message = MIMEMultipart() | |
message['to'] = to | |
message['from'] = sender | |
message['subject'] = subject | |
msg = MIMEText(message_text) | |
message.attach(msg) | |
content_type, encoding = mimetypes.guess_type(file) | |
print(content_type) | |
if content_type is None or encoding is not None: | |
content_type = 'application/octet-stream' | |
main_type, sub_type = content_type.split('/', 1) | |
print(main_type) | |
print(sub_type) | |
if main_type == 'text': | |
fp = open(file, 'rb') | |
msg = MIMEText(fp.read(), _subtype=sub_type) | |
fp.close() | |
elif main_type == 'image': | |
fp = open(file, 'rb') | |
msg = MIMEImage(fp.read(), _subtype=sub_type) | |
fp.close() | |
elif main_type == 'audio': | |
fp = open(file, 'rb') | |
msg = MIMEAudio(fp.read(), _subtype=sub_type) | |
fp.close() | |
else: | |
fp = open(file, 'rb') | |
msg = MIMEBase(main_type, sub_type) | |
msg.set_payload(fp.read()) | |
encode_base64(msg) | |
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file)) | |
fp.close() | |
filename = os.path.basename(file) | |
msg.add_header('Content-Disposition', 'attachment', filename=filename) | |
message.attach(msg) | |
return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')} | |
def SendMessage(service, user_id, message): | |
"""Send an email message. | |
Args: | |
service: Authorized Gmail API service instance. | |
user_id: User's email address. The special value "me" | |
can be used to indicate the authenticated user. | |
message: Message to be sent. | |
Returns: | |
Sent Message. | |
""" | |
try: | |
message = (service.users().messages().send(userId=user_id, body=message) | |
.execute()) | |
print('Message Id: %s' % message['id']) | |
return message | |
except errors.HttpError: | |
print('An error occurred: %s' % error) | |
def main(): | |
"""Shows basic usage of the Gmail API. | |
Creates a Gmail API service object and outputs a list of label names | |
of the user's Gmail account. | |
""" | |
credentials = get_credentials() | |
http = credentials.authorize(httplib2.Http()) | |
service = discovery.build('gmail', 'v1', http=http) | |
results = service.users().labels().list(userId='me').execute() | |
labels = results.get('labels', []) | |
msg_att = create_message_with_attachment() | |
SendMessage(service, 'me',msg_att) | |
# if not labels: | |
# print('No labels found.') | |
# else: | |
# print('Labels:') | |
# for label in labels: | |
# print(label['name']) | |
if __name__ == '__main__': | |
main()` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment