3. SMTP

3.1. Send plaintext email

Code Listing 3.24. Send plaintext email
import smtplib
from email.mime.text import MIMEText

smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
smtp_ssl_port = 465
username = 'USERNAME or EMAIL ADDRESS'
password = 'PASSWORD'
sender = '[email protected]'
targets = ['[email protected]', '[email protected]']

msg = MIMEText('Hi, how are you today?')
msg['Subject'] = 'Hello'
msg['From'] = sender
msg['To'] = ', '.join(targets)

server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
server.login(username, password)
server.sendmail(sender, targets, msg.as_string())
server.quit()

3.2. Send email with attachments

Code Listing 3.25. 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'

FROM = '[email protected]'
RCPT = ['[email protected]', '[email protected]']


msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = FROM
msg['To'] = ', '.join(RCPT)

txt = MIMEText('I just bought a new camera.')
msg.attach(txt)


filepath = '/path/to/image/file'

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

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


server = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT)
server.login(SMTP_USER, SMTP_PASS)
server.sendmail(FROM, RCPT, msg.as_string())
server.quit()

3.3. Secured connection to the SMTP server

Code Listing 3.26. Secured connection to the SMTP server
import ssl
import smtplib


smtp = smtplib.SMTP("mail.python.org", port=587)

context = ssl.create_default_context()

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