Cyber Range ·TelecomunicazioniLaboratorio●●●●○

EXTRA > EMAIL

Configurazione

Generazione Password per la propria applicazione google

!! ATTENZIONE !! : In caso non vi permetta di settare la password / vi dia errore la pagina, provare a passare ad un account personale (non scuola) e abilitare l'autenticazione a due fattori.

Installazione modulo necessario per il serv er smtp

pip install secure-smtplib

Tutorial online per approfondimento:

Invio email standard

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

# Dati di accesso e destinatario
gmail_user = 'tuoindirizzo@gmail.com'
app_password = 'la-tua-app-password-generata'
to_email = 'destinatario@example.com'

# Composizione del messaggio
subject = 'Oggetto della mail'
body = 'Ciao! Questa è una mail inviata con Python 🚀'

# Creazione messaggio
message = MIMEMultipart()
message['From'] = gmail_user
message['To'] = to_email
message['Subject'] = subject

message.attach(MIMEText(body, 'plain'))

try:
    # Connessione al server SMTP di Gmail
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()  # Crittografia TLS
    server.login(gmail_user, app_password)
    server.send_message(message)
    print('Email inviata con successo!')
except Exception as e:
    print('Errore durante l\'invio:', e)
finally:
    server.quit()

Invio email con HTML

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

sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = input("Type your password and press enter:")

message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\
<html>
  <body>
    <p>Hi,<br>
       How are you?<br>
       <a href="http://www.realpython.com">Real Python</a> 
       has many great tutorials.
    </p>
  </body>
</html>
"""

# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)

# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )

Segna come completato

Hai studiato questa dispensa? Segna il completamento per sbloccare i nodi successivi.

Accedi per salvare il progresso.