· Tutorial ·

How to send mails from Python

To send emails from Python3 in an authenticated way via SMTP, you can use the smtplib library.

You will need the access data to the email account from which the emails are going to be sent, together with the access data to the server. In this case, we will use the following data:

info It is recommended to have a TLS certificate installed for email. You can install it from the following manual.

Sending an email in plain text format

The code for sending an email in plain text and HTML is very similar.

In this case, we are sending an email to the destination '[email protected]', with the subject "Welcome to SWPanel" and the text: "Welcome to SWPanel Log in to your SWPanel: https://swpanel.com" in plain text format.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Configuración de la connexión
sender = '[email protected]'
password = 'Password'
server = 'mail.swmanuales.com'
port = 465

# Configuración del destinatario
to = '[email protected]'

# configuración de las cabeceras y del mensaje
message = MIMEMultipart("alternative")
message["Subject"] = "Bienvenido/a a SWPanel"
message["From"] = sender
message["To"] = to

body = """
Bienvenido/a a SWPanel

Accede a tu SWPanel: https://swpanel.com
"""

part = MIMEText(body, "plain")
message.attach(part)

# Envío del mensaje
try:
    smtp_server = smtplib.SMTP_SSL(server, port)
    smtp_server.ehlo()
    smtp_server.login(sender, password)
    smtp_server.sendmail(sender, to, message.as_string())
    smtp_server.close()
    print ("¡Se ha enviado correctamente!")
except Exception as ex:
    print ("Ha ocurrido un error...",ex)

To run it, we can use the following command from the terminal:

python3 nombre_del_fichero.py

If everything went well, it should return: "Successfully sent!".

Sending an email in HTML format

To send an email with HTML content, we can use this variant of the code. HTML formatting allows us to add styles to the message:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Connection configuration
sender = '[email protected]'
password = 'Password'
server = 'mail.swmanuales.com'
port = 465

# Recipient configuration
to = '[email protected]'

# header and message configuration
message = MIMEMultipart("alternative")
message["Subject"] = "Bienvenido/a a SWPanel"
message["From"] = sender
message["To"] = to

body = """\
<html>
<head>
    <style>
        .boton {
            background-color: #089cff;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>Bienvenido/a a SWPanel</h1>
    <p><a href="https://swpanel.com" class="boton">Accede a tu SWPanel</a></p>
</body>
</html>
"""


part = MIMEText(body, "html")
message.attach(part)

# Sending the message
try:
    smtp_server = smtplib.SMTP_SSL(server, port)
    smtp_server.ehlo()
    smtp_server.login(sender, password)
    smtp_server.sendmail(sender, to, message.as_string())
    smtp_server.close()
    print ("¡Se ha enviado correctamente!")
except Exception as ex:
    print ("Ha ocurrido un error...",ex)

To run it, we can use the following command from the terminal:

python3 nombre_del_fichero.py

If everything went well, it should return: "Successfully sent!".

Automating the sending of mail

From the previous code, we can define a function that will be in charge of sending the email and, through a list, we can define the content of the emails that we will send.

In this way, we will not need to edit the document to change the recipient or the content of the email.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys

# Creation of the function that performs the sending
def send_mail(destination, subject, body):
  # Configuración de la connexión
  sender = '[email protected]'
  password = 'Password'
  server = 'mail.swmanuales.com'
  port = 465

  # header and message configuration
  message = MIMEMultipart("alternative")
  message["Subject"] = subject
  message["From"] = sender
  message["To"] = destination

  part = MIMEText(body, "html")
  message.attach(part)

  # Sending the message
  try:
      smtp_server = smtplib.SMTP_SSL(server, port)
      smtp_server.ehlo()
      smtp_server.login(sender, password)
      smtp_server.sendmail(sender, destination, message.as_string())
      smtp_server.close()
      print ("¡Se ha enviado correctamente!")
  except Exception as ex:
      print ("Ha ocurrido un error...",ex)



text = {
  #'identificador': ['Asunto', 'cuerpo']
  'welcome': ['Bienvenido/a a SWPanel', '<html> <head> <style> .boton { background-color: #089cff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; } </style> </head> <body> <h1>Bienvenido/a a SWPanel</h1> <p><a href="https://swpanel.com" class="boton">Accede a tu SWPanel</a></p> </body> </html>'],
  'other_text': 'other text',
  'other_text2': 'other text 2',
}


message = text[sys.argv[0]]
subject = message[0]
body = message[1]

# Recipient configuration
destination = sys.argv[1]

send_mail(destination, subject, body)

When executing the file by console, we will indicate the type of mail we want to send and the recipient to whom it should be sent.

To execute it, we can use the following command from the terminal:

python3 nombre_del_fichero.py welcome [email protected]

Where 'welcome' is the identifier in the list and '[email protected]' is the destination account.

If everything went well, it should return: "Successfully sent!".

i