origin
It is a development of communication , Too lazy to type, omitted , Check later
Management procedure
Some email companies that make email popular
MUA(MailUserAgent) Email user agent
MTA(MailTransferAgent) Mail transfer agent
MDA(MailDeliveryAgent) Mail delivery agent
technological process
MUT->MTA
qq MTA->...........................->sina MTA
sina MTA->.........................->sina MDA
sina MDA->MUA(FoxMail/outlook) Download email to local computer
Programming
send out MUA->MTA agreement
receive MTA->MDA agreement
preparation
Sign up for email
Third party mailbox settings
Enter the setting Center
Get authorization code
Case study 07 Send a plain text email ‘
import smtplib
from email.mime.text import MIMEText
#MIMEText The main parameters of are 3 individual
#1. Email content
#2.MIME subtypes , Here with plain representative text File format
#3. The encoding format of the message
msg = MIMEText(' This is an email in text format ','plain','utf-8')
# send out email The address of , Need to change to the corresponding email address
from_addr = '[email protected]'
# Authorization code , Most mailboxes use third-party software , You need to verify the key , This does not refer to the password of the mailbox
from_pwd = 'XXXXXXXXXXX'
# The recipient
to_addr = '[email protected]'
# Input smtplib Server address
# There are different values according to different mail service providers
# At present, almost any email service provider needs to start the service when opening the third-party email
#TX QQ Mailbox smtplib Address time smtplib.qq.com
smtp_srv = 'smtplib.qq.com'
try:
srv = smtplib.SNTP_SSL(smtp_srv.encode(),465) # there 465 when QQ Port of mailbox
# Log in to email , Any mailbox must be logged in before use
srv.login(from_addr,from_pwd)
# Send E-mail
# Three parameters , Sending address , Accepted address ( When necessary list Format ), String format when sending content
srv.sendmail(from_addr,[to_addr],msg.as_String())
srv.quit()
except Exception as e:
print(e)
Python for mail
SMTP The protocol is responsible for sending emails
Use Email Module build mail - Plain text cases V07
HTML Send by email
Get ready HTML Code as content
Put the mail subtype Set to html
send out
Case list V08
import smtplib
from email.mime.text import MIMEText
#MIMEText The main three parameters of
#1. Email content
#2.MIME Format of subtypes Here HTML So it is html
#3. The encoding format of the message
msg_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> This is a letter HTML Format message </h1>
</body>
</html>
"""
# The address where the mail is sent
from_addr = '[email protected]'
# Password to send email
from_pwd = 'XXXXXXXXXXx'
# The recipient
to_addr = '[email protected]'
# Input SMTP Server address
smtp_srv = 'smtp.qq.com'
try:
srv = smtplib.SMTP_SSL(smtp_srv.encode(),465)
# Log in to email
srv.login(from_addr,from_pwd)
# Send E-mail
srv.sendemail = (from_addr,[to_addr],msg_content.as_toString())
srv.quit()
except Exception as e:
print(e)
Send email with attachments
It can be seen as a combination of a text message and an attachment
Need to use MIMEltaipart Format construction
Add one MIMEBase perhaps MEME text As an attachment
Case list V09
import smtplib
from email.mime.text import MIMEText
from email.mime.text import MIMEBase,MIMMultipart # Use... When building the base message
mail_mul = MIMEMulipart()
# Build message body
main_text = MIMEText(" This is the body of the message ",'plain','utf-8')
# Attach the constructed body to the message
mail_mul.attach(mail_text)
# Build attachments , Need to read in from the local
# Open a local file
with open('a.txt','rb') as f:
s = f.read()
# Set attachment's MIME file name
m = MIMEText(s,'base64','utf-8')
m['Content-Type'] = 'application.octet-stream'
# Need to pay attention to
#1.attachment The semicolon after is in English
#2.filename English package is required at the back , Note that the outside quotation marks are staggered
m['Content-Dispostion'] = 'attachment;filename="a.txt"'
# add to MIMEMultipation
mail_mul.attach(m)
# Send E-mail
from_addr = '[email protected]'
from_pwd = 'XXXXXXXXx'
to_addr = '[email protected],com'
smtp_srv = 'sntp.qq.com'
try:
srv = smtplib.SMTP_SSL(smtp_srv.encode(),465)
# Log in to email
srv.load(from_addr,from_pwd)
srv.sendmail(from_addr,[to_addr],mail_mul.as_string())
srv.quit()
except Exception as e:
print(e)
Add headers , CC and other information
mail['From'] Indicates the sender's information , Include name and email
mail['To'] Indicates the recipient's information , Include name and email address
mail['Subject'] Represents a summary or subject information
Case study V10
Support at the same time html and text Format
Construct a MIMEMultipart Format message
MIMEMultipart Of subtype Set to alterbalive
add to html Document and text file
import smtplib
from email.mime.text import MIMEText
from email,mime.multipart import MIMEMUltipart
# Construct a MIMEMultipart mail
msg = MIMEMultapart('alternative')
# Construct a HTML Message content in different formats
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> This is a letter HTML Format message </h1>
</body>
</html>
"""
msg_html = MIMEText(html_content,'html','utf-8')
msg.attach(msg_html)
# Build a message in text format
msg_text = MIMEText(" This is a message in text format ",'plain','utf-8')
msg.attach(msg_text)
from_addr = '[email protected]'
from_pwd = 'XXXXX'
to_addr = "[email protected]"
smtp_srv = 'smtp.qq.com'
try:
srv = smtplib.SMTP_SSL(smtp_srv.encode(),465)
srv.login(from_addr,from_pwd)
srv_sendmail(from_addr,[to_addr],msg.as_tostring())
srv.quit()
except Exception as e:
print(e)
Use smtplib Module send mail
POP3 Agreement to accept email
In essence, it is from MDA To MTA A process of
from MDA The download is a complete email structure , Each band that requires parsing ability has
step :
1. use poplib Download the original content of the email structure
1. Prepare the corresponding content ( The content of the email , password .pop3 example )
2. Authentication
3. Generally, you will get the whole list of mail in the mailbox first
4. According to the corresponding serial number , Get the data stream of a letter
5. Use the analytic function to analyze the corresponding email structure
2.emai Analyze the specific content of the email
Case study V12
# Import related packages
#poplib Responsible for relevant MDA To MUA The download
import poplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
# Get the original content of the email
# This process is mainly responsible for MDA belt MUA Download and use Parse A rough analysis
def getMsg():
# Prepare the corresponding information
email = '[email protected]'
# Email authorization code
pwd = 'pwd'
#pop3 The server address of Default port 995
pop3_srv = 'pop.qq.com'
#SSL For safe passage
srv = poplib.POP3_SSL(pop3_srv)
#user representative Email Address
srv.user(email)
#pass_ Representative password
srv.pass_(pwd)
# The following operations are used according to the business content
#stat Return the number of messages and the space occupied
# Be careful stat Return to one tuple Format
msgs,counts = srv.stat()
print("messages:{0},Size{1}".format(msgs,counts))
#list Returns a list of all mail numbers
#malis Return to the list of all mail numbers
rsp,mails,octets = srv.list()
# You can view the return mails The list is similar to
print(mails)
# Get the latest email , Be careful , The index number of the message is from 1 Start , The latest email has the highest index number
index = len(mails)
#retr Responsible for returning the contents of a letter with a specific index number , This content is not readable
#lines Store each line of the highest original text of the message
rsp,lines,octets = srv.retr(index)
# Get the original text of the entire message
msg_count = b'\r\n'.join(lines).decode('utf8')
# Parse out the entire structure of the mail
# Parameter is used to decode the whole mail
msg = Parser().parsestr(msg_count)
# Close links
srv.quit()
return msg
#
# Explain the contents of the email in detail
#msg Represents the original content of the message
#idnent It represents the nesting level of mail
def parseMsg(msg,indent=0):
'''
1. Messages can be completely nested
2. There's only one mail From,To,Subject Information like that
:param msg:
:param indent: Describe several emails in the email MIMEXXX Type of content , Indent when showing
:return:
'''
# Find a way to extract header information
# Only in the first level of mail will there be relevant information content
# There's only one thing about this
if indent == 0:
for header in ['From','To','Subject']:
# Use get Can avoid if there is no relevant keyword error possibility
# If there are no keywords “From" In the use of msg["From"] When an error
value = msg.get(header,'')
if value:
#Subject You can decode the contents of , He's a string type
if header == 'Subject':
value = decodeStr(value)
# If it is From and To Field , Then the content is about ‘ My mailbox <[email protected]>’ This format
else:
hdr,addr = parseaddr(value)
name = decodeStr(hdr)
# The final return type is as follows “ My email is <[email protected]>”
value = "{0}<{1}>.".format(name,addr)
print("{0},{1}:{2}".format(indent,header,value))
# Next, focus on the email content itself
# In the content of the email , It could be multipart type , It could also be a normal mail type
# The following parsing uses a recursive method
if (msg.is_multipart()):
# If it is multipart Type calls recursive interpretation
# Get a base mail part of multipart mail
parts = msg.get_payload()
#enumerate Functions are built-in functions
# The function is to put a list , Here is parts, Generate an index and parts The list generated by the original content
# for example :enumerate(['a','b','c']) The result is :[(1,'a'),(2,'b'),(3,'c')]
for n,part in enumerate(parts):
# Multiplying a string by a number means that the string is n Double expansion
# for example ("aa"*2) = 'aaaa'
print("{0}spart:{1}".format(' '*indent,n))
parseMsg(part,indent+1)
else:# The base type
#get_content_type It's a system function , Get the type of content
content_type = msg.get_content_type()
#text/plain, Or is it text/html It's a fixed value
if content_type == 'text/plain' or content_type == 'text/html':
content = msg.get_payload(decode=True)
charset = gussCharset(msg)
if charset:
content = content.decode(charset)
print("{0}text:{1}".format(indent,content))
else:# It's not text content , It should be an attachment
print('{0}Attachment:{1}'.format(indent,content_type))
def decodeStr(s):
'''
s Represents... In an email from,to,Subject Any one of the
Yes s decode , Decoding is the inverse process of encoding
:param s:
:return:
'''
value,charset = decode_header(s)[0]
#charset It could be empty
if charset:
# If you specify the encoding , Decode with the specified encoding format
value = value.decode(charset)
return value
def gussCharset(msg):
'''
Guess the encoding format of the message
:param msg:
:return:
'''
# Call a ready-made function
charset = msg.get_charset()
if charset is None:
# Find the corresponding content type and convert it to lowercase
content_type = msg.get("Content-Type","").lower()
pos = content_type.find('charset=')
if pos > 0:
# If you include charset, The content is charset=XXX
charset = content_type[pos+8:].strip()
return charset
if __name__ == '__main__':
# Get the original content of the email
msg = getMsg()
print(msg)
# Accurately parse the contents of the email
parseMsg(msg,0)