Python USES smtplib and the email module to send mail instances

  • 2020-04-02 13:36:59
  • OfStack

SMTP module

So many defined classes, we most commonly used or smtplib.SMTP class, on the specific use of the class:
The SMTP instance encapsulates an SMTP connection that supports all SMTP and ESMTP operation instructions. If the host and port parameters are defined, SMTP automatically calls the connect() method during initialization. If the connect() method fails, an SMTPConnectError exception is triggered. In a normal invocation, you should follow the steps connetc(), sendmail(), and quit().

SMTP module main methods

Let's take a look at the methods of this class:


SMTP.set_debuglevel(level)
 Set the output debug Debug information is not output by default. 
SMTP.docmd(cmd[, argstring])
 Send a command to smtp The server, 
SMTP.connect([host[, port]])
 Connect to the specified smtp Server, native by default 25 Port. Or you could write it as hostname:port In the form. 
SMTP.helo([hostname])
 use helo Instructions to the smtp The server confirms your identity. 
SMTP.ehlo([hostname])
 use ehlo Instructions to the esmtp The server confirms your identity. 
SMTP.ehlo_or_helo_if_needed()
 If not provided in previous session connection ehlo or helo Directive, this method call ehlo() or helo() . 
SMTP.has_extn(name)
 Determines whether the specified name is in smtp On the server. 
SMTP.verify(address)
 Determine if the email address is in smtp Exists on the server. 
SMTP.login(user, password)
 Login needs to be verified smtp Server, if not previously provided ehlo or helo The command will try first ESMTP the ehlo The instructions. 
SMTP.starttls([keyfile[, certfile]])
 make smtp The connection runs at TLS Patterns, all of them smtp The instructions are encrypted. 
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
 To send a message, this method requires some mail addresses and messages. 
SMTP.quit()
 Termination of smtp Session and close the connection. 

After searching and learning, I found that most of the Internet USES the method of sendmail of SMTP class to send emails. Let's take a look at this example:

Sendmail using sendmail


import smtplib
import time
from email.message import Message
from time import sleep
import email.utils
import base64

smtpserver = 'smtp.gmail.com'
username = 'username@gmail.com'
password = 'password '

from_addr = 'from@gmail.com'
to_addr = 'tooooooo@qq.com'
cc_addr = 'ccccccccc@qq.com'

time = email.utils.formatdate(time.time(),True)

message = Message()
message['Subject'] = 'Mail Subject'
message['From'] = from_addr
message['To'] = to_addr
message['Cc'] = cc_addr
message.set_payload('mail content '+time)
msg = message.as_string()

sm = smtplib.SMTP(smtpserver,port=587,timeout=20)
sm.set_debuglevel(1)
sm.ehlo()
sm.starttls()
sm.ehlo()
sm.login(username, password)

sm.sendmail(from_addr, to_addr, msg)
sleep(5)
sm.quit()

Email module

If you want to include attachments, HTML, pictures, etc., you need to use the email module and its submodules. Let's take a look at the email package, which manages email information and includes MIME and other message formats based on RFC 2822. The main feature of the email package is that it is implemented in separate modules that parse and generate email messages within it.

MIME messages are composed of two major parts, the header and body, in the case of mail. The header and body of the message are separated by a blank line.

The header contains important information about the sender, recipient, subject, time, MIME version, type of message content, and so on. Each message is called a domain, which consists of a domain name followed by ":" and the content of the message. The first line of the field must be "headed," meaning no whitespace characters (Spaces and tabs) on the left. Line continuation must begin with a blank character, and the first blank character is not inherent in the message itself.

The body of the message contains the Content of the message and its Type is indicated by the content-type field of the message header. The most common types are text/plain(plain text) and text/ HTML (hypertext). The body of the message is divided into segments, each containing the header and body, separated by a blank line. There are three common multipart types: multipart/mixed, multipart/related, and multipart/alternative.
There are many modules in the email package:


email.message
email.parser
email.generator
email.mime  create email and MIME object 
email.header
email.charset
email.encoders
email.ereors
email.utils
email.iterators

Let's take a look at email.mime, which is used to carry attachments, pictures, and audio in an email. Normally, you can generate a message object structure by parsing a file or a piece of text. You can also create a message structure from scratch. In fact, you can append a new message object to an existing message structure. You can create an object structure by creating a message instance, and then append attachments and headers to that structure. The email package provides some subclasses that make this easy.
The simulation carries pictures in the email content, as follows:

Include pictures in your email


from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import smtplib

from_mail = 'froooooooom@gmail.com'
to_mail = 'toooooooooo@qq.com'

msg = MIMEMultipart()
msg['From'] = from_mail
msg['To'] = to_mail
msg['Subject'] = 'python mail test'

body = 'test img send'
con = MIMEText('<b>%s</b>
<img alt="" src="cid:D:\10535-102.jpg" />
' % body,'html')
msg.attach(con)

img = MIMEImage(file('D:\10535-102.jpg','rb').read())
img.add_header('Content-ID','D:\10535-102.jpg')
msg.attach(img)

server = smtplib.SMTP('smtp.gmail.com')
server.docmd('ehol','tooooooo@gmail.com')
server.starttls()
server.login('username@gmail.com','password')

server.sendmail(from_mail,to_mail,msg.as_string())
server.quit()

Include attachments in your email

To send a message with an attachment, you first create an instance of MIMEMultipart(), then construct the attachment, if there are more than one, and then send it using smtplib.smtp
The simulation carries attachments in the email, as follows:


from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

# Create an instance with an attachment 
msg = MIMEMultipart()

txt = MIMEText(" This is the email in Chinese ",'plain','gb2312')    
msg.attach(txt)
# Construction accessories 1
att1 = MIMEText(open('d:\drcom.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="drcom.rar"'# Here, filename You can write whatever you want, what's the name, what's the name in the message 
msg.attach(att1)

# Construction accessories 2
att2 = MIMEText(open('d:\123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)

# Add header 
msg['to'] = 'tooooooo@qq.com'
msg['from'] = 'frommmmmmm@gmail.com'
msg['subject'] = 'hello world'

 

 
# Send E-mail 
try:
    server = smtplib.SMTP()
    server.connect('smtp.gmail.com')
    server.starttls()
    server.login('xxxxx@gmail.com','xxxxxxxxx')#XXX Is the user name, XXXXX For the password 
    server.sendmail(msg['from'], msg['to'],msg.as_string())
    server.quit()
    print ' Send a success '
except Exception, e: 
    print str(e)


Related articles: