2.3. SMTP

2.3.1. Send plaintext email

Code 2.58. Send plaintext email
import smtplib
from email.mime.text import MIMEText


SMTP_HOST = 'smtp.gmail.com'
SMTP_PORT = 465
SMTP_USER = 'myusername@gmail.com'
SMTP_PASS = 'mypassword'

EMAIL_FROM = 'myusername@gmail.com'
EMAIL_TO = ['user1@example.com', 'user2@example.com']
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()

2.3.2. Send email with attachments

Code 2.59. 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 = 'myusername@gmail.com'
SMTP_PASS = 'mypassword'

EMAIL_FROM = 'myusername@gmail.com'
EMAIL_TO = ['user1@example.com', 'user2@example.com']
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 = r'/tmp/myfile.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()

2.3.3. Secured connection to the SMTP server

Code 2.60. 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')

2.3.4. Assignments

2.3.4.1. Send email

  • Assignment: Send email

  • Complexity: medium

  • Lines of code: 20 lines

  • Time: 21 min

English:
  1. Connect to SMTP server provided by instructor

  2. Send email to address provided by instructor

  3. Attach pep20.txt file which is a result of import this PEP 20 -- The Zen of Python

  4. Run doctests - all must succeed

Polish:
  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 -- The Zen of Python

  4. Uruchom doctesty - wszystkie muszą się powieść