This article describes how to use the Pythonemail module and the smtplib library to send emails. you can use the Python email module to send emails with attachments.
SMTP (Simple Mail Transfer Protocol)
The Mail Transfer Agent (MTA) program uses the SMTP protocol to send emails to the recipient's Mail server. The SMTP protocol can only be used to send mails and cannot be used to receive mails. Most email sending servers use the SMTP protocol. The default TCP port number of SMTP protocol is 25.
An important feature of the SMTP protocol is its ability to transmit mails through relay. It works in two situations: one is the transmission of email from the client to the server, and the other is the transmission from one server to another.
POP3 (Post Office Protocol) & IMAP (Internet Message Access Protocol)
POP protocol and IMAP Protocol are the two most common protocols used for mail receiving. Almost all mail clients and servers support these two protocols.
The POP3 protocol provides users with a simple and standard way to access their email addresses and obtain emails. The mail client that uses POP3 protocol usually works in the process of connecting to the server, getting all information and saving it on the user host, deleting the messages from the server, and then disconnecting. The default TCP port number for POP3 is 110.
The IMAP protocol also provides a convenient mail download service, allowing users to read offline. The email client that uses the IMAP protocol usually keeps the information on the server until the user explicitly deletes it. This feature allows multiple clients to manage one mailbox at a time. The IMAP protocol provides the abstract browsing function, allowing users to determine whether to download after reading the arrival time, topic, Sender, size, and other information of all emails. The default TCP port number of the IMAP protocol is 143.
Email Format (RFC 2822)
Each mail has two parts: the Mail header and the Mail body, which are separated by a blank line.
Each Field in the mail header consists of two parts: Field name and Field value, which are separated by colons. Note the following two fields: From and Sender. The From field specifies the Sender of the email, and the Sender field specifies the Sender of the email. If the From field contains more than one author, you must specify the Sender field. if the From field has only one author and the author is the same as the Sender, you should not use the Sender field, otherwise, use both the From field and the Sender field.
The Mail body contains the Content of the mail. its Type is specified by the Content-Type field in the mail header. In the Mail format defined in RFC 2822, the Mail body is only a string of ASCII characters.
MIME (Multipurpose Internet Mail Extensions) (RFC 1341)
MIME extended message format. it is used to support non-ASCII text, non-text attachments, and multi-part body.
Python email module
1. class email. message. Message
_ Getitem __,__ setitem _ implements access in the obj [key] format.
Msg. attach (playload): add playload to the current Msg.
Msg. set_playload (playload): sets the message body of the entire Msg object to playload.
Msg. add_header (_ name, _ value, ** _ params): add the mail header field.
2. class email. mime. base. MIMEBase (_ maintype, _ subtype, ** _ params)
The base class of all MIME classes, which is a subclass of the email. message. Message class.
3. class email. mime. multipart. MIMEMultipart ()
In the email module (Python 3.0-Python 2.3) of version 2.5, this class is located in email. MIMEMultipart. MIMEMultipart.
This class is a direct subclass of MIMEBase. it is used to generate MIME objects of mail bodies containing multiple parts.
4. class email. mime. text. MIMEText (_ text)
Use string _ text to generate the subject text of the MIME object.
Code implementation
The code is as follows:
! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
From email. mime. multipart import MIMEMultipart
From email. mime. base import MIMEBase
From email. mime. text import MIMEText
# Python 2. 3. *: email. Utils email. Encoders
From email. utils import COMMASPACE, formatdate
From email import encoders
Import OS
# Server ['name'], server ['user'], server ['passwd']
Def send_mail (server, fro, to, subject, text, files = []):
Assert type (server) = dict
Assert type (to) = list
Assert type (files) = list
Msg = MIMEMultipart ()
Msg ['from'] = fro
Msg ['subobject'] = Subject
Msg ['to'] = COMMASPACE. join (To) # COMMASPACE = ','
Msg ['Date'] = formatdate (localtime = True)
Msg. attach (MIMEText (text ))
For file in files:
Part = MIMEBase ('application', 'octet-stream') # 'octet-Stream': binary data
Part. set_payload (open (file, 'RB'. read ()))
Encoders. encode_base64 (part)
Part. add_header ('content-disposition', 'attachment; filename = "% s" '% OS. path. basename (file ))
Msg. attach (part)
Import smtplib
Smtp = smtplib. SMTP (server ['name'])
Smtp. login (server ['user'], server ['passwd'])
Smtp. sendmail (fro, to, msg. as_string ())
Smtp. close ()
Use python's smtplib library to send emails
The code is as follows:
Import smtplib
Def sendmail ():
Try:
Smtp = smtplib. SMTP (HOST)
Smtp. login (USER, PASSWORD) # logon email
Smtp. sendmail (USER + "@" + PROFIX, TO, MSG) # send mail
Smtp. quit ()
Print 'email send success'
Except t Exception, e:
Print e
Print 'email send failed .'
The email can be sent.
Then I learned how to define msg.
Several class libraries in python generate rich msg formats
To sum up a simple MIMEText, you can edit a lot of mail header information or edit the Mail format
From email. MIMEText import MIMEText
Msg = MIMEText ("content to be sent", "format, for example: html, plain", "encoding, for example: gb2312, UTF-8 ")
Msg ['from'] = 'sender's name displayed in the mail'
Msg ['to'] = 'recipient's name displayed in the mail'
Msg ['subobject'] = 'mail title'
None of these can be set.