Add the following lines in the .env files of your project:
SMTP_USERNAME="sender_gmail_address"
SMTP_PASSWORD="app_password"
| import smtplib | |
| from email.mime.multipart import MIMEMultipart | |
| from email.mime.text import MIMEText | |
| from decouple import config | |
| class EmailSender: | |
| def __init__(self, smtp_server, smtp_port, smtp_username, smtp_password): | |
| self.smtp_server = smtp_server | |
| self.smtp_port = smtp_port | |
| self.smtp_username = smtp_username | |
| self.smtp_password = smtp_password | |
| def send_email_to_multiple_recipients(self, from_email, subject, message, recipients): | |
| # Create the email message | |
| msg = MIMEMultipart() | |
| msg['From'] = from_email | |
| msg['Subject'] = subject | |
| # Add the message body | |
| msg.attach(MIMEText(message, 'plain')) | |
| # Send the email to multiple recipients | |
| try: | |
| server = smtplib.SMTP(self.smtp_server, self.smtp_port) | |
| server.starttls() | |
| server.login(self.smtp_username, self.smtp_password) | |
| for recipient in recipients: | |
| msg['To'] = recipient | |
| server.sendmail(msg['From'], recipient, msg.as_string()) | |
| server.quit() | |
| print('Email sent successfully to multiple recipients') | |
| except Exception as e: | |
| print(f'Error: {e}') | |
| def main(): | |
| # Gmail SMTP server settings | |
| smtp_username = config('SMTP_USERNAME') | |
| smtp_password = config('SMTP_PASSWORD') | |
| smtp_server = 'smtp.gmail.com' | |
| smtp_port = 587 # Use 465 for SSL or 587 for TLS | |
| if smtp_username is None or smtp_password is None: | |
| print("SMTP_USERNAME or SMTP_PASSWORD not found in the .env file.") | |
| exit(1) | |
| email_sender = EmailSender(smtp_server, smtp_port, smtp_username, smtp_password) | |
| from_email = smtp_username | |
| subject = 'Your Subject' | |
| message = 'Your message goes here.' | |
| recipients = ['getachewabdulkarim7@gmail.com'] | |
| email_sender.send_email_to_multiple_recipients(from_email, subject, message, recipients) | |
| if __name__ == '__main__': | |
| main() |
| python-decouple==3.8 |