Created
April 24, 2018 03:02
-
-
Save nitrocode/b00f8f210209bc5d4d6309c73208e540 to your computer and use it in GitHub Desktop.
Sending emails in gmail in an easy, python3 script
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
| # Modified from https://stackoverflow.com/a/37267330/2965993 | |
| # I cannot believe how freaking difficult it is to send an email in gmail... hopefully this will simplify it | |
| import httplib2 | |
| import base64 | |
| from email.mime.multipart import MIMEMultipart | |
| from email.mime.text import MIMEText | |
| from apiclient import errors, discovery | |
| from oauth2client import file, client, tools | |
| SCOPES = 'https://www.googleapis.com/auth/gmail.send' | |
| CLIENT_SECRET_FILE = 'client_id.json' | |
| APPLICATION_NAME = 'Gmail API Python Send Email' | |
| def get_credentials(): | |
| store = file.Storage('credentials.json') | |
| flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) | |
| flow.user_agent = APPLICATION_NAME | |
| return tools.run_flow(flow, store) | |
| def create_message(sender, to, subject, body): | |
| msg = MIMEMultipart('alternative') | |
| msg['Subject'] = subject | |
| msg['From'] = sender | |
| msg['To'] = to | |
| msg.attach(MIMEText(body, 'html')) | |
| return {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()} | |
| def send_email(sender, to, subject, body): | |
| credentials = get_credentials() | |
| http = credentials.authorize(httplib2.Http()) | |
| service = discovery.build('gmail', 'v1', http=http) | |
| message = create_message(sender, to, subject, body) | |
| try: | |
| message = (service.users().messages().send(userId="me", body=message).execute()) | |
| return message | |
| except errors.HttpError as error: | |
| print('An error occurred: %s' % error) | |
| if __name__ == '__main__': | |
| res = send_email( | |
| "receiver@gmail.com", | |
| "sender@gmail.com", | |
| "Subject matter", | |
| "Your body is a temple" | |
| ) | |
| print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment