Python_ use Smtplib and email modules to send mail __python

Source: Internet
Author: User
Tags assert base64 html form imap rfc all mail smtplib smtp
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.


Example of sending an email code:

#!/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[' u Ser '], server[' passwd '] def send_mail (server, fro, to, subject, text, files=[]): Assert type (server) = = Dict Ass ERT 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_he Ader (' 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 ()) s Mtp.close ()

Messages in the form of a file:

#!/usr/bin/env python3  
#coding: utf-8  

import smtplib from  
email.mime.text import Mimetext  
from Email.header Import Header  
  
sender = ' * * *  
receiver = ' * * *  
subject = ' python email test '  
smtpserver = ' SMT P.163.com '  
username = ' * * * '  
password = ' * * '  
  
msg = mimetext (' Hello ', ' text ', ' utf-8 ') #中文需参数 ' Utf-8 ', single-byte characters do not need c11/>msg[' Subject ' = Header (Subject, ' Utf-8 ')  
  
SMTP = Smtplib. SMTP ()  
smtp.connect (' smtp.163.com ')  
smtp.login (username, password)  
smtp.sendmail (sender, receiver , Msg.as_string ())  
Messages in HTML form

#!/usr/bin/env python3  
#coding: utf-8  

import smtplib from  
email.mime.text import mimetext  
  
sender = ' * * * '  
receiver = ' * * *  
subject = ' python email test '  
smtpserver = ' smtp.163.com '  
username = ' * * *  
Password = ' * * *  
  
msg = mimetext (' 

Messages with pictures in HTML form

#!/usr/bin/env python3  
#coding: utf-8  

import smtplib from  
email.mime.multipart import Mimemultipart  
From Email.mime.text import mimetext from  
email.mime.image import mimeimage  
  
sender = ' * * *  
receiver = ' * * * c7/>subject = ' python email test '  
smtpserver = ' smtp.163.com '  
username = ' * * * '  
password = ' * * *  
  
' Msgroot = Mimemultipart (' related ')  
msgroot[' Subject '] = ' test message '  
  
Msgtext = Mimetext (' <b>some <i>HTML</i> text</b> and an image.<br><br>good! ', ' HTML ', ' Utf-8 ')  
Msgroot.attach (msgtext)  
  
fp = open (' h:\\python\\1.jpg ', ' RB ')  
msgimage = Mimeimage (Fp.read ())  
fp.close ()  
  
msgimage.add_header (' Content-id ', ' <image1> ')  
Msgroot.attach (msgimage)  
  
SMTP = Smtplib. SMTP ()  
smtp.connect (' smtp.163.com ')  
smtp.login (username, password)  
smtp.sendmail (sender, receiver , msgroot.as_string ())  
smtp.quit ()

Messages with Attachments

#!/usr/bin/env python3  
#coding: utf-8  

import smtplib from  
email.mime.multipart import Mimemultipart  
From Email.mime.text import mimetext from  
email.mime.image import mimeimage  
  
sender = ' * * *  
receiver = ' * * * c7/>subject = ' python email test '  
smtpserver = ' smtp.163.com '  
username = ' * * * '  
password = ' * * *  
  
' Msgroot = Mimemultipart (' related ')  
msgroot[' Subject '] = ' test message '  
  
#构造附件  
att = mimetext (open (' h:\\ Python\\1.jpg ', ' RB '). Read (), ' base64 ', ' Utf-8 ')  
att["content-type"] = ' application/octet-stream ' att['  
Content-disposition "] = ' attachment; Filename= "1.jpg" '  
Msgroot.attach (att)  
          
smtp = Smtplib. SMTP ()  
smtp.connect (' smtp.163.com ')  
smtp.login (username, password)  
smtp.sendmail (sender, receiver , msgroot.as_string ())  
smtp.quit ()

Group Mail

#!/usr/bin/env python3  
#coding: utf-8 
 
import smtplib from  
email.mime.text import mimetext  
  
sender = ' * * * '  
receiver = [' * * * ', ' * * * ',......]  
Subject = ' python email test '  
smtpserver = ' smtp.163.com '  
username = ' * * * '  
password = ' * * * '  
  
msg = Mimetext (' Hello ', ' text ', ' utf-8 ')  
  
msg[' Subject ' = Subject  
  
smtp = Smtplib. SMTP ()  
smtp.connect (' smtp.163.com ')  
smtp.login (username, password)  
smtp.sendmail (sender, receiver , msg.as_string ())  
smtp.quit ()  

Messages that are contained in various elements

#!/usr/bin/env python3 #coding: Utf-8 import smtplib from Email.mime.multipart import Mimemultipart from EMAIL.MI Me.Text Import mimetext from email.mime.image import mimeimage sender = ' * * * receiver = ' * * * subject = ' Pytho n Email test ' smtpserver = ' smtp.163.com ' username = ' * * * password = ' * * * ' # Create message Container-the Co  
Rrect MIME type is multipart/alternative. msg = Mimemultipart (' alternative ') msg[' Subject '] = "Link" # Create the body of the message (a plain-text and a HT  
ML version). Text = "Hi!\nhow are You?\nhere is the link to you wanted:\nhttp://www.python.org" html = "" \  





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.