Sending Mail with Python SMTP

Python SMTP Mail

Sending Mail with Python SMTP

 Hello everyone, in this post I will explain to you in a very simple way how you can send mail using SMTP with Python3, and of course, in addition to sending regular mail messages, I will also talk about sending mail in HTML format.

Sending Regular Mail with SMTP

Yes, let’s first take a look at how to send a regular mail. Of course, friends, this method can sometimes result in the mail not being sent or falling into spam. 

Therefore, I recommend using the next step for your main projects.

import smtplib

class MailManager:
    def __init__(self) -> None:
            self.fromMail = "deneme@yandex.com" # The e-mail address of the account we’ll send from
            self.fromPassword = "" # The password of the account we’ll send from
            self.smtpHost = "smtp.yandex.com" # Server to send mail from
            self.smtpPort = 465 # SMTP port of the server
       

    def SendMail(self, subject, content, toMail):
        try:
            email_text = """
From: %s  
To: %s  
Subject: %s

%s
            """ % (self.fromMail, toMail, subject, content)

            mail = smtplib.SMTP(self.smtpHost,self.smtpPort) # defining the smtp server
            mail.ehlo() # starting the server
            mail.starttls() # starting ttls
            mail.login(self.fromMail, self.fromPassword) # logging into the smtp server
            mail.sendmail(self.fromMail,toMail,email_text) # sending our message
        except Exception as e:
            print(f"An error occurred\n {e}") # Reporting that an error has occurred
        finally:
            mail.quit() # closing the server connection, you can also use ".close()" instead of quit

# How to use
mailMan = MailManager()
mailMan.SendMail("mail subject","mail content", "recipient email address")

It is that simple to send mail with SMTP in Python.

Sending Mail in HTML Format with SMTP

Now, let’s see how to send mail as HTML. In order to send mail as HTML, we need to set the MIME type as HTML. 

For this, we need to include a few additional libraries in our project, so let's examine these codes.

import smtplib # Our SMTP library
from email.mime.text import MIMEText # Library for setting the MIME type
from email.mime.multipart import MIMEMultipart # Library for setting multiple types

class MailManager:
    def __init__(self) -> None:
        self.fromMail = "" # Sender email address
        self.fromPassword ="" # Sender email password
        self.smtpHost = "" # SMTP server address
        self.smtpPort =  # SMTP server port
       

    def SendMail(self, subject, content, toMail):
        try:
            message = MIMEMultipart("alternative") 
            message["Subject"] = subject # Subject
            message["From"] = self.fromMail # Sender email address
            message["To"] = toMail # Recipient address

            _content = MIMEText(content.encode('utf-8'), _charset='utf-8') # Here, we set the MIME type. You can use "MIMEText(html, "html")" to send HTML.
            message.attach(_content) # Attaching our message

            with smtplib.SMTP_SSL(self.smtpHost, self.smtpPort) as server: # Connecting to the server
                server.login(self.fromMail, self.fromPassword) # Logging into the server
                server.sendmail(self.fromMail, toMail, message.as_string()) # Sending our mail
        except Exception as e:
            print(f"Mail could not be sent!\nError Code: {e}\nMail subject : {subject} \nMail content : {content} \nRecipient : {toMail}") # Printing if there’s an error


# How to use
mailManager = MailManager()
mailManager.SendMail("Mail subject", "Mail content", 'recipient email address')


Yes, friends, I tried to explain everything alongside the codes, but if you still have questions about anything, you can ask me here as a comment.