For example, the use of the smtplib module in Python to process emails, pythonsmtplib
In Internet-based applications, applications 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: ',' <from@yeah.net> ') print smtp.doc md ('RCPT to:', '<from@yeah.net> ') # 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'
Is it easy. Simple is beautiful, and the problem is solved with the least code. This is Python.