Last active
November 1, 2023 07:23
-
-
Save zobayer1/3c69cc2f3342f25339a82ec7b1369129 to your computer and use it in GitHub Desktop.
Send Emails from GMail using Python SMTP library
This file contains hidden or 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
# -*- coding: utf-8 -*- | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.utils import formataddr | |
from typing import List | |
class SendMail(object): | |
host, port = "smtp.gmail.com", 465 | |
username = "[email protected]" | |
password = "your_app_password" | |
sender = formataddr(("Your Name", "[email protected]")) | |
def __init__(self): | |
try: | |
self.server = smtplib.SMTP_SSL(self.host, self.port) | |
self.server.ehlo() | |
self.server.login(self.username, self.password) | |
print("Connected to GMail server") | |
except Exception as err: | |
print(f"Error connecting to server: {str(err)}") | |
def __del__(self): | |
try: | |
self.server.close() | |
print("Connection closed") | |
except Exception as err: | |
print(f"Error occurred while closing connection: {str(err)}") | |
def send(self, receivers: List[str], subject: str, body: str, subtype: str = "html") -> bool: | |
try: | |
message = MIMEMultipart("alternative") | |
message["To"] = ", ".join(receivers) | |
message["From"] = self.sender | |
message["Subject"] = subject | |
message.attach(MIMEText(body, subtype)) | |
self.server.sendmail(self.sender, receivers, message.as_string()) | |
print("Email sent") | |
return True | |
except Exception as err: | |
print(f"Error occurred while sending email: {str(err)}") | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create an app password: https://support.google.com/accounts/answer/185833
Example usage: