Two kinds of Python send email instance explanation (Python email attachment can be implemented using the email module) _python

Source: Internet
Author: User
Tags assert imap rfc all mail python send email

You can use the Python email module to deliver messages with attachments.

SMTP (Simple Mail Transfer Protocol)
The message transfer agent (mail Transfer AGENT,MTA) program uses the SMTP protocol to send e-mail to the recipient's mail server. The SMTP protocol can only be used to send messages and not to receive messages. Most mail-sending servers (outgoing mail server) use the SMTP protocol. The default TCP port number for the SMTP protocol is 25.

An important feature of the SMTP protocol is its ability to relay mail. It works in two cases: one is that e-mail is transferred from the client to the server, and the other is transferred from one server to another server.

POP3 (Post Office Protocol) & IMAP (Internet message Access Protocol)
POP protocols and IMAP protocols are the two most common protocols used for mail reception. Almost all mail clients and servers support both protocols.

The POP3 protocol provides users with a simple, standard way to access mailboxes and obtain e-mail. Email clients using the POP3 protocol typically work by connecting to the server, getting all the information and saving it on the user host, removing the messages from the server, and then disconnecting. The default TCP port number for the POP3 protocol is 110.

The IMAP protocol also provides a convenient mail download service that allows users to read offline. An e-mail client using an IMAP protocol usually keeps the information on the server until the user explicitly deletes it. This feature allows multiple clients to manage a single mailbox at the same time. The IMAP protocol provides a summary browsing feature that allows users to decide whether to download a message after they have read all the time, subject, sender, size, etc. The default TCP port number for the IMAP protocol is 143.

Message Format (RFC 2822)
Each message has two parts: the message header and the body of the message, which are separated by a blank line.

The header of each field (field) includes two parts: The field name and the field value, separated by a colon. There are two fields to note: From and Sender fields. The From field indicates the author of the message, and the sender field indicates the sender of the message. If the From field contains more than one author, you must specify the sender field, and if the From field has only one author and the author and sender are the same, then the sender field should not be used, otherwise the From field and the sender field should be used concurrently.

The message body contains the contents of the message, and its type is indicated by the Content-type field of the message header. In the message format defined in RFC 2822, the message body is simply an ASCII-encoded sequence of characters.

MIME (Multipurpose Internet Mail Extensions) (RFC 1341)
MIME extended message format to support non-ASCII encoded text, non-text attachments, and mail bodies that contain multiple parts (multi-part).

Python Email Module

1. Class Email.message.Message

__GETITEM__,__SETITEM__ implements the Obj[key] form of access.
Msg.attach (playload): Adds playload to current MSG.
Msg.set_playload (playload): Sets the message body of the entire MSG object to Playload.
Msg.add_header (_name, _value, **_params): Add Headers field.
2. Class Email.mime.base.MIMEBase (_maintype, _subtype, **_params)
The base class for all MIME classes, which are subclasses of the Email.message.Message class.

3. Class Email.mime.multipart.MIMEMultipart ()

In the 3.0 version of the email module (Python 2.3-python 2.5), this class is located in email. Mimemultipart.mimemultipart.
This class is a direct subclass of Mimebase, which is used to generate MIME objects that contain multiple parts of the message body.

4. Class Email.mime.text.MIMEText (_text)

Use string _text to generate the body text of a MIME object.

Code implementation

Copy Code code 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[' Subject '] = 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 ()

Using Python's smtplib library to deliver mail

Copy Code code as follows:

Import Smtplib
Def sendmail ():
Try
Smtp=smtplib. SMTP (HOST)
Smtp.login (User,password) #登录邮箱
Smtp.sendmail (user+ "@" +profix,to,msg) #发送邮件
Smtp.quit ()
print ' Email send success '
Except Exception,e:
Print E
print ' email send failed. '

The message can be sent

Then learn a little definition msg
Python has several class libraries that generate rich msg formats
summarize a simple mimetext, you can edit many header information, or edit message format
from email. Mimetext Import Mimetext
Msg=mimetext ("content to send", "format, for example: Html,plain", "encoding, for example: Gb2312,utf-8")
msg[' from ']= ' The sender's name displayed in the message '
msg[' to ']= ' message displays the recipient's name '
msg[' Subject ']= ' message title '
None of these can be set

Related Article

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.