Skip to content

Instantly share code, notes, and snippets.

@devildani
Last active June 15, 2020 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devildani/619d1a9c256b24d4905955d96198bfb4 to your computer and use it in GitHub Desktop.
Save devildani/619d1a9c256b24d4905955d96198bfb4 to your computer and use it in GitHub Desktop.
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)
@ysaito8015
Copy link

My environment is Ubutnu 20.04, python 3.8.2

I hit the error below and then add import pickle

  File "./sending_mail.py", line 45, in get_service
    creds = pickle.load(token)
NameError: name 'pickle' is not defined

@ysaito8015
Copy link

one more thing

base64.urlsafe_b64encode() hits the error below

    File "./sending_mail.py", line 22, in create_message
      return {'raw': base64.urlsafe_b64encode(message.encode('utf-8'))}
AttributeError: 'MIMEText' object has no attribute 'encode'

I changed like this

 22     b64_bytes = base64.urlsafe_b64encode(message.as_bytes())↲                                          
 23     b64_string = b64_bytes.decode()↲                                                                   
 24     return {'raw': b64_string}

@devildani
Copy link
Author

@ysaito8015 Thanks, for the edits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment