-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyemail.py
70 lines (62 loc) · 2.32 KB
/
myemail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from apiclient import errors
from httplib2 import Http
from email.mime.text import MIMEText
import base64
from googleapiclient.discovery import build
from google.oauth2 import service_account
import pdb
import os
EMAIL_FROM = "[email protected]"
EMAIL_TO = "[email protected]"
EMAIL_SUBJECT = "Report: Error while uploading recordings"
EMAIL_CONTENT = 'Hello, this is a test\nLyfepedia\nhttps://lyfepedia.com'
class Email:
def __init__(self):
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
BASE_PATH = os.path.abspath(os.curdir)
# BASE_PATH = '/root/miami-scripts'
SERVICE_ACCOUNT_FILE = f'{BASE_PATH}/creds/google_secret.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,
scopes=SCOPES,
subject=EMAIL_FROM)
# delegated_credentials = credentials.with_subject(EMAIL_FROM)
self.service = build('gmail', 'v1', credentials=credentials, cache_discovery=False)
def send_message(self, msg):
message = self.create_message(EMAIL_FROM, EMAIL_TO, EMAIL_SUBJECT, msg)
sent = self._send_message('me', message)
def create_message(self, 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['cc'] = "[email protected]"
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string().encode('utf-8')).decode("ascii")}
def _send_message(self, 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 = self.service.users().messages().send(userId=user_id, body=message).execute()
print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
if __name__ == '__main__':
myemail = Email()
myemail.send_message('test1')