Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
News_Service_ALLP1/EmailManager.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
64 lines (46 sloc)
2.02 KB
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
# Reference: How to send e-mails using Python | |
# https://www.youtube.com/watch?v=JRCJ6RtE3xU | |
import smtplib # to connect to gmail api | |
from email.message import EmailMessage # email formatting and reshaping | |
from APIManager import APIManager | |
from Database import DatabaseManager | |
class EmailManager: | |
dm = DatabaseManager() | |
api = APIManager() | |
# ---------------------- sends the email to a user | |
def sendEmailtoUser(self, email, subject, title, body, url): | |
EMAIL_ADDR = 'ema.univ@gmail.com' # email from | |
EMAIL_PASS = 'Emaun1v2k21' # password | |
# enter the content and format | |
content = f''' | |
News Alert | |
----------------------------------------------- | |
Title: {title} | |
{body} | |
Reference url: {url} | |
''' | |
msg = EmailMessage() | |
msg['Subject'] = subject # adding email subject | |
msg['From'] = EMAIL_ADDR # from email | |
msg['To'] = email # email recipient | |
msg.set_content(content) # email content | |
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: | |
smtp.login(EMAIL_ADDR, EMAIL_PASS) # login to API | |
smtp.send_message(msg) # send the msg | |
print(f"Email sent to {email} for {subject}") # prints msg acknowledgement | |
# ---------------------- fetches emails and categories | |
def sendEmails(self): | |
print(''' | |
--------------------------- | |
e-mails sending in progress | |
--------------------------- | |
''') | |
# import pandas as pd | |
df = self.dm.getSubscriptionsDF() # gets subscriptions .csv | |
cats = ['business', 'finance', 'computer', 'games', 'entertainment', 'music', 'currentAffairs', 'health', | |
'lifestyle', 'sports', 'culture', 'religion'] | |
for cat in cats: | |
print(">>", cat) | |
title, body, url = self.api.getNews(cat) # gets the news based on category | |
for email in df[df[cat] == 'y']['email']: # if category has 'y' variable | |
self.sendEmailtoUser(email, title, title, body, url) # sends the email | |