Last active
June 15, 2020 04:34
-
-
Save pratik-dani/619d1a9c256b24d4905955d96198bfb4 to your computer and use it in GitHub Desktop.
This file contains 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 base64 | |
import pickle | |
from email.mime.text import MIMEText | |
from googleapiclient.discovery import build | |
def create_message(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_bytes()).decode()} | |
def send_message(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. | |
""" | |
message = (service.users().messages().send(userId=user_id, body=message) | |
.execute()) | |
print('Message Id: %s' % message['id']) | |
return message | |
def get_service(path): | |
with open(rf'{path}', 'rb') as token: | |
creds = pickle.load(token) | |
service = build('gmail', 'v1', credentials=creds) | |
return service | |
path_to_pickle = r"PATH_TO_PICKLE" | |
subject = "Hi! from python" | |
sender = "YOUR_MAIL_ID" | |
to = "MAIL_ID_TO_WHOM_YOU_WANT_TO_SEND" | |
message_text = "This e-mail is sent from Gmail API via python! Isn't that Cool?" | |
user_id = "me" | |
service = get_service(path_to_pickle) | |
raw_text = create_message(sender, to, subject, message_text) | |
message_data = send_message(service, user_id, raw_text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ysaito8015 Thanks, for the edits.