Skip to content

Instantly share code, notes, and snippets.

@zobayer1
Last active November 1, 2023 07:23
Show Gist options
  • Save zobayer1/3c69cc2f3342f25339a82ec7b1369129 to your computer and use it in GitHub Desktop.
Save zobayer1/3c69cc2f3342f25339a82ec7b1369129 to your computer and use it in GitHub Desktop.
Send Emails from GMail using Python SMTP library
# -*- 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 = "youraddress@gmail.com"
password = "your_app_password"
sender = formataddr(("Your Name", "youraddress@gmail.com"))
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
@zobayer1
Copy link
Author

zobayer1 commented Jun 28, 2021

Create an app password: https://support.google.com/accounts/answer/185833

Example usage:

#!/usr/bin/env python3
body = """\
<!DOCTYPE html>
<html><body>
<h3><a style="text-decoration: none;" href="https://gist.github.com/zobayer1">Zobayer's Gists</a></h3>
<div><p>Feel free to look around!!!</p></div>
</body></html>
"""
emailer = SendMail()
emailer.send(
    [
        "addr1@gmail.com",
        "addr2@myemail.com",
    ],
    "Hello there!!!",
    body,
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment