Day 4

Python Sending Email




Olly & Jamie

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 [1]:
import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)

Notice!

  • Please connected to the Internet avoid 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 [2]:
import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
Out[2]:
(250,
 'smtp.gmail.com at your service, [114.32.166.114]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8')

Greeting Success Number is "250"!

Starting TLS Encryption

If your port 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 [3]:
import smtplib
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
Out[3]:
(220, '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

Web

  • Click "2-Step Verification"

Web

  • Click "開始檢查"

Web

  • Login

Web

  • Click "立即試用"

Mobile

  • Choose "是"

網頁端

  • Enter your phone number
  • Click "傳送"

Mobile

Web

  • Enter the verification code from your text message

Web

  • Click "啟用"

Web

  • Turn on 2-Step Verification Sucessfully!!

>> Gmail Applicaiton Password

Web

  • Click "How to generate an App passwords"
  • And click "App passwords"

Web

  • login

Web

  • Click "立即試用"

Mobile

  • Click "是"

Web

  • Choose "其他(自訂名稱)"

Web

  • Enter an Application Password name
  • Click "產生"

Web

  • Copy your Application Password from the yellow bar
  • Click "完成"

Web

  • Applied Application Password successfully!!

Half the Battle Girls~

Try to Login Now!

.login('email', 'password')
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 [5]:
smtp.sendmail('mycoffeeyoa@gmail.com',
              'mycoffeeyoa@gmail.com',
              'Subject: Hello World Email!\n\nDear Jamie,\n\nHow are you?\n\nSincerely,\nJamie')
Out[5]:
{}


Send email to many people

.sendmail('from@gmail', ['to1@gmail', 'to2@gmail', ...], 'Text')

If you get empty dictionary, you are success

In [6]:
smtp.sendmail('mycoffeeyoa@gmail.com',
              ['mycoffeeyoa@gmail.com', 'jmw@leadinfo.com.tw'],
              'Subject: Hello World Email!\nDear Jamie,\n\nHow are you?\n\nSincerely,\nJamie')
Out[6]:
{}

Close Connection

.quit()
In [7]:
smtp.quit()
Out[7]:
(221, '2.0.0 closing connection j5-v6sm7956358pgp.6 - gsmtp')

Server is Ready Lucky Number is "221"!

Email Module

MIME

"Multipurpose Internet Mail Extensions" (mime) is a package under Email module

  • text
  • image
  • multipart
In [8]:
from email.mime.text import MIMEText 
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart 

MIMEText

MIMEText(text, subType, charset)

With text/plain

In [9]:
from email.mime.text import MIMEText   

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"    
text_plain = MIMEText(text,'plain', 'utf-8') 
text_plain.add_header("To","mycoffeeyoa@gmail.com")
text_plain.add_header("Subject","Hello World Email!")
In [11]:
smtp.sendmail('mycoffeeyoa@gmail.com',
              'mycoffeeyoa@gmail.com',
              text_plain.as_string())
Out[11]:
{}

With text/html

In [12]:
from email.mime.text import MIMEText   

html = """
<html>  
  <body>  
    <p> 
       Here is the <a href="http://www.baidu.com">link</a> you wanted.
    </p> 
  </body>  
</html>  
"""    
text_html = MIMEText(html, 'html', 'utf-8')
text_html.add_header("To","mycoffeeyoa@gmail.com")
text_html.add_header("Subject","Hello World Email!")
In [14]:
smtp.sendmail('mycoffeeyoa@gmail.com',
              'mycoffeeyoa@gmail.com',
              text_html.as_string())
Out[14]:
{}

MIMEImage

MIMEText(File_name, SubType)

In [15]:
from email.mime.image import MIMEImage

sendimagefile=open(r'D4_08.JPG','rb').read()
image = MIMEImage(sendimagefile, 'jpeg')
image["To"] = 'mycoffeeyoa@gmail.com'
image["Subject"] = 'PyLadiesTaiwan_Logo'
In [17]:
smtp.sendmail('mycoffeeyoa@gmail.com','mycoffeeyoa@gmail.com', image.as_string())
Out[17]:
{}

MIMEMultipart

MIMEText(SubType)

  • subType:alternative, related, mixed...
- alternative:email includes text/plain or text/html
- related:email includes images or recordings
- mixed:email includes text/plain, text/html images, recordings... and so on
In [18]:
from email.mime.multipart import MIMEMultipart 

msg = MIMEMultipart('mixed')
In [19]:
msg['Subject'] = 'Greeting from Pyladies!!'
msg['From'] = 'mycoffeeyoa@gmail.com <mycoffeeyoa@gmail.com>'
msg['To'] = 'mycoffeeyoa@gmail.com'
In [20]:
#郵件內文
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"    
msg.attach(MIMEText(text,'plain', 'utf-8')) 

#郵件 html 內文
html = """
<html>  
  <body>  
    <p> 
       Here is the <a href="http://www.baidu.com">link</a> you wanted.
    </p> 
  </body>  
</html>  
"""    
msg.attach(MIMEText(html, 'html', 'utf-8'))

#郵件附件圖片
sendimagefile=open(r'D4_08.JPG','rb').read()
image = MIMEImage(sendimagefile, 'jpeg')
msg.attach(image) 
In [22]:
smtp.sendmail('mycoffeeyoa@gmail.com',
              'mycoffeeyoa@gmail.com',
              msg.as_string())
Out[22]:
{}

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 ❤'