Day 4

Python Sending Email




Olly

Book

Contents:

1. Basic python

  • Statement Assignment
  • print()
  • list
  • str()

2. Third-party modules

Check Modules Exist

You don't need to install smtplib/email, because they are in standard library.

Without Error Massage!!

import smtplib
import email

Let's Start!

SMTP Module

(Simple Mail Transfer Protocal)

  • The protocol used for sending email
  • SMTP dictates:
      * How email messages should be formatted
      * Encrypted
      * Relayed between mail servers
      * The other details that your computer handles after you click

Connecting to an SMTP Server

Provider SMTP server domain name
Gmail smtp.gmail.com
Outlook.com/Hotmail.com smtp-mail.outlook.com
Yahoo Mail smtp.mail.yahoo.com
In [3]:
import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
type(smtp)
Out[3]:
smtplib.SMTP

Notice!

  • Please connected to the Internet avoide socket.gaierror: [Errno 11004] getaddrinfo failed or similar exception
  • The port is an integer value and will almost always be 587
  • If SMTP server not support TLS on port 587.Please using smtplib.SMTP_SSL() and port 465 instead.

Greeting SMTP

.ehlo()
  • Be sure to call the ehlo() method first thing after getting the SMTP object or else the later method calls will result in errors
In [7]:
import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
Out[7]:
(250,
 b'smtp.gmail.com at your service, [27.242.33.131]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')

Greeting Success Lucky Number is "250"!

Starting TLS Encryption

If your prot is 587 on the SMTP server:

  • You’ll need to call the .starttls() method next
  • Using TLS encryption
  • .starttls() puts your SMTP connection in TLS mode.

If your port is 465 on the SMTP server:

  • Skip this step
  • Using SSL encryption
In [9]:
import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
Out[9]:
(220, b'2.0.0 Ready to start TLS')

Server is Ready Lucky Number is "220"!

Logging in to the SMTP Server

If you use Gmail, setup before login to SMTP server

>> Two Step Authentication

>> Gmail Applicaiton Password

Half the Battle Girls~

Try to Login Now!

import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('My_EmailAddress@gmail.com','My_PassWord')

Authentication Success Lucky Number is "235"!

Send Hello World with Gmail via Python

.sendmail('from@gmail','to@gmail', 'Text')

If you get empty dictionary you are success

In [7]:
smtp.sendmail('iamshihshan@gmail.com',
              'iamshihshan@gmail.com',
              'Subject: Hello World Email!\nDear Olly,\n\nHow are you?\n\nSincerely,\nOlly')
Out[7]:
{}

Close Connection

.quit()
In [10]:
smtp.quit()
Out[10]:
(451, b'4.4.2 Timeout - closing connection. j13sm21059804pff.131 - gsmtp')

Email Module

Sending Email with Attachment

Click to Download!

Import Modules

In [1]:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText

Logging in to the SMTP Server

import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('My_EmailAddress@gmail.com','My_PassWord')
In [17]:
message = MIMEMultipart()
message['Subject'] = Header('Email With Attachment', 'utf-8')
message.attach(MIMEText('Hello Olly,\n\nNice attach!!', 'plain', 'utf-8'))

Attaching File

In [ ]:
att = MIMEText(open('Imgs\D4_08.JPG', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="PyLadiesTaiwan_Logo.JPG"'
message.attach(att)

Sending Email With SMTP

In [5]:
smtp.sendmail('iamshihshan@gmail.com',
              'iamshihshan@gmail.com',
              message.as_string())
Out[5]:
{}

Sending Email Embedded with HTML

Import Modules

In [22]:
import smtplib
from email.header import Header
from email.mime.text import MIMEText

Logging in to the SMTP Server

import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('My_EmailAddress@gmail.com','My_PassWord')
In [23]:
message['Subject'] = Header('Email Embedded with HTML', 'utf-8')
mail_msg = """
<p>Python Embedded with HTML...</p>
<p><a href="http://tw.pyladies.com/">PyLadies Taiwan</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')

Sending Email With SMTP

In [8]:
smtp.sendmail('iamshihshan@gmail.com',
              ['iamshihshan@gmail.com','olly77vivian@yahoo.com.tw'],
              message.as_string())
Out[8]:
{}

Exercise

Send Any Kind of Email to Anyone You Want

  1. Get 16-digits process key form gmail
  2. Choose notification picture you like (or any file you want)
  3. Import modules
  4. Structuring email subject and contents
  5. Sending with SMTP
import smtplib
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText

Show Time

def Day4End() :

     return 'Thank U ❤'