This article describes how to use the smtplib module in Python to process emails. it is a basic knowledge in Python beginners. if you need it, you can refer to it in Internet-based applications, programs often need to automatically send emails. For example, the registration system of a website will send an email to confirm registration when the user registers. when the user forgets the login password, it will retrieve the password through the email. The smtplib module is the client implementation of smtp (Simple Mail Transfer Protocol) in python. We can use the smtplib module to send emails easily. The following example uses less than 10 lines of code to send an email:
# Coding = gbk import smtplib smtp = smtplib. SMTP () smtp. connect ("smtp.yeah.net", "25") smtp. login ('username', 'password') smtp. sendmail ('From @ yeah.net ',' to @ 21cn.com ',' from: from@yeah.net/r/nTo: to@21cn.com/r/nSubject: this is a email from python demo/r/n/r/nJust for test ~ _~ ') Smtp. quit ()
This example is simple enough. ^_^! The following describes in detail the classes and methods in the pluplib module.
Smtplib. SMTP ([host [, port [, local_hostname [, timeout])
SMTP constructor indicates the connection to the SMTP server. through this connection, we can send commands to the smtp server to execute relevant operations (such as login and email sending ). This class provides many methods, which will be described below. All its parameters are optional. the host parameter indicates the smtp server host name. in the preceding example, the smtp host is "smtp.yeah.net". port indicates the smtp service port. the default value is 25; if the two parameters are provided when an SMTP object is created, the connect method is automatically called during initialization to connect to the server.
The smtplib module also provides SMTP_SSL and LMTP classes, which are basically the same as SMTP.
Methods provided by smtplib. SMTP:
SMTP.set_debuglevel(level)
Set whether to use the debugging mode. The default value is False, that is, non-debug mode, indicating that no debugging information is output.
SMTP.connect([host[, port]])
Connect to the specified smtp server. The parameters represent the smpt host and port respectively. Note: You can also specify the port number (for example, smpt.yeah.net: 25) in the host parameter so that the port parameter is unnecessary.
SMTP.docmd(cmd[, argstring])
Send commands to the smtp server. The optional parameter argstring indicates the command parameter. The following example uses the docmd method to send commands to the server to send emails (experiment passed on the smtp.yeah.net email server. Other email servers have not tried ):
Import smtplib, base64, time userName = base64.encodestring ('from '). strip () password = base64.encodestring ('password '). strip () smtp = smtplib. SMTP () smtp. connect ("smtp.yeah.net: 25") print smtp.doc md ('helo', 'from') print smtp.doc md ('auth login') print smtp.doc md (userName) print smtp.doc md (password) print smtp.doc md ('mail from :','
') Print smtp.doc md ('rcpt :','
') # Data command indicates the Mail content print smtp.doc md ('data') print smtp.doc md (''' from: from@yeah.net to: from@yeah.net subject: subject email body. ''') smtp. quit ()
SMTP. helo ([hostname])
Use the "helo" command to confirm the identity of the server. It is equivalent to telling the smtp server "who I am ".
SMTP. has_extn (name)
Determines whether the specified name exists in the server email list. For security reasons, smtp servers often block this command.
SMTP. verify (address)
Determines whether the specified email address exists on the server. For security reasons, smtp servers often block this command.
SMTP. login (user, password)
Log on to the smtp server. Currently, almost all smtp servers must verify that the user information is valid before sending emails.
SMTP. sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options])
Send an email. Note that the third parameter, msg is a string, indicating the mail. We know that an email generally consists of the title, sender, recipient, email content, attachments, etc. when sending an email, pay attention to the msg format. This format is defined in the smtp protocol. In the preceding example, the msg value is:
'''''From: from@yeah.net To: to@21cn.com Subject: test just for test'''
The meaning of this string indicates that the mail sender is "from@yeah.net", the recipient is "to@21cn.com", The Mail title is "test", and the Mail content is "just for test ". If you are careful, you may have questions: if the content of the email to be sent is complex, including pictures, videos, attachments, and other content, concatenate strings in MIME format, it will be very troublesome. Don't worry. python has taken this into consideration. It provides us with an email module that can easily send emails with images, videos, attachments, and other complex content. After introducing the smtplib module, I will briefly introduce the basic use of the email module.
SMTP. quit ()
Disconnecting the smtp server is equivalent to sending the "quit" command.
Email and its related submodules
The emial module is used to process mail messages, including MIME and other RFC 2822-based message documents. Using these modules to define mail content is very simple. Below are some common classes:
Class email. mime. multipart. MIMEMultipart: a collection of multiple MIME objects.
Class email. mime. audio. MIMEAudio: MIME audio object.
Class email. mime. image. MIMEImage: MIME binary file object.
Class email. mime. text. MIMEText: MIME text object.
Looking at the above explanation, I may feel confused. In fact, I have a superficial understanding of smtp and MIME. But most of the time, we only need to use it. The following is a simple example to demonstrate how to use these classes to send emails with attachments:
# Coding = gbk import smtplib, mimetypes from email. mime. text import MIMEText from email. mime. multipart import MIMEMultipart from email. mime. image import MIMEImage msg = MIMEMultipart () msg ['from'] = "from@yeah.net" msg ['to'] = 'To @ 21cn.com' msg ['subobject'] = 'Email for tesing' # Add Mail content txt = MIMEText ("This is the Mail content ~~ ") Msg. attach (txt) # add the binary attachment fileName = r'e:/PyQt4.rar 'ctype, encoding = mimetypes. guess_type (fileName) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype. split ('/', 1) att1 = MIMEImage (lambda f: (f. read (), f. close () (open (fileName, 'RB') [0], _ subtype = subtype) att1.add _ header ('content-disposition', 'attachment ', filename = fileName) msg. attach (att1) # send mail smtp = smtplib. SMTP () smtp. connect ('smtp .yeah.net: 25') smtp. login ('from', 'password') smtp. sendmail ('From @ yeah.net ',' to @ 21cn.com ', msg. as_string () smtp. quit () print 'email sent successfully'
For more examples, refer to the articles on using the smtplib module to process emails in Python!