Examples of how the Smtplib module in Python handles e-mail usage

Source: Internet
Author: User
Tags base64 mail port number smtplib smtp in python

This article mainly introduces examples of Python smtplib module to handle the use of e-mail, is the basics of Python introductory learning, need friends can refer to the

In internet-based applications, programs often need to send e-mail automatically. For example: A website registration system will send a message to confirm registration when the user registers; When the user forgets to login the password, through the mail to retrieve the password. The Smtplib module is a client-side implementation of the SMTP (Simple Mail Transfer Protocol) in Python. We can use the Smtplib module to easily send email. The following example uses less than 10 lines of code to send an e-mail message:

?

1 2 3 4 5 6 7 8 9 #coding =GBK import Smtplib smtp = Smtplib. SMTP () smtp.connect ("Smtp.yeah.net", "M") 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 classes and methods in the Stmplib module are described in detail below.

Smtplib. SMTP ([host[, port[, local_hostname[, timeout]]]

The SMTP class constructor, which represents the connection to the SMTP server, through which we can send instructions to the SMTP server to perform related operations such as landing, sending mail. This class provides a number of methods, which are described below. All of its parameters are optional, where the host parameter represents the SMTP server host name, and the SMTP host in the example above is "Smtp.yeah.net";p ort the port that represents the SMTP service, which defaults to 25; If these two parameters are provided when the SMTP object is created, The Connect method is automatically invoked at initialization time to connect to the server.

The Smtplib module also provides SMTP_SSL classes and LMTP classes, which are basically consistent with SMTP.

Smtplib. Methods provided by SMTP:

?

1 Smtp.set_debuglevel (Level)

Sets whether the is debug mode. The default is false, which is not debug mode, which means that no debugging information is exported.

?

1 Smtp.connect ([host[, Port]])

Connects to the specified SMTP server. The parameters represent Smpt hosts and ports, respectively. Note: You can also specify a port number (such as: SMPT.YEAH.NET:25) in the host parameter, so there is no need to give the port parameter.

?

1 Smtp.docmd (cmd[, argstring])

Send instructions to the SMTP server. An optional parameter argstring a parameter representing the instruction. The following example simply sends instructions to the server by calling the DoCmd method to send the message (test pass on the Smtp.yeah.net mail server). No other mail server has tried it):

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22 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.docmd (' helo ', ' from ') print smtp.docmd (' auth login ') print Smtp.docmd (userName) print smtp.docmd (password) print smtp.docmd (' Mail from: ', ' <from@yeah.net> ') print Smtp.docmd (' rcpt TO: ', ' <from@yeah.net> ') #data instruction indicates that the message content print smtp.docmd (' data ') print smtp.docmd (' "' From: From@yeah.net to:from@yeah.net subject:subject Email body. "") Smtp.quit ()

Smtp.helo ([hostname])

Use the "helo" directive to confirm identities to the server. The equivalent of telling the SMTP server "who I am".

Smtp.has_extn (name)

Determines whether the specified name exists in the server mailing list. For security reasons, the SMTP server tends to block the directive.

Smtp.verify (Address)

Determines whether the specified mail address exists on the server. For security reasons, the SMTP server tends to block the directive.

Smtp.login (user, password)

Log on to the SMTP server. Almost all SMTP servers now have to verify that the user information is legitimate before they are allowed to send mail.

Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, Rcpt_options])

Send the message. Here's the third argument, MSG is a string that represents the message. We know that the mail generally by the title, sender, recipient, email content, attachments, etc. constitute, send the message, pay attention to the format of MSG. This format is the format defined in the SMTP protocol. In the above example, the value of MSG is:

?

1 2 3 4 5 "' From:from@yeah.net to:to@21cn.com subject:test just for test '

The meaning of this string means that the message sender is "From@yeah.net", the recipient is "to@21cn.com", the message title is "test" and the message content is "just for test". Careful you may ask: if the content of the message to send is very complex, including pictures, videos, attachments and other content, in MIME format to stitching strings, will be a very troublesome thing. Don't worry, Python has taken this into account, providing us with an email module that allows you to easily send messages with complex content such as pictures, videos, attachments, and more. After introducing the Smtplib module, I will briefly introduce the basic use of the email module.

Smtp.quit ()

Disconnecting from the SMTP server is equivalent to sending a "quit" directive.

Email and related sub modules

The Emial module is used to process mail messages, including MIME and other RFC 2822-based message documents. Using these modules to define the content of the message is very simple. Here 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 may feel foggy, in fact, my understanding of SMTP, MIME is also very superficial. But most of the time, we just have to use it. Here is a simple example of how to use these classes to send messages with attachments:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The #coding =gbk import Smtplib, mimetypes from Emai L.mime.text Import mimetext from Email.mime.multipart import mimemultipart from email.mime.image import mimeimage   m sg = Mimemultipart () msg[' from '] = "from@yeah.net" msg[' to '] = ' to@21cn.com ' msg[' Subject '] = ' email for tesing '   #添 Add mail Content txt = mimetext ("This is the mail content ~ ~") Msg.attach (TXT)   #添加二进制附件 fileName = R ' E:/pyqt4.rar ' CType, encoding = Mimetypes.gu Ess_type (FileName) If CType is None or encoding are 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_he Ader (' content-disposition ', ' attachment ', filename = filename) Msg.attach (ATT1)   #发送邮件 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 ' mail sent successfully '

is not very simple. Simplicity is beauty, and using the least amount of code to solve the problem is python. For more information on Smtplib, please refer to the Python manual smtplib module.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.