Skip to content

Instantly share code, notes, and snippets.

@Mr-MaNia7
Last active November 26, 2023 16:38
Show Gist options
  • Save Mr-MaNia7/d050df5598bbb0f8afac7d2c31396a31 to your computer and use it in GitHub Desktop.
Save Mr-MaNia7/d050df5598bbb0f8afac7d2c31396a31 to your computer and use it in GitHub Desktop.
email-sender-gmail

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 = ['[email protected]']
email_sender.send_email_to_multiple_recipients(from_email, subject, message, recipients)
if __name__ == '__main__':
main()
python-decouple==3.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment