Article From:https://www.cnblogs.com/zhangxinqi/p/9113859.html

 

1、smtplibCommon classes and methods of modules

smtplibThe module realizes the sending function of the mail, simulates a STMP client and realizes the mail sending function by interacting with the SMTP server. It can be understood as the mail function of the Foxmail. Before use, we need to prepare the SMTP server host address, the mailbox account, and the password information.

After python2.3, python comes with smtplib module without additional installation.

class smtplib.SMTP(host=””,port=0,local_hostname=None,[timeout,]source_address=None):

SMTPClass definition, as the constructor of SMTP, defines a SMTP client session object, and the function is to establish a link with the SMTP server. After the link is successful, it can send related requests to the server, such as landing, checking, sending, and exiting.

  • host:The parameter is a remote SMTP host address; for example, smtp.163.com
  • port:Default of link port is 25
  • local_hostname:The instruction to send the FQDN (full domain name) of the local host to HELO/EHLO (identify user identity).
  • timeout:How many seconds after a link or try link
  • source_address:Bound to a specific source address on a computer with multiple network interfaces or a specific TCP port, it requires a tuple (host, port).

SMTPClass methods:

SMTP.connect(host=’localhost’,port=0) :The way to link to a remote SMTP host, host as a remote host address, port as a remote host SMTP port, the default is 25, and can be expressed directly in the form of host:port, such as SMTP.connect (‘smtp.163.com’)’25’)

SMTP.login(user,password):Login requires authentication of the SMTP server, the parameters are user name and password, such as SMTP.login (‘python@163.com’,’123′).

SMTP.sendmail(from_addr,to_addrs,msg,mail_options=[],rcpt_options=[]):The message is sent, the parameter from_addr is the sender, the to_addrs is the recipient, and the MSG is the mail content, such as SMTP.sendmail (‘python@163.com’,’demo@qq.com’, body)..

SMTP.starttls(keyfile=None,certfile=None):The TLS security transfer mode is enabled, all SMTP instructions will be encrypted and transmitted, such as the use of Gmail’s SMTP service.

SMTP.quit():Disconnect the SMTP server link

SMTP.set_debuglevel(level):Set debug output level, value 1, 2 or True, send debug message to server

SMTP.send_message(msg,from_addr=None,to_addrs=None,mail_options=[],rcpt_options=[]):This is a convenient way to call messages using email.message.Message objects to use sendmail (), with the same meaning as sendmail (), and only MSG is a Message object; if from_aDDR is None or to_addrs is None, and send_message is filled with those parameters from the address extracted from the MSG head, from is set to the sender automatically, and TO is set to to_addrs.

Instance 1 implements simple mail sending:

import smtplib

from smtplib import SMTP
HOST="smtp.163.com"  #Defining the SMTP host
SUBJECT="test email form python"  #Defining mail topics
TO = "11111@163.com"   #Define mail recipients
FROM="22222@163.com"  #Define mail sender
text="python is test smtp"   #The contents of the message are encoded in characters or byte strings in the range of ASCII, so they cannot be written in Chinese.
BODY = '\r\n'.join((      #The content of the main body of the mail is combined with the sendmail method, and the paragraphs are separated by "\r\n".
    "From: %s" %"admin",
    "TO: %s" %TO,
    "subject: %s" %SUBJECT,
    "",
    text
))
server = SMTP()   #Create a SMTP object
server.connect(HOST,'25')  #Link SMTP host
server.login(FROM,"123")  #Mailbox account login
server.sendmail(FROM,TO,BODY) #Send mail
server.quit()  #Port SMTP link

Example 2: read the contents of the file to send the main body of the mail

import smtplib
from email.utils import formataddr
from email.mime.text import MIMEText

with open('textfile','rb') as fp:   #Read the content of the file
    msg=MIMEText(fp.read(),'plain','utf-8')   #Create a message object


msg['Subject'] = "emailMessage"
msg['From'] = formataddr(["Zhang San","920664709@163.com"])
msg['To'] = formataddr(["Li Si","920664709@163.com"])

try:
    server = smtplib.SMTP() # Create a SMTP () object
    server.connect("smtp.163.com","25") # Connecting the SMTP host by the connect method
    #server.starttls() # Start a safe transmission mode
    server.login("920664709@163.com","xxxxxx") # Checkout of mailbox account
    server.sendmail("92066@163.com","92066@163.com", msg.as_string()) # Mail sending
    server.quit() # Disconnect SMTP connections
    print("Email is successful!")
except Exception as e:
    print('Failure:'+str(e))

2、Handling mail MIME

Transmission of simple text through mail has been unable to meet our needs, for example, we often customize business quality reports, including HTML, images, sounds, and attachment formats in the mail body, and MIME (Multipurpose Internet Mail E)Xtensions, Multipurpose Internet mail extensions), as a new type of extended mail format, is a good complement to this, and more MIME knowledge is seen in https://docs.python.org/3/library/email.html. lowerIntroduce some commonly used MIME implementation classes in Python:

email.mime.base.MIMEBase(_maintype,_subtype,*,policy = compat32,** _ params ):

This is the base class for all MIME specific classes, _maintpe is the main Content-Type type (text or image), _subtype is the secondary type of Content-Type (plain or GIF), _parAMS is a key value dictionary parameter passed directly to Message.add_header.

filename1 = 'Picture.Pdf'
attachfile_base = MIMEBase('application', 'octet-stream')  #Creating the base object specified type
attachfile_base.set_payload(open(filename,'rb').read())  #Set my payload
attachfile_base.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename1) )
encoders.encode_base64(attachfile_base)
msg.attach(attachfile_base)

email.mime.multipart.MIMEMultipart(_subtype=’mixed’,boundary= None,_subparts = None,*,policy = compat32,** _ params )
The role is to generate the MIME object that contains multiple parts of the mail body, and the parameter _subtype specifies the optional three seed types to add to the “Content-type:multipart/subtype” header, respectively mixed, reLated, alternative, the default value is mixed. Define mixed implementation to build an email body with attachments; define related to build e-mail bodies that build embedded resources; and define alternative to build pure text and hypertext.Coexisting mail body; _subparts is the initial class of a class of payloads, and can be attached to the message by using the attach () method.

from email.mime.multipart import MIMEMultipart

msg1 = MIMEMultipart('mixed')  #Create an instance with an attachment
msg2 = MIMEMultipart('related')  #Creating an instance of embedded resources
msg3 = MIMEMultipart('alternative') #Creating pure text and hypertext instances

email.mime.application.MIMEApplication(_data, _subtype=’octet-stream’, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params):

Used to represent the main type of MIME message object application, _data is a string containing the original byte data, _subtype specifies the MIME subtype by default eight byte stream, _encoder is a callable function, it executes the actual encoding of the transmission data, usesSet_payload () changes the payload to the encoding form, the default encoding bit Base64, and uses the email.encoders module to see the built in code table.

filename = 'Resume.Pdf'
with open(filename,'rb') as f:
    attachfile = MIMEApplication(f.read())
attachfile.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachfile)

email.mime.audio.MIMEAudio (_audiodata[, _subtype[, _encoder]]):

Create mail body containing audio data, _audiodata contains byte string of raw binary audio data, _subtype audio type, and _encoder encoding.

from email.mime.audio import MIMEAudio

msgaudio = MIMEAudio(open('yishengsuoai.mp3','rb').read(),'plain')   #Text audio object

msgaudio.add_header('Content-Disposition','attachment',filename='text.mp3') #Extension Title type, file name
msg.attach(msgaudio) #Additional objects are added to the MSG

email.mime.image.MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]]):

MIMENonMultipartIn a subclass, a mail body containing picture data is created, and _imagedata is a byte string containing the original picture data; _sutype specifies the image subtype; _encoder specifies that a function internal coding default is: email.encoders.eNcode_base64 defaults to Base64 encoding

from email.mime.image import MIMEImage   #Importing the MIMEImage class

with open('test.png','rb') as fp:
    msgImage = MIMEImage(fp.read()) #Read a picture to assign a picture object

msgImage.add_header('Content-ID','imgid') #Expand the title field and value for the picture object
msg.attach(msgImage) #Add the image load to the MSG load

email.mime.text.MIMEText (_text[, _subtype[, _charset]]):

MIMENonMultipartIn a subclass, a mail body containing text data is created, _text is a string containing a message load, _subtype specifies a text type, and a string that supports the plain (default) or HTML type. _charset sets the character set, the parameter accepts oneCharset instance.

from email.mime.text import MIMEText

#Mail body to create text content
msg = MIMEText("python test email",'plain','utf-8')

#Create a mail body in HTML format
msg = MIMEText("<p>python test email</p><p><a href="http://www.demo.com">Link < /a> < /p>",'html','utf-8')

MIMEThe method of instance object:

  • as_string() :Returns the string information equivalent to __str__ (), str (MSG).
  • as_bytes() :Returns the byte information equivalent to __bytes__ (), bytes (MSG).
  • is_multipart() :To determine whether a list of message objects is a payload is to return True or False
  • set_unixfrom(unixfrom) :Set the message’s letter head to unixfrom as a string
  • get_unixfrom() :Return the message header. The default is None
  • attach(payload) :Adds a given payload to the current payload.
  • get_payload(i=None, decode=False) :Returns the current payload, which will be a list of Message.
  • set_payload(payload, charset=None) :The payload of the message object is set to payload.
  • set_charset(charset) ;Set the character set of the payload to charset
  • get_charset() :Return an instance of the Charset that is associated with the message payload
  • __len__() :Return the total number of titles, including repeated items
  • __contains__(name) :If the message object has a field named name, it returns true.
  • __getitem__(name) :Returns the value of the specified title field
  • __setitem__(name, val) :Add fields to messages with field names and value val.
  • __delitem__(name) :Remove all occurrences of the field with the name name from the header of the message.
  • keys() :Return a list of all the name of the message Title Field
  • values() :Return a list of all the value of the message field
  • items() :Return the title and value of the field that contains all the messages
  • add_header(_name, _value, **_params) :Expand header settings. _name is the header field to add, and _value is the value of the title.
msg.add_header('Content-ID','imgid')   #Set the picture ID
msg.add_header('Content-Disposition','attachment',filename='test.xlsx') #Add a title for the attachment
msg.add_header('Content-Disposition','attachment',filename=('utf-8','','Chinese title')) #You need to specify the code when adding non - ASCII characters
  • replace_header(_name,_value) :Replace the title

Please read the official documents for more

email.header.Header(s=None,charset=None):Create a string that can contain different character sets and conform to the MIME header.

Optional parameter: s is the initial Title Value, which is None by default, and can be appended to the title using the append () method. Charset specifies the character set.

from email.header import Header

msg['From'] = Header("Test mail comes from",'utf-8')

Additional tools: email.utils

email.utils.localtime(dt=None) :Back to the current time, the DT parameter is an instance of datetime

email.utils.formataddr(pair,charset=’utf-8′)  :pairIt is a header or list that returns the segmented titles and addresses, such as mailbox recipients nicknames and mailbox accounts.

from email.utils import formataddr
msg['From'] = formataddr(['Meslef','92066@163.com'])
msg['To'] = formataddr(['Anybody','92066@163.com'])

 3、Example

The common methods of Python’s smtplib and email modules are introduced. How do they divide their work in the process of mail customization and sending? We can understand email.mime as an extension of smtplib module mail content main body.It extends from original default support to pure text format to HTML, and supports attachment, audio, image and other formats. Smtplib is only responsible for mail delivery. Here are some examples of mail application in daily operation.

By introducing the MIMEText class of email.mime to implement the mail that supports HTML format, support all HTML elements, including tables, pictures, animations, CSS styles, forms, and so on.

(1)Customizing business data reports using HTML’s table

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/1 11:58
# @Author  : Py.qi
# @File    : fangwenliang.py
# @Software: PyCharm

import smtplib
from email.mime.text import MIMEText # Importing the MIMEText class

HOST = "smtp.qq.com" # Defining the SMTP host
SUBJECT = u" Official network flow data report" # Defining mail topics
TO = "92066@163.com" # Define mail recipients
FROM = "92066@qq.com" # Define mail sender
test = """
<body>
<table width="800" border="1" cellspacing="0" cellpadding="4">
<tr>
    <td bgcolor="#CECFAD" height="20" style="font-size:14px">* Official network data < aHref= "http://www.baidu.com" > more > > < /a> < /td>< /tr>< tR>< TD bgcolor= "#EFEBDE" height= "100" style= "font-size:13px" >1, daily access: < foNT color=red> 152433< /font>Number of visits: 23651Page browsing: 45123Number of clicks: 545122Data flow: 504Mb< br>2. State code information < br>& nbsp& nbsp; 500:105 404:3264 503:214< br>3. The visitor's browser information < br>& nbsp; &Amp; nbsp; IE:50% firefox:10% chrome:30% other:10%< br>4, page information < br>&Amp; nbsp; & nbsp; /index.php 42153< br>& nbsp; & nbsp; /view.php 21451< br>& nbsp; & nbsp; /login.php 5112< br>< /td>< /tr>< /Table>"""              
msg = MIMEText(test,"html","utf-8")  #Defining the subject content
msg['Subject'] = SUBJECT # Mail theme
msg['From']=FROM # Mail sender, mail head can be seen
msg['To']=TO # Mail recipients, mail headers can be seen
try:
    server = smtplib.SMTP() # Create a SMTP () object
    server.connect(HOST,"25") # Connecting the SMTP host by the connect method
    server.starttls() # Start a safe transmission mode
    server.login("92066@qq.com","iqcuwzhgmj") # Checkout of mailbox account
    server.sendmail(FROM, TO, msg.as_string()) # Mail sending
    server.quit() # Disconnect SMTP connections
    print("Email is successful!")
except Exception as e:
    print('Failure:'+str(e))

When sending pictures with mail, you need to introduce MIMEImage class and MIMEText class combination to realize data sending in graphic format, and assemble through MIMEMultipart class.

(2)Custom server performance report sending mail

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/1 11:58
# @Author  : Py.qi
# @File    : fangwenliang.py
# @Software: PyCharm

import smtplib
from email.mime.text import MIMEText # Importing the MIMEText class
from email.mime.multipart import MIMEMultipart  #Importing the MIMEMultipart class
from email.mime.image import MIMEImage   #Importing the MIMEImage class

HOST = "smtp.qq.com" # Defining the SMTP host
SUBJECT = u"System performance report" # Defining mail topics
TO = "92066@163.com" # Define mail recipients
FROM = "92066@qq.com" # Define mail sender

def addimg(src,imgid):   #Define picture reading function, parameter 1 is picture path, 2 is picture ID machine identifier.
    with open(src,'rb') as f:
        msgimage = MIMEImage(f.read())   #Read the picture content
    msgimage.add_header('Content-ID',imgid)  #The specified file is Content-ID, < img> in HTML, image SRC will be used.
    return msgimage

msg = MIMEMultipart('related')  #Create MIMEMultipart objects and use related to define embedded resource mails.

test = """  
<table width="600" border="0" cellspacing="0" cellpadding="4">
    <tr bgcolor="#CECFAD" height="20" style="font-size:14px">
        <td colspan=2>*System performance data < a href= "10.0.0.10" > more > > < /a> < /td>< /tr>< tr bgcoLor= "#EFEBDE" height= "100" style= "font-size:13px" >< td>< img src= "Cid:io ">"; photo address is transmitted by MIMEMultipart through ID.< /td>< td>< ImG src= "cid:key_hit" >< /td>< /tr>< tr bgcolor= "#EFEBDE" height= "" "100 "style=" font-size:13px ">< td>< img src= "cid:men" >< /td>< td>< img src= "cid:swap" >< /td>&lT; /tr>< /table>"""
msgtext = MIMEText(test,"html","utf-8") #Create the content of the Text object, including the picture < img>

msg.attach(msgtext)   #MIMEMultipartObject attached to the content of MIMEText
msg.attach(addimg("1.png",'io'))  #Additional picture content, IO points to the parameters in the HTML text.
msg.attach(addimg("2.png",'key_hit'))
msg.attach(addimg("3.png",'men'))
msg.attach(addimg("4.png",'swap'))

msg['Subject'] = SUBJECT # Mail theme
msg['From']=FROM # Mail sender, mail head can be seen
msg['To']=TO # Mail recipients, mail headers can be seen
try:
    server = smtplib.SMTP() # Create a SMTP () object
    server.connect(HOST,"25") # Connecting the SMTP host by the connect method
    server.starttls() # Start a safe transmission mode
    server.login("92066@qq.com","iqcuwzhgmj") # Checkout of mailbox account
    server.sendmail(FROM, TO, msg.as_string()) # Mail sending
    server.quit() # Disconnect SMTP connections
    print("Email is successful!")
except Exception as e:
    print('Failure:'+str(e))

(3)Mail with pictures and attachments

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/1 14:55
# @Author  : Py.qi
# @File    : attach_smtp.py
# @Software: PyCharm

import smtplib
from email.mime.text import MIMEText # Importing the MIMEText class
from email.mime.multipart import MIMEMultipart  #Importing the MIMEMultipart class
from email.mime.image import MIMEImage   #Importing the MIMEImage class
from email.mime.base import MIMEBase  #MIMEThe base class of the subclass
from email import encoders   #Import encoder

HOST = "smtp.qq.com" # Defining the SMTP host
SUBJECT = u"System performance report" # Defining mail topics
TO = "92066@163.com" # Define mail recipients
FROM = "92066@qq.com" # Define mail sender

def addimg(src,imgid):   #Define picture reading function, parameter 1 is picture path, 2 is picture ID machine identifier.
    with open(src,'rb') as f:
        msgimage = MIMEImage(f.read())   #Read the picture content
    msgimage.add_header('Content-ID',imgid)  #The specified file is Content-ID, < img> in HTML, image SRC will be used.
    return msgimage

msg = MIMEMultipart('related')  #Create MIMEMultipart objects and use related to define embedded resource mails.

#Create a MIMEText object with HTML elements including text and pictures.
msgtext = MIMEText("<font color=red> Weekly average delay chart of official website business: < br> < img src=\ "cid:weekly\" border=\ "1\" > < br> details are attached. < /font>","html","utf-8")

msg.attach(msgtext)   #Append the msgtext content to the MIMEMultipart object
msg.attach(addimg("1.png",'weekly')) #Attaching the content of the MIMEImage with the MIMEMultipart object

#Attachment file definition
#Create a MIMEText object and attach the form file (week.xlsx).
filename = 'week.xlsx'
attachfile = MIMEBase('applocation','octet-stream') #Create objects to specify primary and secondary types
attachfile.set_payload(open(filename,'rb').read()) #Set the message content as a payload
attachfile.add_header('Content-Disposition','attachment',filename=('utf-8','',filename))  #Extension Title Setting
encoders.encode_base64(attachfile)
msg.attach(attachfile) #Additional objects are added to the MSG


msg['Subject'] = SUBJECT # Mail theme
msg['From']=FROM # Mail sender, mail head can be seen
msg['To']=TO # Mail recipients, mail headers can be seen
try:
    server = smtplib.SMTP() # Create a SMTP () object
    server.connect(HOST,"25") # Connecting the SMTP host by the connect method
    server.starttls() # Start a safe transmission mode
    server.login("92066@qq.com","iqcuwzhgmj") # Checkout of mailbox account
    server.sendmail(FROM, TO, msg.as_string()) # Mail sending
    server.quit() # Disconnect SMTP connections
    print("Email is successful!")
except Exception as e:
    print('Failure:'+str(e))

View Code

(4)All mail format summarises

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/2 12:06
# @Author  : Py.qi
# @File    : coent_smtp.py
# @Software: PyCharm

import smtplib
from email.utils import make_msgid,formatdate
from email.mime.text import MIMEText #htmlFormat and text format mail
from email.mime.multipart import MIMEMultipart #Mail with multiple parts
from email.mime.image import MIMEImage #Picture format mail
from email.mime.audio import MIMEAudio  #Audio file object
from email.utils import formataddr   #Separation of headings and addresses
from email.header import Header   #Setting the title character set
from email import encoders  #Encoder
from email.mime.application import MIMEApplication  #The main type of MIME message object application
from email.mime.base import MIMEBase

# The sender address, the sender address created by the console.
username = 'service@gemail.com'
# The sender password, the sender password created through the console.
password = '*****'
# Custom reply address
replyto = '92066@qq.com'
# The addressee address or address list supports multiple recipients, up to 30.
rcptto = ['***', '***']

#Building the header structure of the letter
msg = MIMEMultipart('alternative')  #Create a multi - Part mail object
msg['Subject'] = Header('Custom letter theme', 'utf-8')
msg['From'] = formataddr([Header('Custom credit nickname','utf-8'),username])
msg['To'] = formataddr([Header('Custom credit nickname','utf-8'),rcptto])
msg['Reply-to'] = replyto
msg['Message-id'] = make_msgid() #Message-IDheader
msg['Date'] = formatdate()  #Date,


#Building text mail content
msg_text = MIMEText('Custom TEXT plain text part','plain','utf-8')
msg.attach(msg_text)
#Reading files to create mail content
with open('textfile','rb') as fp:   #Read the content of the file
    msg_text=MIMEText(fp.read(),'plain','utf-8')

#Building mail content in HTML format
msg_html = MIMEText("<h1>HTMLFormat mail < /h1>","html","utf-8")
msg.attach(msg_html)

#Build HTML format mail with picture content
html1 = "<div><img src='cid:imgid'></div>"
msg_html_img = MIMEText(html1,'html','utf-8')
msg.attach(msg_html_img)
with open("imgfile","rb") as f:
    msg_img = MIMEImage(f.read())
msg_img.add_header('Content-ID','imgid') #Extending the picture title
msg.attach(msg_img)

#Mail MIMEApplication with attachments
filename = 'Resume.Pdf'
with open(filename,'rb') as f:
    attachfile = MIMEApplication(f.read())
attachfile.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachfile)

#Mail MIMEApplication with multiple attachments
filenames = ['Resume.Pdf','Replica.Pdf']
for tmp in filename:
    with open(tmp,'rb') as f:
        attachfiles = MIMEApplication(f.read())
        attachfiles.add_header('Content-Disposition', 'attachment', filename=tmp)
        msg.attach(attachfiles)

#Mail MIMEBase with attachments
filename1 = 'Picture.Pdf'
attachfile_base = MIMEBase('application', 'octet-stream')  #Creating the base object specified type
attachfile_base.set_payload(open(filename,'rb').read())  #Set my payload
attachfile_base.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename1) )
encoders.encode_base64(attachfile_base)
msg.attach(attachfile_base)

#Creating an audio file
AUDIO_HTML = '''
    <p>this's audio file</p>
    <audio controls>
    <source src="cid:audioid" type="audio/mpeg">
    </audio>
'''
msg_test1 = MIMEText(AUDIO_HTML,'html','utf-8')
msg_audio = MIMEAudio(open('iphone.mp3','rb').read(),'plain')
msg_audio.add_header('Content-ID','audioid')
msg.attach(msg_test1)
msg.attach(msg_audio)
#The receipt of the mail can not be played, to be solved!

# Send mail
try:
    client = smtplib.SMTP()
    #You need to use SSL, so you can create a client
    #client = smtplib.SMTP_SSL()
    client.connect('smtp.163.com', 25)
    #Open the DEBUG mode
    client.set_debuglevel(1)
    client.login(username, password)
    client.sendmail(username, rcptto, msg.as_string())
    client.quit()
    print('email send success!')
except smtplib.SMTPConnectError as e:
    print('Mail failed, connection failed:', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
    print('Mail failure, authentication error:', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
    print('The mail sent failed and the sender was rejected:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
    print('The Mail failed and the recipient was rejected:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
    print('Mail sent failed, data reception refused:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
    print('Mail failed,', e.message)
except Exception as e:
    print('Send an exception to the mail,', str(e))

(5)Drawing lessons from others

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

class mailsender(object):
    _from = None
    _attachments = []

    def __init__(self,host,port):
        self.smtp = smtplib.SMTP()
        self.smtp_ssl = smtplib.SMTP_SSL()
        self.smtp.connect(host,port)

    def login(self, user, pwd):
        self._from = user
        print("login ...")
        self.smtp.login(user, pwd)

    def add_attachment(self, filename): #Add additional
        att = MIMEBase('application', 'octet-stream')
        att.set_payload(open(filename,'rb').read())
        att.add_header('Content-Disposition', 'attachment', filename = ('utf-8','',filename))
        encoders.encode_base64(att)
        self._attachments.append(att)

    def send(self, subject, content, to_addr):
        msg = MIMEMultipart('alternative')
        contents = MIMEText(content, 'plain', _charset ='utf-8')
        msg['subject'] = subject
        msg['from'] = self._from
        msg['to'] = to_addr
        for att in self._attachments:
            msg.attach(att)
        msg.attach(contents)
        try:
            self.smtp.sendmail(self._from, to_addr, msg.as_string())
            self.smtp.quit()
            print('Email is successful!')
        except Exception as e:
            print(str(e))

if __name__ == '__main__':
    emailtext,to_email = input('Mail message:').split()
    email = mailsender('smtp.163.com','25')
    email.login('92066@163.com','xxxxx')
    email.add_attachment('2.png')
    email.send('hello test',emailtext,to_email)

View Code

More contents refer to official documents: e-mail and MIME processing software package.

#################################Later to update the Django instance mail!

 

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *