3. SMTP

3.1. Send plaintext email

Listing 459. Send plaintext email
import smtplib
from email.mime.text import MIMEText


SMTP_HOST = 'smtp.gmail.com'
SMTP_PORT = 465
SMTP_USER = '[email protected]'
SMTP_PASS = 'mypassword'

EMAIL_FROM = '[email protected]'
EMAIL_TO = ['[email protected]', '[email protected]']
EMAIL_SUBJECT = 'My Subject'
EMAIL_BODY = 'My Email Body'


msg = MIMEText(EMAIL_BODY)
msg['Subject'] = EMAIL_SUBJECT
msg['From'] = EMAIL_FROM
msg['To'] = ', '.join(EMAIL_TO)


server = smtplib.SMTP_SSL(
    host=SMTP_HOST,
    port=SMTP_PORT)

server.login(
    user=SMTP_USER,
    password=SMTP_PASS)

server.sendmail(
    from_addr=EMAIL_FROM,
    to_addrs=EMAIL_TO,
    msg=msg.as_string())

server.quit()

3.2. Send email with attachments

Listing 460. Send email with attachments
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart


SMTP_HOST = 'smtp.gmail.com'
SMTP_PORT = 465
SMTP_USER = '[email protected]'
SMTP_PASS = 'mypassword'

EMAIL_FROM = '[email protected]'
EMAIL_TO = ['[email protected]', '[email protected]']
EMAIL_SUBJECT = 'My Subject'
EMAIL_BODY = 'My Email Body'


msg = MIMEMultipart()
msg['Subject'] = EMAIL_SUBJECT
msg['From'] = EMAIL_FROM
msg['To'] = ', '.join(EMAIL_TO)

txt = MIMEText(EMAIL_BODY)
msg.attach(txt)


FILE = '/path/to/image/file.png'

with open(FILE, mode='rb') as file:
    img = MIMEImage(file.read())

img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(FILE))
msg.attach(img)


server = smtplib.SMTP_SSL(
    host=SMTP_HOST,
    port=SMTP_PORT)

server.login(
    user=SMTP_USER,
    password=SMTP_PASS)

server.sendmail(
    from_addr=EMAIL_FROM,
    to_addrs=EMAIL_TO,
    msg=msg.as_string())

server.quit()

3.3. Secured connection to the SMTP server

Listing 461. Secured connection to the SMTP server
import ssl
import smtplib


SMTP_HOST = 'localhost'
SMTP_PORT = 465
SMTP_USER = 'myusername'
SMTP_PASS = 'mypassword'


smtp = smtplib.SMTP_SSL(
    host=SMTP_HOST,
    port=SMTP_PORT)

context = ssl.create_default_context()

smtp.starttls(context=context)
# (220, b'2.0.0 Ready to start TLS')

3.4. Assignments

3.4.1. Send email

  • Complexity level: medium

  • Lines of code to write: 20 lines

  • Estimated time of completion: 25 min

  • Filename: solution/smtp_ssl.py

  1. Połącz się z serwerem podanym przez prowadzącego

  2. Wyślij wiadomość email na podany przez prowadzącego adres

  3. Do wiadomości załącz plik pep20.txt, który będzie wynikiem polecenia import this PEP 20