ApplicantPortal/app/email/__init__.py

44 lines
1.5 KiB
Python
Raw Permalink Normal View History

2025-03-13 02:43:26 +00:00
from __future__ import print_function
from flask import current_app
from googleapiclient.discovery import build
from apiclient import errors
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64
from google.oauth2 import service_account
def login():
scopes = ['https://www.googleapis.com/auth/gmail.send']
service_account_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'service-key.json'))
creds = service_account.Credentials.from_service_account_file(service_account_file, scopes=scopes)
delegated_creds = creds.with_subject(current_app.config['MAIL_USERNAME'])
service = build('gmail', 'v1', credentials=delegated_creds)
return service
def create_message(subject, sender, recipient, txt_body, html_body):
message = MIMEMultipart('alternative')
message['To'] = recipient
message['From'] = sender
message['Subject'] = subject
message.attach(MIMEText(txt_body, 'plain'))
message.attach(MIMEText(html_body, 'html'))
return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')}
def send_email(subject, sender, recipient, txt_body, html_body):
service = login()
message = create_message(subject, sender, recipient, txt_body, html_body)
try:
msg = (service.users().messages().send(userId='me', body=message).execute())
print(f'Message ID: {msg["id"]}')
return msg
except errors.HttpError as error:
print(f'Failed to send message: {str(error)}')